forked from 3fffff/BACF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBACF.cpp
574 lines (454 loc) · 15 KB
/
BACF.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
@@ -0,0 +1,578 @@
#include <opencv2/core/utility.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <cstring>
using namespace cv;
using namespace std;
struct Params {
//filter settings
cv::Size model_sz = cv::Size(50, 50);
float target_padding = 2.0;
//learning parameters
float update_rate = 0.013;
float sigma_factor = 1.0 / 16.0;
//scale settings
float scale_step = 1.05;
int num_scales = 1;
}p;
struct TrackedRegion {
TrackedRegion() { }
TrackedRegion(const cv::Point2i init_center, const cv::Size init_size) : center(init_center), size(init_size) { }
TrackedRegion(const cv::Rect box) : center(box.x + round((float)box.size().width / 2.0),
box.y + round((float)box.size().height / 2.0)),
size(box.size()) { }
cv::Rect Rect() const {
return cv::Rect(center.x - floor((float)size.width / 2.0),
center.y - floor((float)size.height / 2.0),
size.width, size.height);
}
TrackedRegion resize(const float factor) const {
TrackedRegion newRegion;
newRegion.center = center;
newRegion.size = cv::Size(round(size.width *factor),
round(size.height*factor));
return newRegion;
}
cv::Point2i center;
cv::Size size;
};
class BACF {
public:
/*
* Initialize the tracker on the region specified in the image
*/
void initialize(const cv::Mat& image, const cv::Rect region);
/*
* Return the current bounding box of the target as estimated by the tracker
*/
cv::Rect getBoundingBox() const;
/*
* Update the current estimate of the targets position from the image with the current bounding box estimate
*/
void detect(const cv::Mat& image);
/*
* Update the current tracker model, from the current best position estimated by the tracker in the image provided
*/
void update(const cv::Mat& image);
//protected:
bool initImpl(const Mat& image, const Rect2d& boundingBox);
bool updateImpl(const Mat& image, Rect2d& boundingBox);
private:
//internal functions
std::vector<cv::Mat> fft2(const cv::Mat featureData);
int shift_index(const int index, const int length) const;
cv::Mat make_labels(const cv::Size matrix_size, const cv::Size target_size, const float sigma_factor) const;
void compute_ADMM();
cv::Mat compute_response(const std::vector<cv::Mat>& filter, const std::vector<cv::Mat>& sample);
std::vector<cv::Mat> compute_feature_vec(const cv::Mat& patch);
void update_impl(const cv::Mat& image, const TrackedRegion& region, const float update_rate);
cv::Mat detect_impl(const cv::Mat& image, const TrackedRegion& region);
cv::Mat channelMultiply(std::vector<cv::Mat> a, std::vector<cv::Mat> b, int flags, bool conjb);
cv::Mat extractTrackedRegion(const cv::Mat image, const TrackedRegion region, const cv::Size output_sz);
cv::Mat extractTrackedRegionSpec(cv::Mat model, const cv::Size output_sz);
//parameters set on construction
//internal state variables
cv::Mat labelsf; //label function
cv::Mat window; //cos (hann) window
std::vector<cv::Mat> model_xf; //regularization marix
std::vector<cv::Mat> filterf;
float scale_factor;
TrackedRegion target;
}; //end definition
bool BACF::initImpl(const Mat& image, const Rect2d& boundingBox) {
initialize(image, boundingBox);
return true;
}
bool BACF::updateImpl(const Mat& image, Rect2d& boundingBox) {
detect(image);
cv::Rect new_bounding_box = getBoundingBox();
update(image);
boundingBox = new_bounding_box;
return true;
}
void BACF::initialize(const cv::Mat& image, const cv::Rect region) {
//convert region into internal representation defined from center pixel and size
//including the padding
target = TrackedRegion(region).resize(p.target_padding);
scale_factor = sqrt((float)target.size.area() / (float)p.model_sz.area());
float resize_factor = (1.0 / scale_factor) * (1.0 / p.target_padding);
TrackedRegion resized_target = target.resize(resize_factor);
//create labels
labelsf = make_labels(p.model_sz, resized_target.size, p.sigma_factor);
//create window function
cv::createHanningWindow(window, p.model_sz, CV_32FC1);
//create the initial filter from the init patch
update_impl(image, target, 1.0);
}
void BACF::update(const cv::Mat& image) {
update_impl(image, target, 2);
}
//private functions
std::vector<cv::Mat> BACF::compute_feature_vec(const cv::Mat& patch) {
//convert the data type to float
cv::Mat feature_data;
patch.convertTo(feature_data, CV_32FC1, 1.0 / 255.0, -0.5);
std::vector<cv::Mat> feature_vec = fft2(feature_data);
return feature_vec;
}
cv::Rect BACF::getBoundingBox() const {
TrackedRegion return_bb = target.resize(1.0 / p.target_padding);
return return_bb.Rect();
}
cv::Mat BACF::extractTrackedRegion(const cv::Mat image, const TrackedRegion region, const cv::Size output_sz) {
int xMin = region.center.x - floor(((float)region.size.width) / 2.0);
int yMin = region.center.y - floor(((float)region.size.height) / 2.0);
int xMax = xMin + region.size.width;
int yMax = yMin + region.size.height;
int xMinPad, xMaxPad, yMinPad, yMaxPad;
if (xMin < 0) {
xMinPad = -xMin;
}
else {
xMinPad = 0;
}
if (xMax > image.size().width) {
xMaxPad = xMax - image.size().width;
}
else {
xMaxPad = 0;
}
if (yMin < 0) {
yMinPad = -yMin;
}
else {
yMinPad = 0;
}
if (yMax > image.size().height) {
yMaxPad = yMax - image.size().height;
}
else {
yMaxPad = 0;
}
//compute the acual rectangle we will extract from the image
cv::Rect extractionRegion = cv::Rect(xMin + xMinPad,
yMin + yMinPad,
(xMax - xMin) - xMaxPad - xMinPad,
(yMax - yMin) - yMaxPad - yMinPad);
//make sure the patch is not completely outside the image
if (extractionRegion.x + extractionRegion.width > 0 &&
extractionRegion.y + extractionRegion.height > 0 &&
extractionRegion.x < image.cols &&
extractionRegion.y < image.rows) {
cv::Mat real_patch(region.size, image.type());
//replicate along borders if needed
if (xMinPad > 0 || xMaxPad > 0 || yMinPad > 0 || yMaxPad > 0) {
cv::copyMakeBorder(image(extractionRegion), real_patch, yMinPad,
yMaxPad, xMinPad, xMaxPad, cv::BORDER_REPLICATE);
}
else {
real_patch = image(extractionRegion);
}
if (!(real_patch.size().width == region.size.width && real_patch.size().height == region.size.height)) {
//cout << "kasst" << endl;
}
cv::Mat ds_patch;
cv::resize(real_patch, ds_patch, output_sz);
return ds_patch;
}
else {
cv::Mat dummyRegion = cv::Mat::zeros(region.size, image.type());
cv::Mat ds_patch;
cv::resize(dummyRegion, ds_patch, output_sz);
return ds_patch;
}
}
void BACF::update_impl(const cv::Mat& image, const TrackedRegion& region, const float frame) {
//extract pixels to use for update
cv::Mat pixels = extractTrackedRegion(image, region, p.model_sz);
std::vector<cv::Mat> feature_vecf = compute_feature_vec(pixels);
if (frame == 1.0) {
model_xf = feature_vecf;
}
else {
for (int i = 0; i<model_xf.size(); i++)
model_xf[i] = ((1 - p.update_rate)*model_xf[i]) + (p.update_rate* feature_vecf[i]);
}
compute_ADMM();
}
cv::Mat BACF::channelMultiply(std::vector<cv::Mat> a, std::vector<cv::Mat> b, int flags, bool conjb) {
//CV_Assert(a.size() == b.size());
cv::Mat prod;
cv::Mat sum = cv::Mat::zeros(a[0].size(), a[0].type());
for (unsigned int i = 0; i < a.size(); ++i) {
cv::Mat ca = a[i];
cv::Mat cb = b[i];
cv::mulSpectrums(a[i], b[i], prod, flags, conjb);
sum += prod;
}
return sum;
}
void BACF::detect(const cv::Mat& image) {
cv::Mat response = detect_impl(image, target);
// cout << response;
cv::Point2i maxpos;
//resp_newton
cv::minMaxLoc(response, NULL, NULL, NULL, &maxpos);
cv::Point2i translation(round(shift_index(maxpos.x, response.cols)*scale_factor),
round(shift_index(maxpos.y, response.rows)*scale_factor));
target.center = target.center + translation;
}
cv::Mat BACF::detect_impl(const cv::Mat& image, const TrackedRegion& region) {
cv::Mat pixels = extractTrackedRegion(image, region, p.model_sz);
std::vector<cv::Mat> feature_vecf = compute_feature_vec(pixels);
return compute_response(filterf, feature_vecf);
}
std::vector<cv::Mat> BACF::fft2(const cv::Mat featureData) {
std::vector<cv::Mat> channels(featureData.channels());
std::vector<cv::Mat> channelsf(featureData.channels());
cv::split(featureData, channels);
for (size_t i = 0; i < channels.size(); ++i) {
cv::Mat windowed;
cv::multiply(channels[i], window, windowed);
cv::dft(windowed, channelsf[i], 0);
}
return channelsf;
}
int BACF::shift_index(const int index, const int length) const {
int shifted_index;
if (index > length / 2) {
shifted_index = -length + index;
}
else {
shifted_index = index;
}
return shifted_index;
}
cv::Mat BACF::make_labels(const cv::Size matrix_size, const cv::Size target_size, const float sigma_factor) const {
cv::Mat new_labels(matrix_size.height, matrix_size.width, CV_32F);
const float sigma = std::sqrt((float)target_size.area()) * sigma_factor;
const float constant = -0.5 / pow(sigma, 2);
for (int x = 0; x < matrix_size.width; x++) {
for (int y = 0; y < matrix_size.height; y++) {
int shift_x = shift_index(x, matrix_size.width);
int shift_y = shift_index(y, matrix_size.height);
float value = std::exp(constant*(std::pow(shift_x, 2) + std::pow(shift_y, 2)));
new_labels.at<float>(y, x) = value;
}
}
cv::Mat labels_dft;
cv::dft(new_labels, labels_dft);
return labels_dft;
}
void BACF::compute_ADMM() {
std::vector<cv::Mat>l_f;
std::vector<cv::Mat>h_f;
cv::Mat lp = cv::Mat::zeros(model_xf[0].size(), model_xf[0].type());
int mu = 1;
float T = (float)p.model_sz.area();
cv::Mat S_xx = channelMultiply(model_xf, model_xf, 0, true);
filterf.clear();
for (int i = 0; i < 3; i++)
{
l_f.push_back(lp);
h_f.push_back(lp);
filterf.push_back(lp);
}
for (int i = 0; i < 2; i++)
{
cv::Mat B = S_xx + (T*mu);
cv::Mat S_lx = channelMultiply(l_f, model_xf,0,true);
cv::Mat S_hx = channelMultiply(h_f, model_xf,0,true);
for (int j = 0; j<model_xf.size(); j++)
{
cv::Mat mlabelf, S_xxyf, mS_lx, mS_hx,h;
cv::mulSpectrums(labelsf, model_xf[j], mlabelf,0,false);
cv::mulSpectrums(S_xx, mlabelf, S_xxyf,0,false);
cv::mulSpectrums(S_lx, model_xf[j], mS_lx,0,false);
cv::mulSpectrums(S_hx, model_xf[j], mS_hx,0,false);
filterf[j] = ( mlabelf.mul(1/(T*mu)) -l_f[j].mul(1/mu)+ h_f[j])-((S_xxyf.mul(1 / (T*mu)) - mS_lx.mul(1 / mu) + mS_hx)/B);
cv::dft((filterf[j].mul(mu) + l_f[j]), h, cv::DFT_INVERSE | cv::DFT_SCALE);
cv::Mat t = extractTrackedRegionSpec(h.mul(1/mu), p.model_sz);
cv::dft(t, h_f[j]);
l_f[j] = l_f[j] + ((filterf[j].mul(mu) - h_f[j]));
}
mu = 10;
}
}
cv::Mat BACF::extractTrackedRegionSpec(cv::Mat model, const cv::Size output_sz)
{
cv::Rect r(output_sz.width / 4, output_sz.height / 4, output_sz.width / 2, output_sz.height / 2);
TrackedRegion tr = r;
cv::Mat lp1 = cv::Mat::zeros(model.size(), model.type());
cv::Mat lp = extractTrackedRegion(model, tr, output_sz / 2);
lp.copyTo(lp1(r));
//std::cout << lp1;
return lp1;
}
cv::Mat BACF::compute_response(const std::vector<cv::Mat>& filter, const std::vector<cv::Mat>& sample) {
cv::Mat response;
cv::Mat resp_dft = channelMultiply(filter, sample, 0, false);
cv::dft(resp_dft, response, cv::DFT_INVERSE|cv::DFT_SCALE);
//cout << response;
return response;
}
class BoxExtractor {
public:
Rect2d extract(Mat img);
Rect2d extract(const std::string& windowName, Mat img, bool showCrossair = true);
struct handlerT {
bool isDrawing;
Rect2d box;
Mat image;
// initializer list
handlerT() : isDrawing(false) {};
}params;
private:
static void mouseHandler(int event, int x, int y, int flags, void *param);
void opencv_mouse_callback(int event, int x, int y, int, void *param);
};
int main(int argc, char** argv) {
// show help
if (argc<2) {
cout <<
" Usage: example_tracking_kcf <video_name>\n"
" examples:\n"
" example_tracking_kcf Bolt/img/%04.jpg\n"
" example_tracking_kcf faceocc2.webm\n"
<< endl;
return 0;
}
// ROI selector
BoxExtractor box;
// create the tracker
// set input video
std::string video = argv[1];
VideoCapture cap(video);
Mat frame;
// get bounding box
cap >> frame;
Rect2d roi = box.extract("tracker", frame);
//quit if ROI was not selected
if (roi.width == 0 || roi.height == 0)
return 0;
BACF *tracker = new BACF();
tracker->initialize(frame, roi);
// do the tracking
printf("Start the tracking process, press ESC to quit.\n");
for (;; ) {
// get frame from the video
cap >> frame;
// stop the program if no more images
if (frame.rows == 0 || frame.cols == 0)
break;
// update the tracking result
tracker->updateImpl(frame, roi);
// draw the tracked object
rectangle(frame, roi, Scalar(255, 0, 0), 2, 1);
// show image with the tracked object
imshow("tracker", frame);
//quit on ESC button
if (waitKey(1) == 27)break;
}
}
void BoxExtractor::mouseHandler(int event, int x, int y, int flags, void *param) {
BoxExtractor *self = static_cast<BoxExtractor*>(param);
self->opencv_mouse_callback(event, x, y, flags, param);
}
void BoxExtractor::opencv_mouse_callback(int event, int x, int y, int, void *param) {
handlerT * data = (handlerT*)param;
switch (event) {
// update the selected bounding box
case EVENT_MOUSEMOVE:
if (data->isDrawing) {
data->box.width = x - data->box.x;
data->box.height = y - data->box.y;
}
break;
// start to select the bounding box
case EVENT_LBUTTONDOWN:
data->isDrawing = true;
data->box = cvRect(x, y, 0, 0);
break;
// cleaning up the selected bounding box
case EVENT_LBUTTONUP:
data->isDrawing = false;
if (data->box.width < 0) {
data->box.x += data->box.width;
data->box.width *= -1;
}
if (data->box.height < 0) {
data->box.y += data->box.height;
data->box.height *= -1;
}
break;
}
}
Rect2d BoxExtractor::extract(Mat img) {
return extract("Bounding Box Extractor", img);
}
Rect2d BoxExtractor::extract(const std::string& windowName, Mat img, bool showCrossair) {
int key = 0;
// show the image and give feedback to user
imshow(windowName, img);
printf("Select an object to track and then press SPACE/BACKSPACE/ENTER button!\n");
// copy the data, rectangle should be drawn in the fresh image
params.image = img.clone();
// select the object
setMouseCallback(windowName, mouseHandler, (void *)¶ms);
// end selection process on SPACE (32) BACKSPACE (27) or ENTER (13)
while (!(key == 32 || key == 27 || key == 13)) {
// draw the selected object
rectangle(
params.image,
params.box,
Scalar(255, 0, 0), 2, 1
);
// draw cross air in the middle of bounding box
if (showCrossair) {
// horizontal line
line(
params.image,
Point((int)params.box.x, (int)(params.box.y + params.box.height / 2)),
Point((int)(params.box.x + params.box.width), (int)(params.box.y + params.box.height / 2)),
Scalar(255, 0, 0), 2, 1
);
// vertical line
line(
params.image,
Point((int)(params.box.x + params.box.width / 2), (int)params.box.y),
Point((int)(params.box.x + params.box.width / 2), (int)(params.box.y + params.box.height)),
Scalar(255, 0, 0), 2, 1
);
}
// show the image bouding box
imshow(windowName, params.image);
// reset the image
params.image = img.clone();
//get keyboard event
key = waitKey(1);
}
return params.box;
}