7/14/2016

OpenCV Mouse event example code

You can capture mouse event very easy using callback function.
"setMouseCallback” function is that callback function setting.

And many another events, so we can do various of application.
EVENT_MOUSEMOVE      = 0, 
EVENT_LBUTTONDOWN    = 1, 
EVENT_RBUTTONDOWN    = 2, 
EVENT_MBUTTONDOWN    = 3, 
EVENT_LBUTTONUP      = 4, 
EVENT_RBUTTONUP      = 5, 
EVENT_MBUTTONUP      = 6, 
EVENT_LBUTTONDBLCLK  = 7, 
EVENT_RBUTTONDBLCLK  = 8, 
EVENT_MBUTTONDBLCLK  = 9, 
EVENT_MOUSEWHEEL     = 10, 
EVENT_MOUSEHWHEEL    = 11 







#include "opencv2/opencv.hpp"
#include < iostream>

using namespace std;
using namespace cv;


void CallBackFunc(int event, int x, int y, int flags, void* userdata)
{
 if (event == EVENT_LBUTTONDOWN)
 {
  cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
 }
 else if (event == EVENT_RBUTTONDOWN)
 {
  cout << "Right button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
 }
 else if (event == EVENT_MBUTTONDOWN)
 {
  cout << "Middle button of the mouse is clicked - position (" << x << ", " << y << ")" << endl;
 }
 else if (event == EVENT_MOUSEMOVE)
 {
  cout << "Mouse move over the window - position (" << x << ", " << y << ")" << endl;
 }

}
 /*
 EVENT_MOUSEMOVE      = 0,
 EVENT_LBUTTONDOWN    = 1,
 EVENT_RBUTTONDOWN    = 2,
 EVENT_MBUTTONDOWN    = 3,
 EVENT_LBUTTONUP      = 4,
 EVENT_RBUTTONUP      = 5,
 EVENT_MBUTTONUP      = 6,
 EVENT_LBUTTONDBLCLK  = 7,
 EVENT_RBUTTONDBLCLK  = 8,
 EVENT_MBUTTONDBLCLK  = 9,
 EVENT_MOUSEWHEEL     = 10,
 EVENT_MOUSEHWHEEL    = 11
 */

int main()
{
 // Read image from file 
 Mat img = imread("anapji.jpg");

 //if fail to read the image
 if (img.empty())
 {
  cout << "Error loading the image" << endl;
  return 0;
 }

 //Create a window
 namedWindow("My Window", 1);

 //set the callback function for any mouse event
 setMouseCallback("My Window", CallBackFunc, NULL);

 //show the image
 imshow("My Window", img);

 // Wait until user press some key
 waitKey(0);

 return 0;

}

No comments:

Post a Comment