Get coordinates of white pixels (OpenCV)

karl71 picture karl71 · Jan 24, 2016 · Viewed 15.1k times · Source

In OpenCV (C++) I have a b&w image where some shapes appear filled with white (255). Knowing this, how can I get the coordinate points in the image where theses objects are? I'm interested on getting all the white pixels coordinates.

Is there a cleaner way than this?

std::vector<int> coordinates_white; // will temporaly store the coordinates where "white" is found 
for (int i = 0; i<img_size.height; i++) {
    for (int j = 0; j<img_size.width; j++) {
        if (img_tmp.at<int>(i,j)>250) {
            coordinates_white.push_back(i);
            coordinates_white.push_back(j);
        }
    }
}
// copy the coordinates into a matrix where each row represents a *(x,y)* pair
cv::Mat coordinates = cv::Mat(coordinates_white.size()/2,2,CV_32S,&coordinates_white.front());

Answer

sturkmen picture sturkmen · Jan 24, 2016

there is a built-in function to do that cv::findNonZero

Returns the list of locations of non-zero pixels.

Given a binary matrix (likely returned from an operation such as cv::threshold(), cv::compare(), >, ==, etc) returns all of the non-zero indices as a cv::Mat or std::vector<cv::Point>

For example:

cv::Mat binaryImage; // input, binary image
cv::Mat locations;   // output, locations of non-zero pixels
cv::findNonZero(binaryImage, locations);
// access pixel coordinates
Point pnt = locations.at<Point>(i);

or

cv::Mat binaryImage; // input, binary image
vector<Point> locations;   // output, locations of non-zero pixels
cv::findNonZero(binaryImage, locations);
// access pixel coordinates
Point pnt = locations[i];