在OpenCV中利用滑鼠繪製直線
阿新 • • 發佈:2019-02-11
滑鼠繪製直線原始碼:
#include <cv.h> #include <highgui.h> #include <stdio.h> #pragma comment( lib, "cv.lib" ) #pragma comment( lib, "cxcore.lib" ) #pragma comment( lib, "highgui.lib" ) IplImage* src = 0; IplImage* dst = 0; 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}; 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); sprintf(temp,"(%d,%d)",x,y); pre_pt = cvPoint(x,y); cvPutText(src,temp, pre_pt, &font, cvScalar(0,0, 0, 255)); 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(temp,"(%d,%d)",x,y); cur_pt = cvPoint(x,y); cvPutText(src,temp, cur_pt, &font, cvScalar(0,0, 0, 255)); cvLine(src, pre_pt, cur_pt, cvScalar(0,255,0,0), 1, CV_AA, 0 ); cvShowImage( "src", src ); } else if( event == CV_EVENT_LBUTTONUP ) { sprintf(temp,"(%d,%d)",x,y); cur_pt = cvPoint(x,y); cvPutText(src,temp, cur_pt, &font, cvScalar(0,0, 0, 255)); cvCircle( src, cur_pt, 3,cvScalar(255,0,0,0) ,CV_FILLED, CV_AA, 0 ); cvLine( src, pre_pt, cur_pt, cvScalar(0,255,0,0), 1, CV_AA, 0 ); cvShowImage( "src", src ); cvCopy(src,dst); } } 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; }