2016-01-24 715 views
4

在OpenCV(C++)中,我有一個圖像,其中一些形狀顯示爲白色(255)。知道這一點,我怎樣才能得到這些對象在圖像中的座標點?我對獲取所有白色像素座標感興趣。獲取白色像素座標(OpenCV)

有沒有比這更清潔的方法?

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

回答

7

有一個內置的功能,要做到這一點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]; 
0

,你可以用這個方法來獲得白色像素..希望它會幫助你。

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 
        } 
       } 

      }