1

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.

Domenico
  • 292
  • 2
  • 10
  • 26

1 Answers1

3

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; 
Community
  • 1
  • 1
Haris
  • 13,645
  • 12
  • 90
  • 121
  • I'm sorry, but this solution works with grey or color images. I have a binary thresholded image, and in runtime opencv create an error of addressing with the function "image.at for binary image. Can you tell me how access pixels value on a binary image? I've searched on internet and opencv guide, but example it's always for grey or color images... – Domenico Dec 05 '13 at 07:14
  • `binary.at(cv::Point2i(u,v)) = 255;` works to *set* the elements of a binary. I did not have luck with the other methods on a binary either. `(u, v)` are my `int` pixel coordinates and the `mat` was initialized as `cv::Mat binary(cv::Mat::zeros(mask_size, CV_8UC1));` – Patrick K May 05 '14 at 03:58