OpenCV - locations of all non-zero pixels in binary image

前端 未结 3 975
梦如初夏
梦如初夏 2021-01-01 22:52

How can I find the locations of all non-zero pixels in a binary image (cv::Mat)? Do I have to scan through every pixel in the image or is there a high level OpenCV function(

3条回答
  •  太阳男子
    2021-01-01 23:10

    I placed this as an edit in Alex's answer, it did not get reviewed though so I'll post it here, as it is useful information imho.

    You can also pass a vector of Points, makes it easier to do something with them afterwards:

    std::vector locations;   // output, locations of non-zero pixels 
    cv::findNonZero(binaryImage, locations);
    

    One note for the cv::findNonZero function in general: if binaryImage contains zero non-zero elements, it will throw because it tries to allocate '1 x n' memory, where n is cv::countNonZero, and n will obviously be 0 then. I circumvent that by manually calling cv::countNonZero beforehand but I don't really like that solution that much.

提交回复
热议问题