因为需要在图片上标记直线,所以从网上找了相应的参考资料。但大多都是c风格的,于是自己就按照此博主的c++风格的代码进行了简单的修改。
代码如下:
#pragma warning(disable:4996)
#include <opencv2/opencv.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <iostream>
#include <string.h>
using namespace std;
using namespace cv;
Mat src;
Mat dst;
void on_mouse(int event, int x, int y, int flags, void* ustc)
{
static CvPoint pre_pt = { -1, -1 };
static CvPoint cur_pt = { -1, -1 };
char temp[16];
if (event == CV_EVENT_LBUTTONDOWN)
{
dst.copyTo(src);
sprintf(temp, "(%d,%d)", x, y);
pre_pt = Point(x, y);
putText(src, temp, pre_pt, FONT_HERSHEY_PLAIN,1,Scalar(0,0,255),1,8,0);
circle(src, pre_pt, 3, cvScalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0);
imshow("src", src);
src.copyTo(dst);
}
else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))
{
sprintf(temp, "(%d,%d)", x, y);
dst.copyTo(src);
cur_pt = Point(x, y);
putText(src, temp, cur_pt, FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255), 1, 8, 0);
line(src, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, CV_AA, 0);
imshow("src", src);
}
else if (event == CV_EVENT_LBUTTONUP)
{
sprintf(temp, "(%d,%d)", x, y);
dst.copyTo(src);
cur_pt = Point(x, y);
putText(src, temp, cur_pt, FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 255), 1, 8, 0);
circle(src, cur_pt, 3, cvScalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0);
line(src, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, CV_AA, 0);
imshow("src", src);
src.copyTo(dst);
}
}
int main()
{
namedWindow("src", CV_WINDOW_AUTOSIZE);
src = imread("1.jpg", 1);
if (src.empty())
{
cout << "not find the image" << endl;
}
src.copyTo(dst);
setMouseCallback("src", on_mouse, 0);
imshow("src", src);
waitKey(0);
return 0;
}
注:#pragma warning(disable:4996)是为了规避4996的错误。