1. 回调函数 cvSetMouseCallback
void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param CV_DEFAULT(NULL)); //window_name:鼠标执行的窗口名 //on_mouse: 每次指定窗口鼠标事件发生时被调用的函数指针 //param : 传递到回调函数的参数
2. on_mouse函数
void Foo(int event, int x, int y, int flags, void* param); //param: 传递到cvSetMouseCallback函数调用的参数 //x、y: 鼠标指针在图像坐标系的坐标 //event: CV_EVENT_*变量之一
3. 示例代码
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include<iostream> using namespace std; using namespace cv; static int current = 0; void onMouse(int event, int x, int y, int flags, void* param); int main(int argc, char *argv[]) { cv::Mat image; // create an empty image std::cout << "This image is " << image.rows << " x "<< image.cols << std::endl; image = imread("test.jpg"); if (image.empty()) { // error handling std::cout << "Error reading image..." << std::endl; return 0; } Mat image_a = imread("test_a.jpg"); std::cout << "This image is " << image.rows << " x " << image.cols << std::endl; namedWindow("YunFung Image"); // set the mouse callback for this image cvSetMouseCallback("YunFung Image", onMouse, NULL); while (true){ if (current == 0) imshow("YunFung Image", image); if (current == 1) imshow("YunFung Image", image_a); waitKey(100); // refresh frame } return 1; } void onMouse(int event, int x, int y, int flags, void* param) // Outside the main { switch (event){ case CV_EVENT_LBUTTONDOWN: // dispatch the event current++ ; if (current >= 2) current = 0; cout << "current is" << current << endl; cout << "mouse.x" <<x<<" "<<"mouse.y"<<y<< endl; // display pixel value break; default: break; } return; }