#include<highgui.h>
#include<cv.h>
#include<stdio.h>
//#include<iostream>
//鼠标事件
CvPoint down;
CvPoint up;
CvRect rect;
IplImage *dst;
void on_mouse(int event,int x,int y,int flags,void *param)
{
//鼠标事件分为两个部分,左键按下和左键弹起
IplImage *image=(IplImage *)param;
if (event == CV_EVENT_LBUTTONDOWN) //左键按下
{
down.y=y;
down.x=x;
printf("%d %d",down.x,down.y);
cvDestroyWindow("image.roi");
cvReleaseImage(&dst);
}
if (event==CV_EVENT_LBUTTONUP)//左键弹起
{
up.y=y;
up.x=x;
// cvRectangle(image,down,up,cvScalarAll(0),1,8,0);
if( (up.y > down.y) && (up.x > down.x))//避免出现错误
{
rect.x=down.x;
rect.y=down.y;
rect.height=up.y-down.y;
rect.width=up.x-down.x;
printf(" %d %d\n",up.x,up.y);
cvSetImageROI(image,rect);//设置掩膜
dst=cvCloneImage(image);//复制图片
cvNamedWindow("image.roi",CV_WINDOW_AUTOSIZE);
cvShowImage("image.roi",dst);
}
}
}
int main(int argc,char **argv)
{
IplImage *image;
image=cvLoadImage("1.bmp",1);
cvNamedWindow("image",CV_WINDOW_AUTOSIZE);
cvShowImage("image",image);
cvSetMouseCallback("image",on_mouse,(void *)image);
cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseImage(&image);
return 0;
}