Opencv鼠标事件

Opencv中的鼠标事件,例如在界面中通过鼠标左键任意位置,显示点坐标,并将改点存储到points中,为后续使用。

定义鼠标事件:

#include "opencv2/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
cv::Mat org,dst,img,tmp;
std::vector<Point> points;

void on_mouse(int event,int x,int y,int flags,void *ustc)//event鼠标事件代号,x,y鼠标坐标,flags拖拽和键盘操作的代号
{
    static cv::Point pre_pt = cv::Point(-1,-1);//初始坐标
    static cv::Point cur_pt = cv::Point(-1,-1);//实时坐标
    char temp[16];
    if (event == cv::EVENT_LBUTTONDOWN)//左键按下,读取初始坐标,并在图像上该点处划圆
    {
        org.copyTo(img);//将原始图片复制到img中
        sprintf(temp,"(%d,%d)",x,y);
        pre_pt = cv::Point(x,y);
        cv::putText(org,temp,pre_pt,cv::FONT_HERSHEY_SIMPLEX,0.5,cv::Scalar(0,0,0,255),1,8);//在窗口上显示坐标
        cv::circle(org,pre_pt,2,cv::Scalar(255,0,0,0),CV_FILLED,CV_AA,0);//划圆
        cv::imshow("img",org);
    }
    else if(event == cv::EVENT_LBUTTONUP){
        Point p;
        p.x = x;
        p.y = y;
        points.push_back(p);
//        std::cout<<"mouse button up"<<std::endl;
    }
}

调用鼠标事件

在main函数中调用鼠标事件:

    org = cv::Mat(480, 640, CV_8UC3, cv::Scalar(255, 255,255));
    cv::namedWindow("img");
    cv::setMouseCallback("img",on_mouse,0);//调用回调函数
    cv::imshow("img", org);
    char key = cv::waitKey(0);

最后的效果为:
在这里插入图片描述
备注:Opencv中关于所有鼠标事件定义如下:

       EVENT_MOUSEMOVE      = 0, //!< indicates that the mouse pointer has moved over the window.
       EVENT_LBUTTONDOWN    = 1, //!< indicates that the left mouse button is pressed.
       EVENT_RBUTTONDOWN    = 2, //!< indicates that the right mouse button is pressed.
       EVENT_MBUTTONDOWN    = 3, //!< indicates that the middle mouse button is pressed.
       EVENT_LBUTTONUP      = 4, //!< indicates that left mouse button is released.
       EVENT_RBUTTONUP      = 5, //!< indicates that right mouse button is released.
       EVENT_MBUTTONUP      = 6, //!< indicates that middle mouse button is released.
       EVENT_LBUTTONDBLCLK  = 7, //!< indicates that left mouse button is double clicked.
       EVENT_RBUTTONDBLCLK  = 8, //!< indicates that right mouse button is double clicked.
       EVENT_MBUTTONDBLCLK  = 9, //!< indicates that middle mouse button is double clicked.
       EVENT_MOUSEWHEEL     = 10,//!< positive and negative values mean forward and backward scrolling, respectively.
       EVENT_MOUSEHWHEEL    = 11 //!< positive and negative values mean right and left scrolling, respectively.
  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值