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

1 Answer 1

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]); 
    }         
}
3
  • 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. Feb 14, 2013 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<Vec3b>(y, x)[0]. If you know how to change this for 2.1 I would really appreciate it! Feb 18, 2013 at 8:58
  • Did IT! I've replaced (int)(rgb).at<Vec3b>(y, x)[0] with ((uchar)(rgb->imageData + rgb->widthStepy))[x*3] and Mat rgb = (Mat*) param; with IplImage* rgb = (IplImage*) param; Thx for the help! Feb 18, 2013 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.