#include <cv.h>
#include <highgui.h>
#include<cxcore.h>
#pragma comment(lib, "cv.lib")
#pragma comment(lib, "cxcore.lib")
#pragma comment(lib, "highgui.lib")
#define true 1
#define false 0
void my_mouse_callback(int event,int x,int y,int flags,void* param);
CvRect box;
IplImage* image;
IplImage* temp;
char drawing_box=false;
// a little subroutine to draw a box on to an image
void draw_box(IplImage* img,CvRect rect)//画矩形函数
{
cvRectangle(img,cvPoint(box.x,box.y),cvPoint(box.x+box.width,box.y+box.height),cvScalar(0,255,255,0),1,8,0);
}
int main()
{
box=cvRect(-1,-1,0,0);
image =cvCreateImage(cvSize(500,500),IPL_DEPTH_8U,3);
cvZero(image);
temp =cvCloneImage(image);
cvNamedWindow("Box example",1);
cvNamedWindow("image",1);
cvSetMouseCallback("Box example",my_mouse_callback,(void*) image);
while(1){
cvCopyImage(image,temp);
/* if(drawing_box) draw_box(image,box);
cvShowImage("image",image);*/
if(drawing_box) draw_box(temp,box);
cvShowImage("Box example",temp);
cvShowImage("image",temp);
if(cvWaitKey(500)==27) break;
}
cvReleaseImage(&image);
cvReleaseImage(&temp);
cvDestroyWindow("Box example");
cvDestroyWindow("image");
return 0;
} //event 指定鼠标事件类型
//int x y 为事件发生时鼠标位置的x,y坐标值。
//第四个参数flags 制定了事件在事件发生时的不同状态
void my_mouse_callback(int event,int x,int y,int flags,void* param)
{
IplImage* image= (IplImage*) param;
switch(event)
{
case CV_EVENT_MOUSEMOVE://鼠标移动
{
if(drawing_box)
{
box.width=x-box.x;
box.height=y-box.y;
}
}
break;
case CV_EVENT_LBUTTONDOWN://鼠标左键按下
{
drawing_box=true;
box=cvRect(x,y,0,0);
}
break;
case CV_EVENT_LBUTTONUP://鼠标抬起
{
drawing_box=false;
if(box.width<0)//鼠标往右上角画的时候
{
box.x=box.x+box.width;
box.width*=-1;
}
if(box.height<0)
{
box.y+=box.height;
box.height*=-1;
}
draw_box(image,box);
}
break;
}
}