opencv笔记16-鼠标操作与响应

鼠标操作与响应

#include
#include

using namespace std;
using namespace cv;

Point sp(-1, -1);
Point ep(-1, -1);
Mat temp;

//回调函数
static void on_draw(int event, const int x, const int y, int flags, void* userdata)
{
	Mat image = *((Mat*)userdata);

	//鼠标点击
	if (event == EVENT_LBUTTONDOWN)
	{
		sp.x = x;
		sp.y = y;
		cout << "Point:" << sp << endl;
	}

	//鼠标左键拖动
	else if (event == EVENT_LBUTTONUP)
	{
		ep.x = x;
		ep.y = y;
		int dx = abs(ep.x - sp.x);
		int dy = abs(ep.y - sp.y);

		//绘制图
		Rect box(sp.x, sp.y, dx, dy);
		imshow("ROI区域", image(box));
		rectangle(image, box, Scalar(0, 255, 0), 2, 8, 0);
		imshow("鼠标绘制", image);
		//为下一次绘制
		sp.x = -1;
		sp.y = -1;
	}
	else if (event == EVENT_MOUSEMOVE)
	{
		if (sp.x > 0 && sp.y > 0)
		{
			ep.x = x;
			ep.y = y;
			int dx = abs(ep.x - sp.x);
			int dy = abs(ep.y - sp.y);

			//绘制图
			Rect box(sp.x, sp.y, dx, dy);
			temp.copyTo(image);
			rectangle(image, box, Scalar(0, 255, 0), 2, 8, 0);
			imshow("鼠标绘制", image);
		}
		
	}

}

//鼠标响应与操作
void mouse_demo(Mat &image)
{
	namedWindow("鼠标绘制", WINDOW_AUTOSIZE);
	setMouseCallback("鼠标绘制", on_draw,(void*)(&image));
	imshow("鼠标绘制", image);
	temp = image.clone();
}

int main()
{
	string path = "C:\\Users\\四明\\Pictures\\QQ图片20200608155343.jpg";
	Mat img = imread(path);
	if (img.empty())
	{
		cout << "图片加载失败!" << endl;
		return -1;
	}
	namedWindow("image", WINDOW_FREERATIO);
	imshow("image", img);
	mouse_demo(img);
	waitKey(0);
	destroyAllWindows();
	return 0;
}

效果图
opencv笔记16-鼠标操作与响应_第1张图片

你可能感兴趣的:(opencv笔记,笔记,c++,opencv)