Domenico Domenico - 17 days ago 8
C++ Question

How access to a pixel value in a binary Mat image?

I'm using Visual C++ and OpenCV.

I want to ask, how can I access to a pixel element in a Mat in OpenCV.

I mean, I want to verify in a binary Mat image if a pixel it's 1 or 0...images is binary threshold...

how can I do to access to a pixel, with x and y (or rows and coloumn), and verify this value?

Can you help me? Thanks in advance.

Answer

For Mat element access you can refer OpenCV official Doc and these link1, link2 might be helpful

And here is a simple code that access pixel value according to your mouse position and display the pixel value.

#include <iostream>
#include <stdio.h>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;
 Mat image, src;
 char window_name[20]="Pixel Value Demo";

void onMouse( int event, int x, int y, int f, void* ){
 image=src.clone();
 Vec3b pix=image.at<Vec3b>(y,x);
 int B=pix.val[0];
 int G=pix.val[1];
 int R=pix.val[2];


 char name[30];
    sprintf(name,"R=%d",R);
    putText(image,name, Point(10,130) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"G=%d",G);
    putText(image,name, Point(10,170) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"B=%d",B);
    putText(image,name, Point(10,210) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"X=%d",x);
    putText(image,name, Point(10,300) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    sprintf(name,"Y=%d",y);
    putText(image,name, Point(10,340) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );
 imshow( window_name, image );
}



int main( int argc, char** argv )
{
  namedWindow( window_name, CV_WINDOW_AUTOSIZE );

  src = imread( "ball.jpg");
  imshow( window_name, src );

  setMouseCallback( window_name, onMouse, 0 );

  waitKey(0);

  return 0;
}

Edit:-

For binary image you can access pixel value with Mat::at(row,col) method.

In below example show how to do this. Here the image is of type uchar.

 Mat src(480,640,CV_8UC1,Scalar(0));
 circle(src,Point(src.cols/2,src.rows/2),100,Scalar(255),-1,8,0);

 int pix=(int)src.at<uchar>(src.rows/2,src.cols/2);
 cout<<pix<<endl; 
Comments