Opencv學習記錄之鼠標窗口響應

/*
 *	Description: drawing box in the window by opencv.
 *	
 *	by pbImage at 2013-07-24
*/
#include <opencv2/opencv.hpp>

using namespace cv;

Rect box;
bool drawing_box = false;

void drawBoxEx(Mat& image, CvRect box)
{
	rectangle( image, cvPoint(box.x, box.y), cvPoint(box.x + box.width, box.y + box.height), cv::Scalar(255, 0, 0), 1);
} 
//bounding box mouse callback
void mouseHandler(int event, int x, int y, int flags, void *param)
{
	Mat* tmp = (Mat*)param;
	Mat tempFm = *tmp;
	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.height;
				box.height *= -1;
			}

			drawBoxEx(tempFm, box);
		}
		break;
	}
}


int main()
{
	VideoCapture camera(0);
	if (!camera.isOpened())
	{
		printf("Open camera failed\n");
		return -1;
	}
	namedWindow("video");

	Mat frame;
	camera>>frame;
	cvSetMouseCallback( "video", mouseHandler, (void*)&frame );

	char setMouse = 0;
	while(1)
	{
		camera>>frame;

		if (box.width > 0 && box.height > 0)
		{
			drawBoxEx(frame, box);
		}
		imshow("video", frame);

		if (waitKey(1) == 27)
		{
			break;
		}
	}
	return 0;
}
代碼比較簡單,貼在這裏的目的主要是爲了方便自己日後使用,直接copy。當然,同時也分享給OpenCV新成員,歡迎大家進入CV大家庭。
發佈了33 篇原創文章 · 獲贊 5 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章