opencv鼠标绘制直线 C++版
因为需要在图片上标记直线,所以从网上找了相应的参考资料。但大多都是c风格的,于是自己就写了一个c++风格的。
opencv2.4.11,win8.1,vs2013
#include <cv.h>
#include <highgui.h>
#include <string>
cv::Mat src;
cv::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 };
if (event == CV_EVENT_LBUTTONDOWN)
{
dst.copyTo(src);
pre_pt = cvPoint(x, y);
cv::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))
{
dst.copyTo(src);
cur_pt = cvPoint(x, y);
cv::line(src, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, CV_AA, 0);
imshow("src", src);
}
else if (event == CV_EVENT_LBUTTONUP)
{
dst.copyTo(src);
cur_pt = cvPoint(x, y);
cv::circle(src, cur_pt, 3, cvScalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0);
cv::line(src, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, CV_AA, 0);
imshow("src", src);
src.copyTo(dst);
}
}
int main()
{
cv::namedWindow("src", CV_WINDOW_AUTOSIZE);
src = cv::imread("lena.jpg", 1);
src.copyTo(dst);
cv::setMouseCallback("src", on_mouse, 0);
cv::imshow("src", src);
cv::waitKey(0);
return 0;
}