userXktape
userXktape

Reputation: 227

How to store point co-ordinates in vector data type in opencv?

I have a Mat object (CV_8UC1) which is a binary map with 1's on some positions and zeros otherwise.I want to create a vector which stores the co-ordinates of the points where the Mat is 1.Any suggestions on how to go about it. I know that I can loop around the image and check points with the following code

for( int p = 1; p <= img.rows; p++ )
    { for( int q = 1; q <= img.cols; q++ )
        {
            if(  img.at<uchar>(p,q) == 1 )
            {
                //what to do here ? 
            }
        }
    }

Also, I need the co-ordinates to be single precision floating point numbers.This is to use it as an input for another function which requires vectors. Please gimme a hint.I am not familiar with vector data types and STL.

Upvotes: 1

Views: 1805

Answers (1)

Sunreef
Sunreef

Reputation: 4542

If you want to find all non-zero coordinates in a binary map with OpenCV, th ebest is to use findNonZero.

Here is an example of how to use it (with a dummy matrix but you get the idea):

cv::Mat img(100, 100, CV_8U, cv::Scalar(0));
img.at<uchar>(50, 50) = 255;
img.at<uchar>(70, 50) = 255;
img.at<uchar>(58, 30) = 255;

cv::Mat nonZeroes;

cv::findNonZero(img, nonZeroes);

std::vector<cv::Point2f> coords(nonZeroes.total());

for (int i = 0; i < nonZeroes.total(); i++) {
    coords[i] = nonZeroes.at<cv::Point>(i);
}

Upvotes: 1

Related Questions