程序:

wKiom1PsXzWBieKjAABuoTH-oDE769.jpg

核心函数:

回调函数,注册回调函数cvSetMouseCallback

代码:

#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include <iostream>
CvRect rect=cvRect(-1,-1,0,0);
CvPoint pt1=cvPoint(0,0);
CvPoint pt2=cvPoint(0,0);
bool draw=false;
void DrawRect(IplImage* src,CvPoint pt1,CvPoint pt2)
{
cvRectangle(src,pt1,pt2,cvScalar(0,0,255,NULL));
}
void my_mouse_callback(int event,int x,int y,int flags,void* param) //回调函数
{
//static bool draw=false;
//static int rectx=-1;
//static int recty=-1;
//static int rectwidth=0;
//static int rectheight=0;
switch(event)
{
case CV_EVENT_LBUTTONDOWN:
{
std::cout<<"CV_EVENT_LBUTTONDOWN"<<std::endl;
draw=true;
//rect.x=x;
//rect.y=y;
pt1.x=x;
pt1.y=y;
}
break;
case CV_EVENT_MOUSEMOVE:
{
pt2.x=x;
pt2.y=y;
//std::cout<<"CV_EVENT_MOUSEMOVE"<<std::endl;
//if(draw)
//{
std::cout<<"x:"<<x<<std::endl;
std::cout<<"y:"<<y<<std::endl;
rect.width=x-rect.x;
rect.height=y-rect.y;
//}
}
break;
case CV_EVENT_LBUTTONUP:
{
std::cout<<"CV_EVENT_LBUTTONUP"<<std::endl;
draw=false;
pt2.x=x;
pt2.y=y;
//if(rect.width<0)
//{
//rect.x=rect.x+rect.width;
//rect.width=rect.width*(-1);
//}
//if(rect.height<0)
//{
//rect.y=rect.y+rect.height;
//rect.height=rect.height*(-1);
//}
//rect.x=rectx;
//rect.y=recty;
//rect.width=rectwidth;
//rect.height=rectheight;
//std::cout<<"rectx: "<<rectx<<std::endl;
//std::cout<<"recty: "<<recty<<std::endl;
//std::cout<<"rectwidth: "<<rectwidth<<std::endl;
//std::cout<<"rectheight: "<<rectheight<<std::endl;
DrawRect((IplImage*)param,pt1,pt2);
}
break;
}
}
int MouseRectangle(int argc,char** argv)  //注册回调函数
{
IplImage* src=cvLoadImage("e:\\picture\\4.jpg");
IplImage* temp=cvCloneImage(src);
cvNamedWindow("src",0);   //注意这里第二个参数最好为0,要不大图可能画的矩形坐标不准
//cvShowImage("src",src);
cvSetMouseCallback("src",my_mouse_callback,(void*)src);
while(1)
{
cvCopyImage(src,temp);
if(draw)
{
DrawRect(temp,pt1,pt2);  //让画的矩形具有连续性
}
cvShowImage("src",temp);
if(cvWaitKey(15)==27)
{break;}
}
//cvWaitKey(0);
cvDestroyWindow("src");
cvReleaseImage(&src);
return 0;
}