0
votes

I have a problem in OpenCV C++. I read in an image from file and use the threshold-function to get a binary image. After that I want to access the pixel values of the thresholded image.

PROBLEM: The Mat::data array of the thresholded image is 0.

I use threshold(src, img, 220, 255, CV_THRESH_BINARY); with src and img beig cv::Mat.

After that call in the img::data = " "

Here is my code:

// read image source    
Mat src = imread("image.png", CV_LOAD_IMAGE_COLOR);
if(src.empty())
{   
    return -1;
}

cvtColor(src,src,CV_RGB2GRAY);

threshold(src, src, 220, 255, CV_THRESH_BINARY );

    int line[1200];
int lineCount = 0;

for(int i=src.rows; i>src.rows/2; i-=10)    
{
    uchar* rowi = src.ptr(i-1);

    int columnCount = 0;
    // begin on the left of the image
    for(int j=0; j<src.cols; j++)
    {
        uchar grayscale = src.at<uchar>(rowi[j]);   

        // write data to array
        line[columnCount] = grayscale;

        columnCount++;
    }
}

I think the problem might be about cv::Mat with referencing and copying Mat::data:

Thanks for your help!

1
It's unclear exactly what your problem is. What do you mean when you say The Mat::data array ... is 0? is the pointer NULL? Are all the values zero? Also, what is the problem you're trying to solve? I'm confident there is a better solution than using nested loops.Aurelius

1 Answers

0
votes

I suppose you have checked that your image.png (after having been converted to grayscale) contains values higher than 220?

You may want to try to perform cvtColor as a non-in-place operation, as it might not properly support in-place conversion (see https://stackoverflow.com/a/15345586/19254). This you would do for example like this:

Mat dst;
cvtColor(src, dst, CV_RGB2GRAY);

... and then do threshold on dst. Alternatively, you could read the image into memory in grayscale mode to begin with (second parameter to imread can be CV_LOAD_IMAGE_GRAYSCALE), in which case the cvtColor call is not necessary.

Between each call, you can imwrite your image to disk in order to find out which step is not working as expected.