Refer from http://blog.csdn.net/qq_23880193/article/details/41974849
刚刚写好的在图像中运用鼠标事件,现在要写的是在视频序列中运用鼠标事件
- #include<opencv2/imgproc/imgproc.hpp>
- #include<opencv2/imgproc/types_c.h>
- #include<opencv2/highgui/highgui.hpp>
- #include<opencv2/core/core.hpp>
- #include<iostream>
- #include<vector>
- #include<opencv2/nonfree/features2d.hpp>
- #include<opencv2/legacy/legacy.hpp>
- #include<opencv2/features2d/features2d.hpp>
- #include<opencv2/calib3d/calib3d.hpp>
- #include<opencv2/video/tracking.hpp>
- using namespace cv;
- using namespace std;
- Point coord;//储存初始坐标
- Rect sqart;//储存矩形框的起始坐标以及长度和宽度
- bool draw;
- bool flag = 0;//这个标志位是用在如果要将矩形标定的部分单独显示在一个窗口时使用的
- Mat frame;
- Mat dst;//感兴趣区域图像
- void onMouse(int event, int x, int y, int flags, void *param)
- {
- //显示鼠标的当前坐标
- cout << "Event:" << event << endl;
- cout << "x=" << x << " " << "y=" << y << endl;
- cout << "flags:" << endl;
- cout << "param" << param << endl;
- //这个if必须放在switch之前
- if (draw)
- {
- //用MIN得到左上点作为矩形框的其实坐标,如果不加这个,画矩形时只能向一个方向进行
- sqart.x = MIN(x, coord.x);
- sqart.y = MIN(y, coord.y);
- sqart.width = abs(coord.x - x);
- sqart.height = abs(coord.y - y);
- //防止矩形区域超出图像的范围
- sqart &= Rect(0, 0, frame.cols, frame.rows);
- }
- switch (event)
- {
- case CV_EVENT_LBUTTONDOWN:
- coord = Point(x, y);
- sqart = Rect(x, y, 0, 0);
- draw = true;
- break;
- case CV_EVENT_LBUTTONUP:
- draw = false;
- flag = 1;
- break;
- }
- }
- int main()
- {
- char c;
- VideoCapture capture(0);
- namedWindow("Mouse", 1);
- setMouseCallback("Mouse", onMouse, 0);
- //由于视频序列的每一帧都在跟新,所以不会出现连环嵌套的状况
- while (1)
- {
- capture >> frame;
- if (frame.empty())
- return -1;
- //将矩形框得到矩形区域用另一个窗口显示
- if ((flag == 1) && sqart.height > 0 && sqart.width > 0)
- {
- dst = frame(Rect(sqart.x, sqart.y, sqart.width, sqart.height));
- namedWindow("dst");
- imshow("dst", dst);
- flag = 0;
- }
- rectangle(frame, sqart, Scalar(0, 0, 255), 3);
- imshow("Mouse", frame);
- c = waitKey(20);
- if (c == 27)
- break;
- }
- return 0;
- }
- 以上程序是以打开摄像头为例的,由于没有好的背景,下面的截图是用的一个视频段截出来的结果,程序中只要把capture.open(0)改为capture.open(视频路径)即可。