获取白色像素点的坐标(OpenCV)

7
在OpenCV(C++)中,我有一张黑白图像,其中一些形状填充为白色(255)。在此情况下,如何获得图像中这些对象的坐标点?我想获取所有白色像素的坐标。是否有比这更简洁的方法?
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());
2个回答

14

有一个内置函数可以实现这个功能 cv::findNonZero

返回非零像素的位置列表。

给定一个二进制矩阵(很可能是从诸如cv :: threshold()cv :: compare()> == 等操作返回的),将所有非零索引作为cv :: Matstd :: 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];

-2
你可以使用这个方法来获取白色像素.. 希望能对你有所帮助。
 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
                    }
                }

            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接