user1783116
user1783116

Reputation: 57

how to pick up value of a pixel from a mouse click?

I show a Mat matrix on the screen as an image. I want to click a location on this image and I want obtain that pixel value on screen.

How can be done with OpenCV, C++?

Upvotes: 0

Views: 789

Answers (2)

zkan
zkan

Reputation: 641

I use this code below for IplImage, but the result should be the same when you use Mat.

void my_mouse_callback(int event, int x, int y, int flags, void* param){
  IplImage* image = (IplImage*) param;

  switch(event) {
    case CV_EVENT_LBUTTONDOWN:
      std::cout << "x: " << x << std::endl;
      std::cout << "y: " << y << std::endl;
      break;
    default:
      break;
  }
}

int main() {
  IplImage* image = cvLoadImage("picture_file_name_here");

  cvNamedWindow("Test");

  cvSetMouseCallback("Test", my_mouse_callback, (void*) image);

  cvShowImage("Test", image);
  cvWaitKey(0);

  cvReleaseImage(&image);

  return 0;
}

Hope this helps.

Upvotes: 2

berak
berak

Reputation: 39786

for cv::Mat it would look like:

cv::Mat mat; // load img, etc

cv::setMouseCallback("Test", my_mouse_callback, (void*) &mat);

// ...



void my_mouse_callback(int event, int x, int y, int flags, void* param){
  cv::Mat mat = *((cv::Mat*)param);  // so, 1st cast, then deref
}

Upvotes: 0

Related Questions