opencv选框操作

引言

在实验阶段,有时我们需要简单的GUI交互,比如拉一个框。下面就奉上选框的Demo代码,原理很简单,就是获取鼠标事件然后进行一些简单的操作。如果你不熟悉GUI操作,不妨看看吧。

代码
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
void mouseEvent(int event, int x, int y, int flags, void* userdata);
Rect rect; //选的框
bool render; //是否渲染
Mat frame; //帧
Point tl; //框的左上角,每次鼠标单击时记录一下
int main()
{
    VideoCapture cap(0);
    render = false;
    namedWindow("GUI");
    setMouseCallback("GUI", mouseEvent);
    while (waitKey(1000 / 25) == -1) {
        cap >> frame;  //读取帧
        if (frame.empty())
            break;
        if (render)  //渲染
            rectangle(frame, rect, { 0,255,255 }, 3);
        imshow("GUI", frame);
    }
}
void mouseEvent(int event, int x, int y, int flags, void* userdata)
{
    if (event == EVENT_LBUTTONDOWN) { //每次鼠标按下记录一次
        tl = { x,y };
    }
    else if (event == EVENT_MOUSEMOVE && flags == EVENT_FLAG_LBUTTON) {   //左键按下拖动拉框
        rect = { tl.x,tl.y,x-tl.x,y-tl.y };
        render = true;      
    }   
    else if (event == EVENT_MBUTTONDOWN) {  //中键取消渲染
        render = false;
    }


}
运行结果

选框结果

Guess you like

Origin blog.csdn.net/qq_16952303/article/details/80264732