opencv侦测鼠标运动和与键盘功能键的混用

opencv窗口鼠标事件回调函数声明如下

void eventCallback(int event, int x, int y, int flags, void* userdata)

函数解释如下

void setMouseCallback(const string& winname, MouseCallback onMouse, void* userdata = 0)
This function sets a callback function to be called every time any mouse events occurs in the specified window. Here is the detailed explanation of the each parameters of the 
above OpenCV function. 1.winname - Name of the OpenCV window. All mouse events related to this window will be registered 2.onMouse - Name of the callback function. Whenever mouse events related to the above window occur, this callback function will be called. This function should have the
signature like the following void FunctionName(int event, int x, int y, int flags, void* userdata) event - Type of the mouse event. These are the entire list of mouse events EVENT_MOUSEMOVE EVENT_LBUTTONDOWN EVENT_RBUTTONDOWN EVENT_MBUTTONDOWN EVENT_LBUTTONUP EVENT_RBUTTONUP EVENT_MBUTTONUP EVENT_LBUTTONDBLCLK EVENT_RBUTTONDBLCLK EVENT_MBUTTONDBLCLK x - x coordinate of the mouse event y - y coordinate of the mouse event flags - Specific condition whenever a mouse event occurs. See the next OpenCV example code for the usage of this parameter. Here is the entire list of enum values which will
be possesed by "flags" EVENT_FLAG_LBUTTON EVENT_FLAG_RBUTTON EVENT_FLAG_MBUTTON EVENT_FLAG_CTRLKEY EVENT_FLAG_SHIFTKEY EVENT_FLAG_ALTKEY userdata - Any pointer passes to the "setMouseCallback" function as the 3rd parameter (see below) userdata - This pointer will be passed to the callback function

鼠标事件响应实例代码

#include <iostream>
#include "opencv2/highgui/highgui.hpp"
using namespace std;

void eventCallback(int event, int x, int y, int flags, void* userdata)
{
	//鼠标事件
	if (event == cv::EVENT_LBUTTONDOWN)
	{
		printf("L_Button Down
");
	}
	else if (event == cv::EVENT_RBUTTONDOWN)
	{
		printf("R_Button Down
");
	}
	else if (event == cv::EVENT_MBUTTONDOWN)
	{
		printf("M_Button Down
");
	}
	else if (event == cv::EVENT_MOUSEMOVE)
	{
		printf("M_V Event: %d %d
", x, y);
	}

	//键盘和鼠标混合事件
	if (flags == (cv::EVENT_FLAG_CTRLKEY + cv::EVENT_FLAG_LBUTTON))
	{
		printf("Ctrl_LB Event
");
	}
	else if (flags ==  cv::EVENT_FLAG_RBUTTON + cv::EVENT_FLAG_SHIFTKEY)
	{
		printf("Shift_RB Event
");
	}
	else if (flags == cv::EVENT_MOUSEMOVE + cv::EVENT_FLAG_ALTKEY)
	{
		printf("Alter_MV Event: %d %d
", x, y);
	}
}

int main(int argc, char** argv)
{
	char w_name[] = "OpenCV Windows";

	// Read image from file
	cv::Mat img = cv::Mat(500, 700, CV_8UC3, cv::Scalar(255, 255, 255));

	imshow(w_name, img);
	cv::setMouseCallback(w_name, eventCallback, NULL);

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

	return 0;
}
原文地址:https://www.cnblogs.com/flyinggod/p/12432913.html