使用opencv鼠标回调函数选择ROI区域

发布于:2025-03-20 ⋅ 阅读:(20) ⋅ 点赞:(0)

使用opencv绘制矩形ROI,点击鼠标左键开始绘制,鼠标右键退出绘制并返回矩形左上角和右下角坐标。可绘制多个ROI区域(图中红色区域)
在这里插入图片描述

/****************************************
函数名称:
		MouseCallbackDrawRect()
函数功能:
		绘制矩形回调函数
***************************************/
bool drawing = false;
bool bExitDrawing = false;
Point startPoint, endPoint;
Mat tempImg;
vector<pair<Point, Point>> vecPairLeftUpRightDownPoint;//记录绘制的起点和终点

void MouseCallbackDrawRect(int event, int x, int y, int flags, void* userdata)
{
	const Mat& image = *(Mat*)userdata;
	if (event == EVENT_LBUTTONDOWN) { // 鼠标左键按下
		drawing = true;
		startPoint = Point(x, y); // 记录起始点
	}
	else if (event == EVENT_MOUSEMOVE) { // 鼠标移动
		if (drawing)
		{
			endPoint = Point(x, y); // 更新结束点
			tempImg = image.clone(); // 复制原始图像
			rectangle(tempImg, startPoint, endPoint, Scalar(0, 0, 255), 2); // 绘制矩形
			for (vector<pair<Point, Point>>::const_iterator it = vecPairLeftUpRightDownPoint.cbegin(); it != vecPairLeftUpRightDownPoint.cend(); it++)
			{
				rectangle(tempImg, Rect(it->first,it->second), Scalar(0, 0, 255), 2); // 绘制矩形
			}
			imshow("Image", tempImg); // 显示实时矩形
		}
	}
	else if (event == EVENT_LBUTTONUP) { // 鼠标左键释放
		drawing = false;
		endPoint = Point(x, y); // 记录结束点
		pair<Point, Point> pairPointTemp;
		pairPointTemp.first = startPoint;
		pairPointTemp.second = endPoint;
		vecPairLeftUpRightDownPoint.push_back(pairPointTemp);
		rectangle(image, startPoint, endPoint, Scalar(0, 0, 255), 2); // 在原始图像上绘制矩形
		imshow("Image", image); // 显示最终结果
	}
	if (event == EVENT_RBUTTONDOWN)//鼠标右键退出
	{
		bExitDrawing = true;
		return;
	}
}

/****************************************
函数名称:
		LogLURDPoint()
函数功能:
		记录矩形左上角和右下角坐标
***************************************/
vector<pair<Point, Point>> LogLURDPoint(Mat img, string WindowName)
{
	namedWindow(WindowName);
	setMouseCallback(WindowName, MouseCallbackDrawRect, &img);

	vector<pair<Point, Point>> vecpairStartEndPoint;

	// 显示图像
	imshow(WindowName, img);

	// 等待按键退出
	while (true)
	{
		if ((waitKey(1) == 27)|| bExitDrawing) { // 按下ESC键或者鼠标右键退出
			vecpairStartEndPoint= vecPairLeftUpRightDownPoint;
			vecPairLeftUpRightDownPoint.clear();
			bExitDrawing = false;
			break;
		}
	}
	return vecpairStartEndPoint;
}

/*************************主函数***************************/
int main()
{
    Mat matSrcColor = imread("1.jpg",IMREAD_COLOR);
    if (matSrcColor.empty())
    {
        cout << "源图像不存在,请确认图像路径。";
        return -1;
    }
    else
    {
        Mat matSrcColorClone = matSrcColor.clone();
        vector<pair<Point, Point>> pairLURDPoints;
        pairLURDPoints = LogLURDPoint(matSrcColorClone, "Image");
        return;
    }