Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/cpp/camshiftdemo.cpp
16337 views
1
#include <opencv2/core/utility.hpp>
2
#include "opencv2/video/tracking.hpp"
3
#include "opencv2/imgproc.hpp"
4
#include "opencv2/videoio.hpp"
5
#include "opencv2/highgui.hpp"
6
7
#include <iostream>
8
#include <ctype.h>
9
10
using namespace cv;
11
using namespace std;
12
13
Mat image;
14
15
bool backprojMode = false;
16
bool selectObject = false;
17
int trackObject = 0;
18
bool showHist = true;
19
Point origin;
20
Rect selection;
21
int vmin = 10, vmax = 256, smin = 30;
22
23
// User draws box around object to track. This triggers CAMShift to start tracking
24
static void onMouse( int event, int x, int y, int, void* )
25
{
26
if( selectObject )
27
{
28
selection.x = MIN(x, origin.x);
29
selection.y = MIN(y, origin.y);
30
selection.width = std::abs(x - origin.x);
31
selection.height = std::abs(y - origin.y);
32
33
selection &= Rect(0, 0, image.cols, image.rows);
34
}
35
36
switch( event )
37
{
38
case EVENT_LBUTTONDOWN:
39
origin = Point(x,y);
40
selection = Rect(x,y,0,0);
41
selectObject = true;
42
break;
43
case EVENT_LBUTTONUP:
44
selectObject = false;
45
if( selection.width > 0 && selection.height > 0 )
46
trackObject = -1; // Set up CAMShift properties in main() loop
47
break;
48
}
49
}
50
51
string hot_keys =
52
"\n\nHot keys: \n"
53
"\tESC - quit the program\n"
54
"\tc - stop the tracking\n"
55
"\tb - switch to/from backprojection view\n"
56
"\th - show/hide object histogram\n"
57
"\tp - pause video\n"
58
"To initialize tracking, select the object with mouse\n";
59
60
static void help()
61
{
62
cout << "\nThis is a demo that shows mean-shift based tracking\n"
63
"You select a color objects such as your face and it tracks it.\n"
64
"This reads from video camera (0 by default, or the camera number the user enters\n"
65
"Usage: \n"
66
" ./camshiftdemo [camera number]\n";
67
cout << hot_keys;
68
}
69
70
const char* keys =
71
{
72
"{help h | | show help message}{@camera_number| 0 | camera number}"
73
};
74
75
int main( int argc, const char** argv )
76
{
77
VideoCapture cap;
78
Rect trackWindow;
79
int hsize = 16;
80
float hranges[] = {0,180};
81
const float* phranges = hranges;
82
CommandLineParser parser(argc, argv, keys);
83
if (parser.has("help"))
84
{
85
help();
86
return 0;
87
}
88
int camNum = parser.get<int>(0);
89
cap.open(camNum);
90
91
if( !cap.isOpened() )
92
{
93
help();
94
cout << "***Could not initialize capturing...***\n";
95
cout << "Current parameter's value: \n";
96
parser.printMessage();
97
return -1;
98
}
99
cout << hot_keys;
100
namedWindow( "Histogram", 0 );
101
namedWindow( "CamShift Demo", 0 );
102
setMouseCallback( "CamShift Demo", onMouse, 0 );
103
createTrackbar( "Vmin", "CamShift Demo", &vmin, 256, 0 );
104
createTrackbar( "Vmax", "CamShift Demo", &vmax, 256, 0 );
105
createTrackbar( "Smin", "CamShift Demo", &smin, 256, 0 );
106
107
Mat frame, hsv, hue, mask, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj;
108
bool paused = false;
109
110
for(;;)
111
{
112
if( !paused )
113
{
114
cap >> frame;
115
if( frame.empty() )
116
break;
117
}
118
119
frame.copyTo(image);
120
121
if( !paused )
122
{
123
cvtColor(image, hsv, COLOR_BGR2HSV);
124
125
if( trackObject )
126
{
127
int _vmin = vmin, _vmax = vmax;
128
129
inRange(hsv, Scalar(0, smin, MIN(_vmin,_vmax)),
130
Scalar(180, 256, MAX(_vmin, _vmax)), mask);
131
int ch[] = {0, 0};
132
hue.create(hsv.size(), hsv.depth());
133
mixChannels(&hsv, 1, &hue, 1, ch, 1);
134
135
if( trackObject < 0 )
136
{
137
// Object has been selected by user, set up CAMShift search properties once
138
Mat roi(hue, selection), maskroi(mask, selection);
139
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
140
normalize(hist, hist, 0, 255, NORM_MINMAX);
141
142
trackWindow = selection;
143
trackObject = 1; // Don't set up again, unless user selects new ROI
144
145
histimg = Scalar::all(0);
146
int binW = histimg.cols / hsize;
147
Mat buf(1, hsize, CV_8UC3);
148
for( int i = 0; i < hsize; i++ )
149
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255);
150
cvtColor(buf, buf, COLOR_HSV2BGR);
151
152
for( int i = 0; i < hsize; i++ )
153
{
154
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255);
155
rectangle( histimg, Point(i*binW,histimg.rows),
156
Point((i+1)*binW,histimg.rows - val),
157
Scalar(buf.at<Vec3b>(i)), -1, 8 );
158
}
159
}
160
161
// Perform CAMShift
162
calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
163
backproj &= mask;
164
RotatedRect trackBox = CamShift(backproj, trackWindow,
165
TermCriteria( TermCriteria::EPS | TermCriteria::COUNT, 10, 1 ));
166
if( trackWindow.area() <= 1 )
167
{
168
int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6;
169
trackWindow = Rect(trackWindow.x - r, trackWindow.y - r,
170
trackWindow.x + r, trackWindow.y + r) &
171
Rect(0, 0, cols, rows);
172
}
173
174
if( backprojMode )
175
cvtColor( backproj, image, COLOR_GRAY2BGR );
176
ellipse( image, trackBox, Scalar(0,0,255), 3, LINE_AA );
177
}
178
}
179
else if( trackObject < 0 )
180
paused = false;
181
182
if( selectObject && selection.width > 0 && selection.height > 0 )
183
{
184
Mat roi(image, selection);
185
bitwise_not(roi, roi);
186
}
187
188
imshow( "CamShift Demo", image );
189
imshow( "Histogram", histimg );
190
191
char c = (char)waitKey(10);
192
if( c == 27 )
193
break;
194
switch(c)
195
{
196
case 'b':
197
backprojMode = !backprojMode;
198
break;
199
case 'c':
200
trackObject = 0;
201
histimg = Scalar::all(0);
202
break;
203
case 'h':
204
showHist = !showHist;
205
if( !showHist )
206
destroyWindow( "Histogram" );
207
else
208
namedWindow( "Histogram", 1 );
209
break;
210
case 'p':
211
paused = !paused;
212
break;
213
default:
214
;
215
}
216
}
217
218
return 0;
219
}
220
221