鼠标手动绘制矩形

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

Mat image;
Rect xx;
bool draw_or_not = 0;
RNG g_rng(12345);

//利用鼠标回调函数来在图像上画矩形。
void mouse_on(int event, int x, int y, int, void*);
void draw_rect(Mat & im, Rect &rec);
int main()
{
	//1.创建图像,或者读取一副图像。
	image = imread("C:/Users/ASUS/Pictures/保存的图片/circle.png");

	//2.初始化一个矩形。
	xx = Rect(-1, -1, 0, 0);
	//3.创建回调函数。
	namedWindow("效果窗口");
	setMouseCallback("效果窗口", mouse_on);
	//4.回调函数调用的画图函数。

	while (1)
	{


		imshow("效果窗口", image);

		int c = waitKey(20);
		if (c == 27)
			break;

	}

	waitKey(0);
	return 1;

}

void mouse_on(int event, int x, int y, int, void*)
{
	//1.判断鼠标动作,动作有移动,左键按下,左键松开。在松开时候画矩形。
	//1.左键按下,取rect的起始坐标。
	if (event == EVENT_LBUTTONDOWN)
	{
		draw_or_not = 1;
		xx.x = x;
		xx.y = y;


	}
	//2.移动的时候,计算rect的长和宽。
	if (draw_or_not == 1 && event == EVENT_MOUSEMOVE)
	{

		xx.width = x - xx.x;
		xx.height = y - xx.y;

	}
	//3.左键松开时候,判断长和宽相对于开始点的方向,找出rect的左上点。
	if (draw_or_not == 1 && event == EVENT_LBUTTONUP)
	{

		draw_or_not = 0;
		if (xx.width < 0)
		{
			xx.x = xx.x + xx.width;
			xx.width = -xx.width;
		}
		if (xx.height < 0)
		{
			xx.y = xx.y + xx.height;
			xx.height *= -1;
		}

		draw_rect(image, xx);


	}


}

void draw_rect(Mat& im, Rect& rec)
{
	rectangle(im, rec, Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)));

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peteous

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值