opencv鼠标操作

#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

void on_MouseHandle(int event,int x,int y,int flags,void * param);
void DrawRectangle(cv::Mat& img,cv::Rect box);

Rect g_rectangle;
bool g_bDrawingBox  = false;
RNG g_rng(12345);

int main(int argc,char** argv)
{
	g_rectangle = Rect(-1,-1,0,0);
	Mat srcImage(600,800,CV_8UC3),tempImage;
	srcImage.copyTo(tempImage);
	srcImage = Scalar::all(0);

	namedWindow("程序窗口");
	setMouseCallback("程序窗口",on_MouseHandle,(void*)&srcImage);
	while(1)
	{
		srcImage.copyTo(tempImage);
		if(g_bDrawingBox)
			DrawRectangle(tempImage,g_rectangle);
		imshow("程序窗口",tempImage);
		if(waitKey(10)==27)
			break;
	}
	return 0;
}

void on_MouseHandle(int event,int x,int y,int flags,void * param)
{
	Mat & image = *(cv::Mat*) param;
	switch(event)
	{
		case EVENT_MOUSEMOVE:
		{
			if(g_bDrawingBox)
			{
				g_rectangle.width = x- g_rectangle.x;
				g_rectangle.height = y- g_rectangle.y;
			}
		}
		break;
		case EVENT_LBUTTONDOWN:
		{
			g_bDrawingBox = true;
			g_rectangle = Rect(x,y,0,0);
		}
		break;
		case EVENT_LBUTTONUP:
		{
			g_bDrawingBox = false;
			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;
	}
}

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)));

	rectangle(img,box.tl(),box.br(),Scalar(g_rng.uniform(0,255),g_rng.uniform(0,255),g_rng.uniform(0,255)));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值