首页
登录 | 注册

在OpenCV中调用鼠标事件

需要用到这个函数:cvSetMouseCallback

cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse,
                                void* param CV_DEFAULT(NULL));

第一个参数为窗口名,第二个为用于处理的函数。

那个用于处理的函数如下:

event为所发生的事件名
x,y为鼠标在图片上的坐标

然后,这是全部的事件

enum
{
    CV_EVENT_MOUSEMOVE      =0,   //鼠标移动
    CV_EVENT_LBUTTONDOWN    =1,   //按下左键
    CV_EVENT_RBUTTONDOWN    =2,   //按下右键
    CV_EVENT_MBUTTONDOWN    =3,   //按下中键
    CV_EVENT_LBUTTONUP      =4,   //放开左键
    CV_EVENT_RBUTTONUP      =5,   //放开右键
    CV_EVENT_MBUTTONUP      =6,   //放开中键
    CV_EVENT_LBUTTONDBLCLK  =7,   //左键双击
    CV_EVENT_RBUTTONDBLCLK  =8,   //右键双击
    CV_EVENT_MBUTTONDBLCLK  =9,   //中键双击
    CV_EVENT_MOUSEWHEEL     =10,  //滚轮滚动
    CV_EVENT_MOUSEHWHEEL    =11   //横向滚轮滚动(还好我鼠标是G502可以这么干)
};

enum
{
    CV_EVENT_FLAG_LBUTTON   =1,   //左键拖拽
    CV_EVENT_FLAG_RBUTTON   =2,   //右键拖拽
    CV_EVENT_FLAG_MBUTTON   =4,   //中键拖拽
    CV_EVENT_FLAG_CTRLKEY   =8,   //按住CTRL拖拽
    CV_EVENT_FLAG_SHIFTKEY  =16,  //按住Shift拖拽
    CV_EVENT_FLAG_ALTKEY    =32   //按住ALT拖拽
};

下面是我自己写的按下右键画图的代码:

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <stdio.h>
#include "opencv2/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/imgproc.hpp"
#include"opencv2/flann.hpp"
#include"opencv2/xfeatures2d.hpp"
#include"opencv2/ml.hpp"

using namespace cv;
using namespace std;
using namespace cv::xfeatures2d;
using namespace cv::ml;

Mat src;
bool down = false;
Point prept = Point(-1, -1);
Point curpt = Point(-1, -1);
void on_mouse(int event, int x, int y, int flags, void* ustc)
{

    if (event == CV_EVENT_LBUTTONDOWN)    //右键按下
    {
        prept = Point(x, y);
        down = true;
    }
    else if (event == CV_EVENT_LBUTTONUP)     //右键放开
        down = false;

    if (down ==true&&event == CV_EVENT_MOUSEMOVE)    //右键按下且鼠标移动
    {
        curpt = cvPoint(x, y);
        line(src, prept, curpt, Scalar(255, 0, 0), 5);
        waitKey(5);        //可以解决画图时卡顿的问题
        imshow("src", src);
        prept = curpt;
    }
}

int main()
{
    src = imread("7f6a384c510fd9f9da3ee67b232dd42a2834a40d.jpg");

    cvNamedWindow("src");
    cvSetMouseCallback("src", on_mouse, 0);

    imshow("src", src);
    cvWaitKey(0);
    cvDestroyAllWindows();
    return 0;
}

效果图
在OpenCV中调用鼠标事件



2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.009 s.
京ICP备10005923号