#include "stdafx.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
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);
cout << x << " " << y << endl;
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("C:\\Users\\Administrator\\Desktop\\3.png", 1);
cvNamedWindow("src");
cvSetMouseCallback("src", on_mouse, 0);//关键内置函数
imshow("src", src);
cvWaitKey(0);
cvDestroyAllWindows();
return 0;
}
其中#include <opencv2/highgui/highgui_c.h>可以加入此头文件,防止后面的cvNameWindow等函数无法识别。此外#include "stdafx.h"可以删除。
CV_EVENT_LBUTTONDOWN可以将CV_去掉,如果出现无法识别。