拖动鼠标画框

Matlab:

I=imread('pic.jpg');

figure(1); imshow(I); title('Input Image');
text(6,6,'Left click to get points, right click to get end point','FontSize',[12],'Color', 'r');
[m,xi,yi]=roipoly;
min_xi=min(xi);
max_xi=max(xi);
min_yi=min(yi);
max_yi=max(yi);
roi=I(min_yi:max_yi,min_xi:max_xi);
 

C++:

按下鼠标左键开始选取区域,按下鼠标右键显示截取的区域:

Mat org, dst, img, tmp;
static Point pre_pt = (-1, -1);
static Point cur_pt = (-1, -1);
void on_mouse(int event, int x, int y, int flags, void *)
{
    if (event == CV_EVENT_LBUTTONDOWN)
    {
        pre_pt = Point(x, y);
    }
    else if (event == CV_EVENT_MOUSEMOVE && flags)//摁下左键,flags为1 

    {
        org.copyTo(tmp);
        cur_pt = Point(x, y);
        circle(tmp, cur_pt, 4, Scalar(0, 255, 0, 0), 2, 8);
        rectangle(tmp, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);
        imshow("img", tmp);//画的时候显示框
    }
    else if (event == CV_EVENT_LBUTTONUP)
    {
        org.copyTo(img);
        rectangle(img, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);
        imshow("img", img);//画完后显示框    

    }
    if (event == CV_EVENT_RBUTTONUP)                        //右键UP,截取所选区域  
    {
        if (!dst.empty())
            dst = NULL;
        int width = abs(pre_pt.x - cur_pt.x);
        int height = abs(pre_pt.y - cur_pt.y);
        if (width == 0 || height == 0)
        {
            imshow("img", img);//画完后显示框
        }
        else
        {
            dst = org(Rect(min(cur_pt.x, pre_pt.x), min(cur_pt.y, pre_pt.y), width, height));
            namedWindow("dst");
            imshow("dst", dst);
        }
        flags = 0;

    }

}

int main()

{

     Mat image=imread("pic.jpg");    

    org = image.clone();
    org.copyTo(img);
    namedWindow("img");
    imshow("img", img);
    setMouseCallback("img", on_mouse, 0);
    waitKey(0);

}

或可参考:https://www.pianshen.com/article/790697097/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值