OpenCV画矩形 #include "stdafx.h" #include <cv.h> #include <highgui.h> //#pragma comment(lib,"cv.lib") //#pragma comment(lib,"cxcore.lib") //#pragma comment(lib,"highgui.lib")
CvRect box; bool Drawing=false; void my_mouse_callback(int event, int x, int y, int flags, void* param);//实现对窗口Window_Name上的对象param添加鼠标响应操作 void DrawRect(IplImage*img,CvRect rect) { cvRectangle(img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0x00,0xff,0x00),2); } int main(int argc,char*argv[]) { box=cvRect(0,0,-1,-1);
IplImage*img=cvCreateImage(cvSize(640,480),IPL_DEPTH_8U,3);
cvZero(img); IplImage*temp=cvCloneImage(img); cvNamedWindow("Draw_Rectangle",CV_WINDOW_AUTOSIZE); cvSetMouseCallback("Draw_Rectangle",my_mouse_callback,(void*)img);//设置鼠标事件回调函数 while(1) { cvCopyImage(img,temp); if(Drawing) DrawRect(temp,box); cvShowImage("Draw_Rectangle",temp);
if(cvWaitKey(100)==27) break; }
cvReleaseImage(&img); cvReleaseImage(&temp); cvDestroyWindow("Draw_Rectangle"); return 0; } void my_mouse_callback(int event,int x,int y,int flags,void*param) { IplImage*img=(IplImage*)param; switch(event) { case CV_EVENT_MOUSEMOVE: { if(Drawing) { box.width=x-box.x; box.height=y-box.y; } } break; case CV_EVENT_LBUTTONDOWN: { Drawing=true; box=cvRect(x,y,0,0); } break; case CV_EVENT_LBUTTONUP: { Drawing=false; if (box.width<0) { box.x+=box.width; box.width*=-1; } if (box.height<0) { box.y+=box.height; box.height*=-1; } DrawRect(img,box); } break; } } |
|