c++opencvimage-processing

Get List of Black Pixel of a cv::Mat


I' am actually working with a cv::Mat with B&W pixels. I'am searching for a way to get a list of my black point in this Mat.

Does someone know how to do such thing ?

I want to do that because I want to detect the bounding rect of this points. (The best is to get them back in a vector)

somekind of :

cv::Mat blackAndWhite;
std::vector<cv::Point> blackPixels = MAGIC_FUNCTION(blackAndWhite);

Thanks for your help.

Edit: I want to precise that I want the best practices, the more Opencv compliant as possible.


Solution

  • You can traverse the cv::Mat to check the pixels that are 0, and get the x and y coordinates from the linear index if the matrix is continuous in memory:

    // assuming your matrix is CV_8U, and black is 0
    std::vector<cv::Point> blackPixels;
    unsigned int const *p = blackAndWhite.ptr<unsigned char>();
    for(int i = 0; i < blackAndWhite.rows * blackAndWhite.cols; ++i, ++p)
    {
      if(*p == 0)
      {
        int x = i % blackAndWhite.cols;
        int y = i / blackAndWhite.cols;
        blackPixels.push_back(cv::Point(x, y));
      }
    }