C++Opencv鼠标响应

Opencv鼠标响应

前面已经介绍过了键盘的响应操作,那么鼠标的呢?这里就来介绍如何使用opencv的鼠标响应API。

1.函数介绍

 void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0);
 参数:
 winname:窗口名称
 onMouse:鼠标响应函数,回调函数
 userdata:用户自定义的参数

此函数会在调用之后不断查询鼠标信息直到窗口销毁

2.主要操作在回调函数onMouse中设置

void on_Mouse(int event, int x, int y, int flags, void* param);
参数:
event:表示鼠标事件类型的常量
x和y:鼠标指针在图像坐标系的坐标
flags:鼠标事件标志的常量
param:用户可自定义的参数

3.鼠标事件的类型(字母和数字完全等价):

Event:
#define EVENT_MOUSEMOVE 0 滑动
#define EVENT_LBUTTONDOWN 1 左键点击
#define EVENT_RBUTTONDOWN 2 右键点击
#define EVENT_MBUTTONDOWN 3 中键点击
#define EVENT_LBUTTONUP 4 左键放开
#define EVENT_RBUTTONUP 5 右键放开
#define EVENT_MBUTTONUP 6 中键放开
#define EVENT_LBUTTONDBLCLK 7 左键双击
#define EVENT_RBUTTONDBLCLK 8 右键双击
#define EVENT_MBUTTONDBLCLK 9 中键双击
示例代码:

Point sp(-1, -1);
Point ep(-1, -1);
Mat temp;
static void on_draw(int event, int x, int y, int flags, void* userdata) {
	Mat image = *((Mat*)userdata);
	if (event == EVENT_LBUTTONDOWN) {
		sp.x = x;
		sp.y = y;
		cout << "x:" << x << " y:" << y << endl;
	}
	else if (event == EVENT_LBUTTONUP) {
		ep.x = x;
		ep.y = y;
		cout << "x:" << x << " y:" << y << endl;
		if (ep.x - sp.x > 0 && ep.y - sp.y > 0) {
			Rect rect;
			rect.x = sp.x;
			rect.y = sp.y;
			rect.width = ep.x - sp.x;
			rect.height = ep.y - sp.y;

			image.copyTo(temp);
			rectangle(temp, rect, Scalar(0, 0, 255), 2, 8, 0);
			imshow("截图", temp); 
			imshow("ROI区域", image(rect));
			//reset
			sp.x = -1;
			sp.y = -1;
		}
	}
	else if (event == EVENT_MOUSEMOVE) {
		if (sp.x > 0 && sp.y > 0) {
			Rect rect;
			rect.x = sp.x;
			rect.y = sp.y;
			rect.width = x - sp.x;
			rect.height = y - sp.y;

			image.copyTo(temp);
			rectangle(temp, rect, Scalar(0, 0, 255), 2, 8, 0);
			imshow("截图", temp);
		}
	}
}

void mouse_drawimg_demo(Mat &image) {
	imshow("截图", image);
	setMouseCallback("截图", on_draw, (void*)(&image));
}

void test1401()
{
	Mat image = imread("C:/Users/86156/Pictures/Saved Pictures/cwt.jpg");
	mouse_drawimg_demo(image);
	waitKey(0);
}


int main()
{
	test1401();
	system("pause");
}

效果:
C++Opencv鼠标响应_第1张图片

你可能感兴趣的:(Opencv(C++),opencv,c++,计算机视觉)