Domenico Domenico - 4 months ago 26
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.


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* ){
 int B=pix.val[0];
 int G=pix.val[1];
 int R=pix.val[2];

 char name[30];
    putText(image,name, Point(10,130) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    putText(image,name, Point(10,170) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    putText(image,name, Point(10,210) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    putText(image,name, Point(10,300) , FONT_HERSHEY_SIMPLEX, .7, Scalar(0,255,0), 2,8,false );

    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 );


  return 0;


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));

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