1

I'm a beginner in OpenCV and would like to print in my console the specific value of a pixel (RGB format) that I define by clicking on it.

After some searches I managed to prind the coordinates of the click I make on the image.

If anyone knows how to do that please modify this code that I am using:

void mouseEvent (int evt, int x, int y, int flags, void* param)
{                    
     if (evt == CV_EVENT_LBUTTONDOWN)
     { 
          printf("%d %d\n",x ,y );  
     }         
}

and this is what I use to call the function:

cvSetMouseCallback("blah blah", mouseEvent, 0);
Aditi
  • 1,188
  • 2
  • 16
  • 44

1 Answers1

7

Place your image in a Mat called frame, then:

namedWindow("test");
cvSetMouseCallback("test", mouseEvent, &frame);

char key = 0;
while ((int)key != 27) {
    imshow("test", frame);
    key =  waitKey(1);
}

where mouseEvent is defined as:

void mouseEvent(int evt, int x, int y, int flags, void* param) {                    
    Mat* rgb = (Mat*) param;
    if (evt == CV_EVENT_LBUTTONDOWN) { 
        printf("%d %d: %d, %d, %d\n", 
        x, y, 
        (int)(*rgb).at<Vec3b>(y, x)[0], 
        (int)(*rgb).at<Vec3b>(y, x)[1], 
        (int)(*rgb).at<Vec3b>(y, x)[2]); 
    }         
}
Radford Parker
  • 731
  • 4
  • 14
  • 2
    Just to clarify your answer to Cristian: the last parameter of `cvSetMouseCallback()` is a pointer, and it's used to send user data to the callback. So, the data we are interested in sending its the image itself so when the click is made you can access the pixel at that specified position. That's what this answer is showing. – karlphillip Feb 14 '13 at 16:17
  • thx for the answer mate but there are still some difficulties: I'm using OpenCV 2.1 on Dev c++. I've tried switching Mat* rgb to CvScalar but still have to change (*rgb).at(y, x)[0]. If you know how to change this for 2.1 I would really appreciate it! – Cristian Trasnea Feb 18 '13 at 08:58
  • Did IT! I've replaced (int)(*rgb).at(y, x)[0] with ((uchar*)(rgb->imageData + rgb->widthStep*y))[x*3] and Mat* rgb = (Mat*) param; with IplImage* rgb = (IplImage*) param; Thx for the help! – Cristian Trasnea Feb 18 '13 at 09:34