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 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"<

调用鼠标事件

在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鼠标事件_第1张图片
备注: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.

你可能感兴趣的:(Opencv)