1、在图片上用鼠标进行操作,opencv主要用到setMouseCallback()函数。


winname 窗口名称
onMouse 鼠标事件的回调函数
userdata 传递给回调函数
还有onMouse函数


event 鼠标事件
x,y 鼠标在图片上的坐标
flags 鼠标事件标志
这里有一个容易搞混的地方
void跟void_
在函数的返回值中, void 是没有任何返回值, 而 void _ 是返回任意类型的值的指针.

划线还需要用到line()函数


img 图片名称
pt1 线段起点
pt2 线段终点
color 颜色
thickness 宽度
lineType 线段类型
shift 移位点坐标中的小数位数。

接下来直接看代码

#include <iostream>
#include<opencv.hpp>

using namespace std;
using namespace cv;

Mat img;
Point p;
void on_monse(int event, int x, int y, int flags, void*)
{
    if (event == 1)//1 左键点击
    {
        p = Point(x, y);
    }
    else if (event == 0 && flags == 1)//0 滑动 1左键拖曳
    {
        Point p1(x, y);
        line(img, p, p1, Scalar(255, 0, 0), 5);
        p = p1;
        imshow("www", img);
    }
}
int main()
{
    img = imread("星空1.png", 1);
    imshow("www", img);
    setMouseCallback("www", on_monse);
    waitKey(0);
}

效果图:


附: