OpenCV之利用鼠标获取坐标
好久没有更新博客了,今天临时起意,将以前写的示例代码整理了一下,暂且发布一篇,希望对大家有用!
代码一:点击时显示坐标,鼠标移动时不显示。
[cpp]
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
IplImage* src=0;
void on_mouse( int event, int x, int y, int flags, void* ustc)
{
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA);
if( event == CV_EVENT_LBUTTONDOWN )
{
CvPoint pt = cvPoint(x,y);
char temp[16];
sprintf(temp,"(%d,%d)",pt.x,pt.y);
cvPutText(src,temp, pt, &font, cvScalar(255, 255, 255, 0));
cvCircle( src, pt, 2,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 );
cvShowImage( "src", src );
}
}
int main()
{
src=cvLoadImage("lena.jpg",1);
cvNamedWindow("src",1);
cvSetMouseCallback( "src", on_mouse, 0 );
cvShowImage("src",src);
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&src);
return 0;
}
代码二:鼠标移动时显示坐标,点击时不显示坐标
[cpp]
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
IplImage* src=0;
IplImage* dst=0;
void on_mouse( int event, int x, int y, int flags, void* ustc)
{
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA);
if( event == CV_EVENT_MOUSEMOVE )
{
cvCopy(dst,src);
CvPoint pt = cvPoint(x,y);
char temp[16];
sprintf(temp,"(%d,%d)",pt.x,pt.y);
cvPutText(src,temp, pt, &font, cvScalar(255, 255, 255, 0));
cvCircle( src, pt, 2,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 );
cvShowImage( "src", src );
}
}
int main()
{
src=cvLoadImage("lena.jpg",1);
dst=cvCloneImage(src);
cvNamedWindow("src",1);
cvSetMouseCallback( "src", on_mouse, 0 );
cvShowImage("src",src);
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&src);
cvReleaseImage(&dst);
return 0;
}
代码三:鼠标移动和点击时均显示坐标
[cpp]
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
IplImage* src=0;
IplImage* dst=0;
void on_mouse( int event, int x, int y, int flags, void* ustc)
{
char temp[16];
CvPoint pt;
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, CV_AA);
if( event == CV_EVENT_MOUSEMOVE )
{
cvCopy(dst,src);
sprintf(temp,"(%d,%d)",x,y);
pt = cvPoint(x,y);
cvPutText(src,temp, pt, &font, cvScalar(255, 255, 255, 0));
cvCircle( src, pt, 2,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 );
cvShowImage( "src", src );
}
else if( event == CV_EVENT_LBUTTONDOWN )
{
//cvCopy(dst,src);
sprintf(temp,"(%d,%d)",x,y);
pt = cvPoint(x,y);
cvPutText(src,temp, pt, &font, cvScalar(255, 255, 255, 0));
cvCircle( src, pt, 2,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 );
cvCopy(src,dst);
cvShowImage( "src", src );
}
}
int main()
{
src=cvLoadImage("lena.jpg",1);
dst=cvCloneImage(src);
cvNamedWindow("src",1);
cvSetMouseCallback( "src", on_mouse, 0 );
cvShowImage("src",src);
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&src);
cvReleaseImage(&dst);
return 0;
}
代码四,上面的代码在边界处处理的不好,坐标值显示的不完全,下面是对代码三的改进。下面的代码还将点约束在图像的几何区域范围内。
[cpp]
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
//注意参数是有符号短整型,该函数的作用是使i限定为[a,b]区间内
int bound(short i,short a,short b)
{
return min(max(i,min(a,b)),
补充:软件开发 , C++ ,