#include<cv.h>
#include<highgui.hpp>
#include"highgui.h"
using namespace std;
#include <iostream>
using namespace cv;
//回调函数:
void my_mouse_callback(
int event,int x,int y,int flag,void *para
);
CvRect box;
bool drawing_box = false;
void draw_box(IplImage * img, CvRect rect) {
cvRectangle(
img,
CvPoint(rect.x, rect.y),
CvPoint(rect.x + rect.width, rect.y + rect.height),
CvScalar(0, 0, 255)
);
}
int main()
{
box = CvRect(-1, -1, 0, 0);
IplImage *rect = cvCreateImage(
CvSize(200, 200),
IPL_DEPTH_8U,
3
);
cvZero(0);
IplImage *temp = cvCloneImage(rect);
cvNamedWindow("Box Example",CV_WINDOW_AUTOSIZE);
//注册回调函数
cvSetMouseCallback("Box Example", my_mouse_callback, (void *)rect);
while (1) {
cvCopy(rect, temp);
if (drawing_box)draw_box(temp, box);
cvShowImage("Box Example", temp);
if(cvWaitKey(15)==27)break;
}
cvReleaseImage(&rect);
cvReleaseImage(&temp);
cvDestroyWindow("Box Example");
}
void my_mouse_callback(int event, int x, int y, int flag, void *para) {
IplImage * img = (IplImage *)para;
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.width;
box.width *= -1;
}
if (box.height < 0) {
box.y += box.width;
box.height *= -1;
}
draw_box(img, box);
}
break;
default:
break;
}
}