利用opencv3.0点击图片显示对应坐标(x,y)

(VS2013+Opencv3.0)

  1. h文件:
#include 
#include 
using namespace std;
using namespace cv;

void on_mouseDisplayC(int event, int x, int y, int flags, void* ustc);
int DisplayCoordinates(IplImage* src1);
  1. 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;
}
  1. 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);
}
  1. 运行
    利用opencv3.0点击图片显示对应坐标(x,y)_第1张图片

你可能感兴趣的:(C++,opencv,计算机视觉)