(VS2013+Opencv3.0)
- h文件:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;void on_mouseDisplayC(int event, int x, int y, int flags, void* ustc);
int DisplayCoordinates(IplImage* src1);
- CPP文件:
#include "DisplayCoordinates.h"IplImage* src = 0;
IplImage* dst = 0;void on_mouseDisplayC(int event, int x, int y, int flags, void* ustc)//event鼠标事件代号,x,y鼠标坐标,flags拖拽和键盘操作的代号
{static CvPoint pre_pt = { -1,-1 };//初始坐标static CvPoint cur_pt = { -1,-1 };//实时坐标CvFont font;cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA);///初始化字体char temp[16];if (event == CV_EVENT_LBUTTONDOWN)//左键按下,读取初始坐标,并在图像该点出划圆{cvCopy(dst, src);//将原始图片复制到dst中;sprintf_s(temp, "(%d,%d)", x, y);pre_pt = cvPoint(x, y);cvPutText(src, temp, pre_pt, &font, cvScalar(0, 255, 0, 0));//显示坐标cvCircle(src, pre_pt, 3, cvScalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0);//划圆cvShowImage("src", src);cvCopy(src, dst);}else if (event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON))//若鼠标在滑动,左键没有按下{cvCopy(dst, src);sprintf_s(temp, "(%d,%d)", x, y);cur_pt = cvPoint(x, y);cvPutText(src, temp, cur_pt, &font, cvScalar(0, 255, 0, 0));//实时显示鼠标移动的坐标cvShowImage("src", src);}else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))//event鼠标事件代号,x,y鼠标坐标,flags拖拽和键盘操作的代号 {cvCopy(dst, src);sprintf_s(temp, "(%d,%d)", x, y);cur_pt = cvPoint(x, y);cvPutText(src, temp, cur_pt, &font, cvScalar(0, 255, 0, 0));cvRectangle(src, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, 8, 0);//根据初始点和结束点将矩形画到图片上cvShowImage("src", src);}else if (event == CV_EVENT_LBUTTONUP)//左键松开,将在图片dst上画矩形{sprintf_s(temp, "(%d,%d)", x, y);cur_pt = cvPoint(x, y);cvPutText(src, temp, cur_pt, &font, cvScalar(0, 255, 0, 0));cvCircle(src, cur_pt, 3, cvScalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0);//绘制圆形cvRectangle(src, pre_pt, cur_pt, cvScalar(0, 255, 0, 0), 1, 8, 0);//绘制矩形cvShowImage("src", src);cvCopy(src, dst);}
}
int DisplayCoordinates(IplImage* src1)
{//src = cvLoadImage("原标准模板.bmp", 1);src = cvCloneImage(src1);dst = cvCloneImage(src1);cvNamedWindow("src", 0);//定义一个“src”窗口cvSetMouseCallback("src", on_mouseDisplayC, 0);//调用回调函数cvShowImage("src", src);waitKey();return 0;
}
- main主函数调用:
#include "DisplayCoordinates.h"
using namespace std;
using namespace cv;void main()
{ Mat src;src = imread("1.png");IplImage* pB1 = &IplImage(src);//Mat 转IplImage//IplImage *img = cvCloneImage(pB1);DisplayCoordinates(pB1);
}
- 运行