AlcherBlack
AlcherBlack

Reputation: 13

Checking if a pixel is black in a grayscale image (OpenCV)

I need to figure out if any given pixel is black or white on a gray-scale image that I put through a thresholding algorithm before that. The image becomes basically blobs of black on a white background.

Mat falsetest;

...

cv::cvtColor(detected_edges, falsetest, CV_BGR2GRAY);    
threshold(falsetest, falsetest,128, 255,THRESH_BINARY);

...

printf("x:%d y:%d %d\n",x,y,falsetest.at<uchar>(x,y));

I expected the results to be either 0 or 255, however, that is not the case. The output for different pixels looks something like this:

x:1259 y:175 111
x:1243 y:189 184
x:1229 y:969 203
x:293 y:619 255
x:1123 y:339 183

Am I trying to do this in a wrong way, or does it seem that the error lies elsewhere?

Upvotes: 1

Views: 2759

Answers (3)

AlcherBlack
AlcherBlack

Reputation: 13

I have finally figured out what the problem was. I thought that when I called

cv::cvtColor(detected_edges, falsetest, CV_BGR2GRAY); 

all the matrix data was copied to falsetest. However, it seems that it was not the case, and when I proceeded to modify detected_edges, falsetest also became contaminated. Cloning the matrix solved the problem.

Upvotes: 0

R&#233;gis B.
R&#233;gis B.

Reputation: 10618

Are you sure that falsetest contains uchar pixels, and not floats? In such case, you would need to access values of falsetest by:

falsetest.at<float>(x,y)

Upvotes: 1

sylvain.joyeux
sylvain.joyeux

Reputation: 1699

The CV code looks good. However, you are using %d in printf to display a uchar.

Either use %hhd or do

static_cast<int>(falsetest.at<uchar>(x,y)).

Upvotes: 0

Related Questions