1
votes

I want to ask a question: I have to check the value time by time of a pixel (X,Y) in a binary thresholded OpenCV Mat image.

I have to check if the pixel at the X,Y that I want to verify is black or white (0 or 255)...how is the best method to do this thing?

I have searched and read about direct method (Get2D) or with pointers..but it isn't so clear for me...Image are binary, thresholded and eroded/dilated before...

Can someone post me an example of code of function that I've to use to do this thing?

4

4 Answers

3
votes

If you check the same pixel all the time, do it as @Xale says:

mat.at<unsigned char>(x,y) // assuming your type is CV_8U

If you have to do it for several pixels, get the offset of the row first and access the column later:

unsigned char *row = mat.ptr<unsigned char>(y);
// access now row[x1], row[x2]...

There is one more option that is only valid if you only want a single pixel and if all the operations on the image are done on the same allocated memory (it depends on your code and the opencv functions you call). In that case, you can get the pointer to that pixel once, and access it when you need:

unsigned char *px = mat.ptr<unsigned char>(y) + x;
...
unsigned char current_value = *px;
2
votes

You have to refer to this nice tutorial for accessing cv::Mat elements:

http://docs.opencv.org/doc/tutorials/core/mat_the_basic_image_container/mat_the_basic_image_container.html

There are different ways to achieve it. The main problem when you access the element is to understand the data type of the matrix/image. In you case, if the mat is a binary black and white probab it is of the type CV_8U, and my advice is always check for the type to be sure. Plus, playing with types get you more control on the knowledge of what you're dealing with.

One of the easiest method for accessing pixels is cv::Mat::at that is a template method, and it needs to specify the type, that, if your mati is CV_8U is uchar.

1
votes

the easy way:

int n = cv::countNonZero(binary_mat);

the hard way:

for ( int i=0; i<mat.rows; i++ )   
{
    for ( int j=0; j<mat.cols; j++ )
    {
        uchar pix = mat.at<uchar>(i,j);
        ...
1
votes

Hers is a link to another stackoverflow answer. Anyway short answer is

mat.at<Type>(x,y)

where Typeis the type of data stored in the matrixelements. In your case unsigned char