Opencv实现矩形框拖动

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

#define WINDOW_NAME "矩形拖动"

Mat src_image;
Mat dst_image;
Rect rect;
Point pt;
bool flag_mouse_contained;

void Mouse_Callback(int event, int x, int y, int flags, void* userdata)
{
    switch (event)
    {
    case EVENT_LBUTTONDOWN:
        if (rect.contains(Point(x, y)))
        {
            flag_mouse_contained = true;
            pt = Point(x, y);
        }
        break;
    case EVENT_MOUSEMOVE:
        if (flag_mouse_contained == true)
        {
            rect.x += (x - pt.x);   //当前鼠标坐标减去上一次回调事件的鼠标坐标
            rect.y += (y - pt.y);
        }
        break;
    case EVENT_LBUTTONUP:
        flag_mouse_contained = false;
        break;
    }
    pt = Point(x, y);   //记录当前鼠标坐标用于下一次回调事件
}

int main(int argc, char** argv)
{
    flag_mouse_contained = false;
    src_image = Mat(256, 256, CV_32FC3, Scalar(255, 255, 255));
    namedWindow(WINDOW_NAME, WINDOW_AUTOSIZE);
    setMouseCallback(WINDOW_NAME, Mouse_Callback, 0);
    rect = Rect(50, 50, 50, 50);
    src_image.copyTo(dst_image);    //类似于winform中的Paint事件,只修改dst_image,scr_image保持不变
    rectangle(dst_image, rect, Scalar(0, 0, 0));
    imshow(WINDOW_NAME, dst_image);
    while (1)
    {
        if (flag_mouse_contained == true)
        {
            src_image.copyTo(dst_image);
            rectangle(dst_image, rect, Scalar(0, 0, 0));
            imshow(WINDOW_NAME, dst_image);
        }
        if (waitKey(10) == 27)  //等待事件必须大于0,如果小于等于0,则程序会进入无限等待
        {
            return 0;
        }
    }
    //cvDrawRect()
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/canyeweiwei/p/10504588.html