opencv c++怎么通过gui使用鼠标设定指定区域
时间: 2024-02-25 09:58:30 浏览: 22
要通过GUI使用鼠标设定指定区域,可以使用OpenCV的setMouseCallback函数来实现。下面是一个基本的示例:
```
#include <opencv2/opencv.hpp>
using namespace cv;
Rect box; //定义一个矩形框,用于记录鼠标选择的区域
bool drawing_box = false; //标记是否正在通过鼠标绘制矩形框
void draw_box(Mat& img, Rect box)
{
//绘制矩形框
rectangle(img, box.tl(), box.br(), Scalar(0, 0, 255), 2);
}
void onMouse(int event, int x, int y, int flags, void* param)
{
Mat& image = *(Mat*)param;
switch (event)
{
case EVENT_MOUSEMOVE:
if (drawing_box)
{
//更新矩形框位置
box.width = x - box.x;
box.height = y - box.y;
}
break;
case EVENT_LBUTTONDOWN:
//开始绘制矩形框
drawing_box = true;
box = Rect(x, y, 0, 0);
break;
case EVENT_LBUTTONUP:
//结束绘制矩形框
drawing_box = false;
if (box.width < 0)
{
box.x += box.width;
box.width *= -1;
}
if (box.height < 0)
{
box.y += box.height;
box.height *= -1;
}
draw_box(image, box);
break;
}
}
int main()
{
Mat image = imread("test.jpg");
namedWindow("image");
setMouseCallback("image", onMouse, &image);
while (true)
{
imshow("image", image);
if (waitKey(10) == 27) break; //按下ESC键退出程序
}
return 0;
}
```
以上代码实现了在图像上使用鼠标绘制一个矩形框的功能。我们定义了一个全局的矩形框变量box,用于记录鼠标选择的区域。在setMouseCallback函数中,我们将回调函数设置为onMouse,并将图像的引用传递给它。在onMouse中,我们根据鼠标事件的不同来更新矩形框的位置或绘制矩形框。最后,在主循环中不断显示图像,直到按下ESC键退出程序。