Search code examples
c++opencvmatrixbackground-imagepixel

OpenCV: read matrix value


I want to count the number of white points in a background image which is only black and white. I have a code like this:

int count = 0; 
for ( int j = 0; j < Image.rows; j ++ )
    {
    for ( int i = 0; i < Image.cols; i ++ )
        {
            if ( Image.at<int>(i,j) >= 150 )
            {
                count ++ ;
            }
        }
    }

For some reason, the above code doesn't work, it just stops reacting. I checked, and the line" if ( Image.at(i,j) >= 150 ) " causes the problem. My "Image" is a "cv::Mat", with "CV_8UC3" type. Is there someone can help me? Thank you.


Solution

  • In addition to my comment to Robin's answer, your error is that you try to access an image of CV_8UC3 type as ints. If you want to check grey levels, do something like this (note the "unsigned char" instead of "int", as in Robin's answer).

    cv::Mat greyscale;
    cv::cvtColor(image,grayscale,CV_RGB2GRAY);
    // either, most elegant:
    int count = cv::countNonZero(greyscale >= 150);
    // or, copied from Robin's answer:
    int count = 0;
    for(int i = 0; i < greyscale.rows; ++i) {
        const unsigned char* row = greyscale.ptr<unsigned char>(i);
        for(int j = 0; j < greyscale.cols; j++) {
            if (row[j] >= 150)
                ++count;
        }
    }