Get White Pixel Coordinates (OpenCV)

In OpenCV (C ++), I have a b & w image in which some shapes are filled with white (255). Knowing this, how can I get the coordinate points in the image, where are the abstracts of objects? I am interested in getting all the white pixel 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());
+4
source share
2 answers

there is a built-in function for this cv :: findNonZero

Returns a list of non-zero pixel locations.

(, , cv::threshold(), cv::compare(), >, == ..) cv::Mat std::vector<cv::Point>

:

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);

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];
+7

. , u.

 for(int i = 0 ;i <image.rows() ; i++){// image:the binary image
                for(int j = 0; j< image.cols() ; j++){
                    double[] returned = image.get(i,j); 
                    int value = (int) returned[0]; 
                    if(value==255){
                    System.out.println("x: " +i + "\ty: "+j);//(x,y) coordinates
                    }
                }

            }
0

Source: https://habr.com/ru/post/1625727/


All Articles