1 #include <iostream>
2 #include <opencv2/imgcodecs.hpp>
3 #include <opencv2/imgproc.hpp>
4 #include <opencv2/videoio.hpp>
5 #include <opencv2/highgui.hpp>
6 #include <opencv2/video.hpp>
7
8 using namespace cv;
9 using namespace std;
10
main(int argc,char ** argv)11 int main(int argc, char **argv)
12 {
13 const string about =
14 "This sample demonstrates the camshift algorithm.\n"
15 "The example file can be downloaded from:\n"
16 " https://www.bogotobogo.com/python/OpenCV_Python/images/mean_shift_tracking/slow_traffic_small.mp4";
17 const string keys =
18 "{ h help | | print this help message }"
19 "{ @image |<none>| path to image file }";
20 CommandLineParser parser(argc, argv, keys);
21 parser.about(about);
22 if (parser.has("help"))
23 {
24 parser.printMessage();
25 return 0;
26 }
27 string filename = parser.get<string>("@image");
28 if (!parser.check())
29 {
30 parser.printErrors();
31 return 0;
32 }
33
34 VideoCapture capture(filename);
35 if (!capture.isOpened()){
36 //error in opening the video input
37 cerr << "Unable to open file!" << endl;
38 return 0;
39 }
40
41 Mat frame, roi, hsv_roi, mask;
42 // take first frame of the video
43 capture >> frame;
44
45 // setup initial location of window
46 Rect track_window(300, 200, 100, 50); // simply hardcoded the values
47
48 // set up the ROI for tracking
49 roi = frame(track_window);
50 cvtColor(roi, hsv_roi, COLOR_BGR2HSV);
51 inRange(hsv_roi, Scalar(0, 60, 32), Scalar(180, 255, 255), mask);
52
53 float range_[] = {0, 180};
54 const float* range[] = {range_};
55 Mat roi_hist;
56 int histSize[] = {180};
57 int channels[] = {0};
58 calcHist(&hsv_roi, 1, channels, mask, roi_hist, 1, histSize, range);
59 normalize(roi_hist, roi_hist, 0, 255, NORM_MINMAX);
60
61 // Setup the termination criteria, either 10 iteration or move by atleast 1 pt
62 TermCriteria term_crit(TermCriteria::EPS | TermCriteria::COUNT, 10, 1);
63
64 while(true){
65 Mat hsv, dst;
66 capture >> frame;
67 if (frame.empty())
68 break;
69 cvtColor(frame, hsv, COLOR_BGR2HSV);
70 calcBackProject(&hsv, 1, channels, roi_hist, dst, range);
71
72 // apply camshift to get the new location
73 RotatedRect rot_rect = CamShift(dst, track_window, term_crit);
74
75 // Draw it on image
76 Point2f points[4];
77 rot_rect.points(points);
78 for (int i = 0; i < 4; i++)
79 line(frame, points[i], points[(i+1)%4], 255, 2);
80 imshow("img2", frame);
81
82 int keyboard = waitKey(30);
83 if (keyboard == 'q' || keyboard == 27)
84 break;
85 }
86 }
87