/*
* 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大家庭。
Opencv学习记录之鼠标窗口响应
最新推荐文章于 2022-05-26 10:58:22 发布