Opencv打开摄像头VideoCapture 以及鼠标画图事件
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Rect box;
bool gotBox = false;
Mat image;
char temp[16];
void mouseHandler(int event, int x, int y, int flags, void *param)
{
static Point pre_pt = (-1,-1);
static Point cur_pt = (-1,-1);
if (event == CV_EVENT_LBUTTONDOWN)
{
sprintf(temp,"(%d,%d)",x,y);
pre_pt = Point(x,y);
putText(image,temp,pre_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255),1,8);
circle(image,pre_pt,2,Scalar(255,0,0,0),CV_FILLED,CV_AA,0);
imshow("Test",image);
}
else if (event == CV_EVENT_MOUSEMOVE && !(flags & CV_EVENT_FLAG_LBUTTON))
{
sprintf(temp,"(%d,%d)",x,y);
cur_pt = Point(x,y);
putText(image,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255));
imshow("Test",image);
}
else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))
{
sprintf(temp,"(%d,%d)",x,y);
cur_pt = Point(x,y);
putText(image,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255));
rectangle(image,pre_pt,cur_pt,Scalar(0,255,0,0),1,8,0);
imshow("Test",image);
}
else if (event == CV_EVENT_LBUTTONUP)
{
sprintf(temp,"(%d,%d)",x,y);
cur_pt = Point(x,y);
putText(image,temp,cur_pt,FONT_HERSHEY_SIMPLEX,0.5,Scalar(0,0,0,255));
circle(image,pre_pt,2,Scalar(255,0,0,0),CV_FILLED,CV_AA,0);
rectangle(image,pre_pt,cur_pt,Scalar(0,255,0,0),1,8,0);
int width = abs(pre_pt.x - cur_pt.x);
int height = abs(pre_pt.y - cur_pt.y);
if (width == 0 || height == 0)
{
printf("width == 0 || height == 0");
return;
}
box=Rect(pre_pt.x,pre_pt.y,width,height);
gotBox=true;
imshow("Test",image);
}
}
int main(int argc, char * argv[])
{
VideoCapture capture;
capture.open(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH, 340);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
if (!capture.isOpened())
{
cout << "capture device failed to open!" << endl;
return 1;
}
namedWindow("Test", CV_WINDOW_AUTOSIZE);
setMouseCallback("Test", mouseHandler, NULL);
Mat frame;
Mat first_gray;
while(!gotBox)
{
capture >> frame;
frame.copyTo(image);
if (cvWaitKey(33) == 27) { return 0; }
}
setMouseCallback("Test", NULL, NULL);
printf("Initial Tracking Box = x:%d y:%d h:%d w:%d\n", box.x, box.y, box.width, box.height);
Mat current_gray;
while(capture.read(frame))
{
frame.copyTo(image);
cvtColor(frame, current_gray, CV_RGB2GRAY);
rectangle(frame, box, Scalar(0,0,255));
imshow("Test", frame);
if(cvWaitKey(20)==27){break;}
}
return 0;
}