OpenCV学习笔记_鼠标回调函数

bool drawing;
CvRect box;

void draw_box(IplImage* src, CvRect rect){
	cvRectangle(src, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height), cvScalar(255), 1);
}

void callback(int event, int x, int y, int flags, void* param){
	IplImage* image = (IplImage*)param;
	switch(event){
		case CV_EVENT_LBUTTONDOWN:
			drawing = true;
			box = cvRect(x, y, 0, 0);
			break;
		case CV_EVENT_LBUTTONUP:
			drawing = false;
			if(box.width < 0){
				box.width *= -1;
				box.x -= box.width;
			}
			if(box.height < 0){
				box.height *= -1;
				box.y -= box.height;
			}
			//当鼠标左键松开时,在画布上作图
			draw_box(image, box);
			break;
		case CV_EVENT_MOUSEMOVE:
			if(drawing == true){
				box.width = x - box.x;
				box.height = y - box.y;
			}
			else{
				box = cvRect(x, y, 1, 1);
			}
	}
}

int main(void){
	IplImage* src = cvLoadImage("d:\\1.jpeg");
	IplImage* clone = cvCloneImage(src);
	cvNamedWindow("test", 0);
	//设置鼠标回调函数
	cvSetMouseCallback("test", callback, src);
	
	while(1){
		//将两幅图同步
		cvCopy(src, clone);
		if(cvWaitKey(5) == 27){
			break;
		}
		//当还没确定画图的形状时,在clone上作图
		if(drawing){
			draw_box(clone, box);
			cvShowImage("test", clone);
		}
		//当鼠标左键松开,确定画图形状时,显示src上的图片
		else{
			cvShowImage("test", src);
		}
	}
	cvReleaseImage(&src);
	cvDestroyWindow("test");
	cvWaitKey();
	return 0;
}

你可能感兴趣的:(OpenCV学习)