OpenCV之鼠标操作

 先上代码

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/video.hpp>

using namespace cv;
using namespace std;

#define WINDOW_NAME "[程序窗口]"  //为窗口标题定义的宏

Rect g_rectangle;
bool g_bDrawingBox = false; // 是否进行绘制标记位
RNG g_rng(12345);


void DrawRectangle(cv::Mat& img, cv::Rect box) {
	rectangle(img, box.tl(), box.br(), Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)));
}


void on_MouseHandle(int event, int x, int y, int flags, void* param) {
	Mat& image = *(cv::Mat*)param;
	switch (event)
	{
		case EVENT_MOUSEMOVE:
		{
			cout << "111xxxxxxxxxxxxxxxx = " << x << "                     yyyyyyyyyyyyyyyyyyyyy = " << y << endl;
			if (g_bDrawingBox)//如果进行绘制,则记录下长和宽到Rect类型变量中
			{
				g_rectangle.width = x - g_rectangle.x;
				g_rectangle.height = y - g_rectangle.y;
			}
		}
			break;
		case EVENT_LBUTTONDOWN:
		{
			cout << "222xxxxxxxxxxxxxxxx = " << x << "                     yyyyyyyyyyyyyyyyyyyyy = " << y << endl;
			g_bDrawingBox = true;//绘制标记置true
			g_rectangle = Rect(x, y, 0, 0);//记录起始点
		}
			break;
		case EVENT_LBUTTONUP:
		{
			cout << "333xxxxxxxxxxxxxxxx = " << x << "                     yyyyyyyyyyyyyyyyyyyyy = " << y << endl;
			g_bDrawingBox = false;//绘制标记置false
			//对宽和高小于0的处理
			if (g_rectangle.width < 0)
			{
				g_rectangle.x += g_rectangle.width;
				g_rectangle.width *= -1;
			}
			if (g_rectangle.height < 0)
			{
				g_rectangle.y += g_rectangle.height;
				g_rectangle.height *= -1;
			}
			//调用函数进行绘制
			DrawRectangle(image, g_rectangle);
		}
			break;
	}

}


int main(int argc, char** argv)
{
	//1.准备参数
	g_rectangle = Rect(-1, -1, 0, 0);
	Mat srcImage(600, 800, CV_8UC3), tempImage;
	srcImage.copyTo(tempImage);
	g_rectangle = Rect(-1, -1, 0, 0);
	srcImage = Scalar::all(0);
	//2.设置鼠标操作回调函数
	namedWindow(WINDOW_NAME);
	setMouseCallback(WINDOW_NAME, on_MouseHandle, (void*)&srcImage);

	//3.程序主循环,当进行绘制的标识符为真时,进行绘制
	while (1)
	{	
		srcImage.copyTo(tempImage);//复制源图到临时变量
		if (g_bDrawingBox)
		{
			DrawRectangle(tempImage, g_rectangle);
		}
		imshow(WINDOW_NAME, tempImage);
		if (waitKey(10) == 27)//按下esc键,程序退出
		{
			break;
		}
	}
	return 0;
}

效果

 setMouseCallback函数

程序的主循环主要是完成对鼠标点击移动画图的过程

setMouseCallback主要完成了在鼠标释放以后显示画出的矩形

坐标:图片左上角为(0, 0)  向下增大,向右增大

猜你喜欢

转载自blog.csdn.net/sono_io/article/details/124136358