此处给出OpenCV中的鼠标回调函数,实现功能:将鼠标左键点击处的图像像素值显示在终端。
/* void setMousecallback(const string& winname, MouseCallback onMouse, void* userdata=0) winname:窗口名 onMouse:鼠标响应函数,原型:void on_Mouse(int event, int x, int y, int flags, void* param); userdata:可认为是传给回调函数的参数 */ #include <iostream> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; const char* windows_name = "onMouseCallback"; void on_Mouse(int event, int x, int y, int flags, void* param); int main(int argc, char* argv[]) { Mat src = imread("imgA.png",-1); if (src.empty()) { cout << "The image is empty, please check it!" << endl; return -1; } namedWindow(windows_name); setMouseCallback(windows_name, on_Mouse,(void*)&src); //类型转换 imshow(windows_name, src); waitKey(); return 0; } void on_Mouse(int event, int x, int y, int flags, void* param) { Mat depth_img = *(Mat*)param; // 先转换类型,再取数据 Vec3b depth; // 初始化不可放在case内 // 一般包含如下3个事件 switch (event) { case EVENT_MOUSEMOVE: //cout << "Please select one point:" << endl; break; case EVENT_LBUTTONDOWN: // 鼠标左键按下 depth = depth_img.at<Vec3b>(x, y); cout << "Position: (" << x << "," << y << ")—— depth = " << depth << endl; break; case EVENT_LBUTTONUP: // 鼠标左键释放 cout << "buttonup" << endl; break; } }