opencv+vs+C++鼠标在图像上画直线

因为需要在图片上标记直线,所以从网上找了相应的参考资料。但大多都是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的错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值