]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blob - src/kcf.cpp
17777a685f9ccadd5e2692513b672ce1b0d5ae52
[hercules2020/kcf.git] / src / kcf.cpp
1 #include "kcf.h"
2 #include <numeric>
3 #include <thread>
4 #include <algorithm>
5 #include "threadctx.hpp"
6 #include "debug.h"
7 #include <limits>
8
9 #ifdef FFTW
10 #include "fft_fftw.h"
11 #define FFT Fftw
12 #elif defined(CUFFT)
13 #include "fft_cufft.h"
14 #define FFT cuFFT
15 #else
16 #include "fft_opencv.h"
17 #define FFT FftOpencv
18 #endif
19
20 #ifdef OPENMP
21 #include <omp.h>
22 #endif // OPENMP
23
24 DbgTracer __dbgTracer;
25
26 template <typename T>
27 T clamp(const T& n, const T& lower, const T& upper)
28 {
29     return std::max(lower, std::min(n, upper));
30 }
31
32 template <typename T>
33 void clamp2(T& n, const T& lower, const T& upper)
34 {
35     n = std::max(lower, std::min(n, upper));
36 }
37
38 #if CV_MAJOR_VERSION < 3
39 template<typename _Tp> static inline
40 cv::Size_<_Tp> operator / (const cv::Size_<_Tp>& a, _Tp b)
41 {
42     return cv::Size_<_Tp>(a.width / b, a.height / b);
43 }
44 #endif
45
46 class Kcf_Tracker_Private {
47     friend KCF_Tracker;
48     std::vector<ThreadCtx> threadctxs;
49 };
50
51 KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor,
52                          double output_sigma_factor, int cell_size)
53     : p_cell_size(cell_size), fft(*new FFT()), p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
54       p_lambda(lambda), p_interp_factor(interp_factor), d(*new Kcf_Tracker_Private)
55 {
56 }
57
58 KCF_Tracker::KCF_Tracker() : fft(*new FFT()), d(*new Kcf_Tracker_Private) {}
59
60 KCF_Tracker::~KCF_Tracker()
61 {
62     delete &fft;
63     delete &d;
64 }
65
66 void KCF_Tracker::train(cv::Mat input_rgb, cv::Mat input_gray, double interp_factor)
67 {
68     TRACE("");
69
70     // obtain a sub-window for training
71     get_features(input_rgb, input_gray, p_current_center.x, p_current_center.y,
72                  p_windows_size.width, p_windows_size.height,
73                  p_current_scale).copyTo(model->patch_feats.scale(0));
74     DEBUG_PRINT(model->patch_feats);
75     fft.forward_window(model->patch_feats, model->xf, model->temp);
76     DEBUG_PRINTM(model->xf);
77     model->model_xf = model->model_xf * (1. - interp_factor) + model->xf * interp_factor;
78     DEBUG_PRINTM(model->model_xf);
79
80     if (m_use_linearkernel) {
81         ComplexMat xfconj = model->xf.conj();
82         model->model_alphaf_num = xfconj.mul(model->yf);
83         model->model_alphaf_den = (model->xf * xfconj);
84     } else {
85         // Kernel Ridge Regression, calculate alphas (in Fourier domain)
86         cv::Size sz(Fft::freq_size(feature_size));
87         ComplexMat kf(sz.height, sz.width, 1);
88         (*gaussian_correlation)(kf, model->model_xf, model->model_xf, p_kernel_sigma, true, *this);
89         DEBUG_PRINTM(kf);
90         model->model_alphaf_num = model->yf * kf;
91         model->model_alphaf_den = kf * (kf + p_lambda);
92     }
93     model->model_alphaf = model->model_alphaf_num / model->model_alphaf_den;
94     DEBUG_PRINTM(model->model_alphaf);
95     //        p_model_alphaf = p_yf / (kf + p_lambda);   //equation for fast training
96 }
97
98 static int round_pw2_down(int x)
99 {
100         for (int i = 1; i < 32; i <<= 1)
101             x |= x >> i;
102         x++;
103         return x >> 1;
104 }
105
106
107 void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int fit_size_y)
108 {
109     __dbgTracer.debug = m_debug;
110     TRACE("");
111
112     // check boundary, enforce min size
113     double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
114     if (x1 < 0) x1 = 0.;
115     if (x2 > img.cols - 1) x2 = img.cols - 1;
116     if (y1 < 0) y1 = 0;
117     if (y2 > img.rows - 1) y2 = img.rows - 1;
118
119     if (x2 - x1 < 2 * p_cell_size) {
120         double diff = (2 * p_cell_size - x2 + x1) / 2.;
121         if (x1 - diff >= 0 && x2 + diff < img.cols) {
122             x1 -= diff;
123             x2 += diff;
124         } else if (x1 - 2 * diff >= 0) {
125             x1 -= 2 * diff;
126         } else {
127             x2 += 2 * diff;
128         }
129     }
130     if (y2 - y1 < 2 * p_cell_size) {
131         double diff = (2 * p_cell_size - y2 + y1) / 2.;
132         if (y1 - diff >= 0 && y2 + diff < img.rows) {
133             y1 -= diff;
134             y2 += diff;
135         } else if (y1 - 2 * diff >= 0) {
136             y1 -= 2 * diff;
137         } else {
138             y2 += 2 * diff;
139         }
140     }
141
142     p_init_pose.w = x2 - x1;
143     p_init_pose.h = y2 - y1;
144     p_init_pose.cx = x1 + p_init_pose.w / 2.;
145     p_init_pose.cy = y1 + p_init_pose.h / 2.;
146
147     cv::Mat input_gray, input_rgb = img.clone();
148     if (img.channels() == 3) {
149         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
150         input_gray.convertTo(input_gray, CV_32FC1);
151     } else
152         img.convertTo(input_gray, CV_32FC1);
153
154     // don't need too large image
155     if (p_init_pose.w * p_init_pose.h > 100. * 100.) {
156         std::cout << "resizing image by factor of " << 1 / p_downscale_factor << std::endl;
157         p_resize_image = true;
158         p_init_pose.scale(p_downscale_factor);
159         cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
160         cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
161     }
162
163     // compute win size + fit to fhog cell size
164     p_windows_size.width = round(p_init_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
165     p_windows_size.height = round(p_init_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
166
167     if (fit_size_x == 0 || fit_size_y == 0) {
168         // Round down to the next highest power of 2
169         fit_size = cv::Size(round_pw2_down(p_windows_size.width),
170                             round_pw2_down(p_windows_size.height));
171     } else if (fit_size_x == -1 || fit_size_y == -1) {
172         fit_size =  p_windows_size;
173     } else {
174         fit_size = cv::Size(fit_size_x, fit_size_y);
175     }
176
177     feature_size = fit_size / p_cell_size;
178
179     p_scales.clear();
180     for (int i = -int(p_num_scales) / 2; i <= int(p_num_scales) / 2; ++i)
181         p_scales.push_back(std::pow(p_scale_step, i));
182
183 #ifdef CUFFT
184     if (m_use_linearkernel) {
185         std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
186         std::exit(EXIT_FAILURE);
187     }
188 #endif
189
190     model.reset(new Model(feature_size, p_num_of_feats));
191
192 #ifndef BIG_BATCH
193     for (auto scale: p_scales)
194         d.threadctxs.emplace_back(feature_size, p_num_of_feats, scale);
195 #else
196     d.threadctxs.emplace_back(feature_size, p_num_of_feats, p_num_scales);
197 #endif
198
199     gaussian_correlation.reset(new GaussianCorrelation(1, p_num_of_feats, feature_size));
200
201     p_current_center = p_init_pose.center();
202     p_current_scale = 1.;
203
204     double min_size_ratio = std::max(5. * p_cell_size / p_windows_size.width, 5. * p_cell_size / p_windows_size.height);
205     double max_size_ratio =
206         std::min(floor((img.cols + p_windows_size.width / 3) / p_cell_size) * p_cell_size / p_windows_size.width,
207                  floor((img.rows + p_windows_size.height / 3) / p_cell_size) * p_cell_size / p_windows_size.height);
208     p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
209     p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
210
211     std::cout << "init: img size " << img.size() << std::endl;
212     std::cout << "init: win size " << p_windows_size;
213     if (p_windows_size != fit_size)
214         std::cout << " resized to " << fit_size;
215     std::cout << std::endl;
216     std::cout << "init: FFT size " << feature_size << std::endl;
217     std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
218
219     p_output_sigma = std::sqrt(p_init_pose.w * p_init_pose.h * double(fit_size.area()) / p_windows_size.area())
220            * p_output_sigma_factor / p_cell_size;
221
222     fft.init(feature_size.width, feature_size.height, p_num_of_feats, p_num_scales);
223     fft.set_window(MatDynMem(cosine_window_function(feature_size.width, feature_size.height)));
224
225     // window weights, i.e. labels
226     MatScales gsl(1, feature_size);
227     gaussian_shaped_labels(p_output_sigma, feature_size.width, feature_size.height).copyTo(gsl.plane(0));
228     fft.forward(gsl, model->yf);
229     DEBUG_PRINTM(model->yf);
230
231     // train initial model
232     train(input_rgb, input_gray, 1.0);
233 }
234
235 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat &img, int fit_size_x, int fit_size_y)
236 {
237     init(img, bbox.get_rect(), fit_size_x, fit_size_y);
238 }
239
240 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
241 {
242     BBox_c tmp = bbox;
243     if (p_resize_image) {
244         tmp.scale(p_downscale_factor);
245     }
246     p_current_center = tmp.center();
247 }
248
249 BBox_c KCF_Tracker::getBBox()
250 {
251     BBox_c tmp;
252     tmp.cx = p_current_center.x;
253     tmp.cy = p_current_center.y;
254     tmp.w = p_init_pose.w * p_current_scale;
255     tmp.h = p_init_pose.h * p_current_scale;
256     tmp.a = 0;
257
258     if (p_resize_image)
259         tmp.scale(1 / p_downscale_factor);
260
261     return tmp;
262 }
263
264 double KCF_Tracker::getFilterResponse() const
265 {
266     return this->max_response;
267 }
268
269 void KCF_Tracker::resizeImgs(cv::Mat &input_rgb, cv::Mat &input_gray)
270 {
271     if (p_resize_image) {
272         cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
273         cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
274     }
275 }
276
277 double KCF_Tracker::findMaxReponse(uint &max_idx, cv::Point2d &new_location) const
278 {
279     double max = -1.;
280     max_idx = std::numeric_limits<uint>::max();
281
282 #ifndef BIG_BATCH
283     for (uint j = 0; j < d.threadctxs.size(); ++j) {
284         if (d.threadctxs[j].max.response > max) {
285             max = d.threadctxs[j].max.response;
286             max_idx = j;
287         }
288     }
289 #else
290     for (uint j = 0; j < p_scales.size(); ++j) {
291         if (d.threadctxs[0].max[j].response > max) {
292             max = d.threadctxs[0].max[j].response;
293             max_idx = j;
294         }
295     }
296 #endif
297     assert(max_idx < IF_BIG_BATCH(p_scales.size(), d.threadctxs.size()));
298
299     if (m_visual_debug) {
300         int w = 100; //feature_size.width;
301         int h = 100; //feature_size.height;
302         cv::Mat all_responses(h * p_num_scales, w * p_num_angles,
303                               d.threadctxs[0].response.type(), cv::Scalar::all(0));
304         for (size_t i = 0; i < p_num_scales; ++i) {
305             for (size_t j = 0; j < p_num_angles; ++j) {
306                 cv::Mat tmp = d.threadctxs[IF_BIG_BATCH(0, p_num_angles * i + j)].response.plane(IF_BIG_BATCH(p_num_angles * i + j, 0));
307                 tmp = circshift(tmp, -tmp.cols/2, -tmp.rows/2);
308                 cv::resize(tmp, tmp, cv::Size(w, h));
309                 cv::Mat resp_roi(all_responses, cv::Rect(j * w, i * h, w, h));
310                 tmp.copyTo(resp_roi);
311             }
312         }
313         cv::namedWindow("All responses", CV_WINDOW_AUTOSIZE);
314         cv::imshow("All responses", all_responses);
315     }
316
317     cv::Point2i &max_response_pt = IF_BIG_BATCH(d.threadctxs[0].max[max_idx].loc,        d.threadctxs[max_idx].max.loc);
318     cv::Mat max_response_map     = IF_BIG_BATCH(d.threadctxs[0].response.plane(max_idx), d.threadctxs[max_idx].response.plane(0));
319
320     DEBUG_PRINTM(max_response_map);
321     DEBUG_PRINT(max_response_pt);
322
323     // sub pixel quadratic interpolation from neighbours
324     if (max_response_pt.y > max_response_map.rows / 2) // wrap around to negative half-space of vertical axis
325         max_response_pt.y = max_response_pt.y - max_response_map.rows;
326     if (max_response_pt.x > max_response_map.cols / 2) // same for horizontal axis
327         max_response_pt.x = max_response_pt.x - max_response_map.cols;
328
329
330     if (m_use_subpixel_localization) {
331         new_location = sub_pixel_peak(max_response_pt, max_response_map);
332     } else {
333         new_location = max_response_pt;
334     }
335     DEBUG_PRINT(new_location);
336     return max;
337 }
338
339 void KCF_Tracker::track(cv::Mat &img)
340 {
341     __dbgTracer.debug = m_debug;
342     TRACE("");
343
344     cv::Mat input_gray, input_rgb = img.clone();
345     if (img.channels() == 3) {
346         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
347         input_gray.convertTo(input_gray, CV_32FC1);
348     } else
349         img.convertTo(input_gray, CV_32FC1);
350
351     // don't need too large image
352     resizeImgs(input_rgb, input_gray);
353
354 #ifdef ASYNC
355     for (auto &it : d.threadctxs)
356         it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
357             it.track(*this, input_rgb, input_gray);
358         });
359     for (auto const &it : d.threadctxs)
360         it.async_res.wait();
361
362 #else  // !ASYNC
363     NORMAL_OMP_PARALLEL_FOR
364     for (uint i = 0; i < d.threadctxs.size(); ++i)
365         d.threadctxs[i].track(*this, input_rgb, input_gray);
366 #endif
367
368     cv::Point2d new_location;
369     uint max_idx;
370     max_response = findMaxReponse(max_idx, new_location);
371
372     new_location.x *= double(p_windows_size.width) / fit_size.width;
373     new_location.y *= double(p_windows_size.height) / fit_size.height;
374
375     p_current_center += p_current_scale * p_cell_size * new_location;
376
377     clamp2(p_current_center.x, 0.0, img.cols - 1.0);
378     clamp2(p_current_center.y, 0.0, img.rows - 1.0);
379
380     // sub grid scale interpolation
381     if (m_use_subgrid_scale) {
382         p_current_scale *= sub_grid_scale(max_idx);
383     } else {
384         p_current_scale *= p_scales[max_idx];
385     }
386
387     clamp2(p_current_scale, p_min_max_scale[0], p_min_max_scale[1]);
388
389     // train at newly estimated target position
390     train(input_rgb, input_gray, p_interp_factor);
391 }
392
393 void ThreadCtx::track(const KCF_Tracker &kcf, cv::Mat &input_rgb, cv::Mat &input_gray)
394 {
395     TRACE("");
396
397     BIG_BATCH_OMP_PARALLEL_FOR
398     for (uint i = 0; i < IF_BIG_BATCH(kcf.p_num_scales, 1); ++i)
399     {
400         kcf.get_features(input_rgb, input_gray, kcf.p_current_center.x, kcf.p_current_center.y,
401                          kcf.p_windows_size.width, kcf.p_windows_size.height,
402                          kcf.p_current_scale * IF_BIG_BATCH(kcf.p_scales[i], scale))
403                 .copyTo(patch_feats.scale(i));
404         DEBUG_PRINT(patch_feats.scale(i));
405     }
406
407     kcf.fft.forward_window(patch_feats, zf, temp);
408     DEBUG_PRINTM(zf);
409
410     if (kcf.m_use_linearkernel) {
411         kzf = zf.mul(kcf.model->model_alphaf).sum_over_channels();
412     } else {
413         gaussian_correlation(kzf, zf, kcf.model->model_xf, kcf.p_kernel_sigma, false, kcf);
414         DEBUG_PRINTM(kzf);
415         kzf = kzf.mul(kcf.model->model_alphaf);
416     }
417     kcf.fft.inverse(kzf, response);
418
419     DEBUG_PRINTM(response);
420
421     /* target location is at the maximum response. we must take into
422     account the fact that, if the target doesn't move, the peak
423     will appear at the top-left corner, not at the center (this is
424     discussed in the paper). the responses wrap around cyclically. */
425     double min_val, max_val;
426     cv::Point2i min_loc, max_loc;
427 #ifdef BIG_BATCH
428     for (size_t i = 0; i < kcf.p_scales.size(); ++i) {
429         cv::minMaxLoc(response.plane(i), &min_val, &max_val, &min_loc, &max_loc);
430         DEBUG_PRINT(max_loc);
431         double weight = kcf.p_scales[i] < 1. ? kcf.p_scales[i] : 1. / kcf.p_scales[i];
432         max[i].response = max_val * weight;
433         max[i].loc = max_loc;
434     }
435 #else
436     cv::minMaxLoc(response.plane(0), &min_val, &max_val, &min_loc, &max_loc);
437
438     DEBUG_PRINT(max_loc);
439     DEBUG_PRINT(max_val);
440
441     double weight = scale < 1. ? scale : 1. / scale;
442     max.response = max_val * weight;
443     max.loc = max_loc;
444 #endif
445 }
446
447 // ****************************************************************************
448
449 cv::Mat KCF_Tracker::get_features(cv::Mat &input_rgb, cv::Mat &input_gray, int cx, int cy,
450                                   int size_x, int size_y, double scale) const
451 {
452     cv::Size scaled = cv::Size(floor(size_x * scale), floor(size_y * scale));
453
454     cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, scaled.width, scaled.height);
455     cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, scaled.width, scaled.height);
456
457     // resize to default size
458     if (scaled.area() > fit_size.area()) {
459         // if we downsample use  INTER_AREA interpolation
460         // note: this is just a guess - we may downsample in X and upsample in Y (or vice versa)
461         cv::resize(patch_gray, patch_gray, fit_size, 0., 0., cv::INTER_AREA);
462     } else {
463         cv::resize(patch_gray, patch_gray, fit_size, 0., 0., cv::INTER_LINEAR);
464     }
465
466     // get hog(Histogram of Oriented Gradients) features
467     std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
468
469     // get color rgb features (simple r,g,b channels)
470     std::vector<cv::Mat> color_feat;
471     if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
472         // resize to default size
473         if (scaled.area() > (fit_size / p_cell_size).area()) {
474             // if we downsample use  INTER_AREA interpolation
475             cv::resize(patch_rgb, patch_rgb, fit_size / p_cell_size, 0., 0., cv::INTER_AREA);
476         } else {
477             cv::resize(patch_rgb, patch_rgb, fit_size / p_cell_size, 0., 0., cv::INTER_LINEAR);
478         }
479     }
480
481     if (m_use_color && input_rgb.channels() == 3) {
482         // use rgb color space
483         cv::Mat patch_rgb_norm;
484         patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
485         cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
486         cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
487         cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
488         std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
489         cv::split(patch_rgb_norm, rgb);
490         color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
491     }
492
493     if (m_use_cnfeat && input_rgb.channels() == 3) {
494         std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
495         color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
496     }
497
498     hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
499
500     int size[] = {p_num_of_feats, feature_size.height, feature_size.width};
501     cv::Mat result(3, size, CV_32F);
502     for (uint i = 0; i < hog_feat.size(); ++i)
503         hog_feat[i].copyTo(cv::Mat(size[1], size[2], CV_32FC1, result.ptr(i)));
504
505     return result;
506 }
507
508 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
509 {
510     cv::Mat labels(dim2, dim1, CV_32FC1);
511     int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
512     int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
513
514     double sigma_s = sigma * sigma;
515
516     for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
517         float *row_ptr = labels.ptr<float>(j);
518         double y_s = y * y;
519         for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
520             row_ptr[i] = std::exp(-0.5 * (y_s + x * x) / sigma_s); //-1/2*e^((y^2+x^2)/sigma^2)
521         }
522     }
523
524     // rotate so that 1 is at top-left corner (see KCF paper for explanation)
525     MatDynMem rot_labels = circshift(labels, range_x[0], range_y[0]);
526     // sanity check, 1 at top left corner
527     assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
528
529     return rot_labels;
530 }
531
532 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot) const
533 {
534     cv::Mat rot_patch(patch.size(), CV_32FC1);
535     cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
536
537     // circular rotate x-axis
538     if (x_rot < 0) {
539         // move part that does not rotate over the edge
540         cv::Range orig_range(-x_rot, patch.cols);
541         cv::Range rot_range(0, patch.cols - (-x_rot));
542         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
543
544         // rotated part
545         orig_range = cv::Range(0, -x_rot);
546         rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
547         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
548     } else if (x_rot > 0) {
549         // move part that does not rotate over the edge
550         cv::Range orig_range(0, patch.cols - x_rot);
551         cv::Range rot_range(x_rot, patch.cols);
552         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
553
554         // rotated part
555         orig_range = cv::Range(patch.cols - x_rot, patch.cols);
556         rot_range = cv::Range(0, x_rot);
557         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
558     } else { // zero rotation
559         // move part that does not rotate over the edge
560         cv::Range orig_range(0, patch.cols);
561         cv::Range rot_range(0, patch.cols);
562         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
563     }
564
565     // circular rotate y-axis
566     if (y_rot < 0) {
567         // move part that does not rotate over the edge
568         cv::Range orig_range(-y_rot, patch.rows);
569         cv::Range rot_range(0, patch.rows - (-y_rot));
570         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
571
572         // rotated part
573         orig_range = cv::Range(0, -y_rot);
574         rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
575         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
576     } else if (y_rot > 0) {
577         // move part that does not rotate over the edge
578         cv::Range orig_range(0, patch.rows - y_rot);
579         cv::Range rot_range(y_rot, patch.rows);
580         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
581
582         // rotated part
583         orig_range = cv::Range(patch.rows - y_rot, patch.rows);
584         rot_range = cv::Range(0, y_rot);
585         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
586     } else { // zero rotation
587         // move part that does not rotate over the edge
588         cv::Range orig_range(0, patch.rows);
589         cv::Range rot_range(0, patch.rows);
590         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
591     }
592
593     return rot_patch;
594 }
595
596 // hann window actually (Power-of-cosine windows)
597 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
598 {
599     cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
600     double N_inv = 1. / (static_cast<double>(dim1) - 1.);
601     for (int i = 0; i < dim1; ++i)
602         m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
603     N_inv = 1. / (static_cast<double>(dim2) - 1.);
604     for (int i = 0; i < dim2; ++i)
605         m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
606     cv::Mat ret = m2 * m1;
607     return ret;
608 }
609
610 // Returns sub-window of image input centered at [cx, cy] coordinates),
611 // with size [width, height]. If any pixels are outside of the image,
612 // they will replicate the values at the borders.
613 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height) const
614 {
615     cv::Mat patch;
616
617     int x1 = cx - width / 2;
618     int y1 = cy - height / 2;
619     int x2 = cx + width / 2;
620     int y2 = cy + height / 2;
621
622     // out of image
623     if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
624         patch.create(height, width, input.type());
625         patch.setTo(double(0.f));
626         return patch;
627     }
628
629     int top = 0, bottom = 0, left = 0, right = 0;
630
631     // fit to image coordinates, set border extensions;
632     if (x1 < 0) {
633         left = -x1;
634         x1 = 0;
635     }
636     if (y1 < 0) {
637         top = -y1;
638         y1 = 0;
639     }
640     if (x2 >= input.cols) {
641         right = x2 - input.cols + width % 2;
642         x2 = input.cols;
643     } else
644         x2 += width % 2;
645
646     if (y2 >= input.rows) {
647         bottom = y2 - input.rows + height % 2;
648         y2 = input.rows;
649     } else
650         y2 += height % 2;
651
652     if (x2 - x1 == 0 || y2 - y1 == 0)
653         patch = cv::Mat::zeros(height, width, CV_32FC1);
654     else {
655         cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
656                            cv::BORDER_REPLICATE);
657         //      imshow( "copyMakeBorder", patch);
658         //      cv::waitKey();
659     }
660
661     // sanity check
662     assert(patch.cols == width && patch.rows == height);
663
664     return patch;
665 }
666
667 void KCF_Tracker::GaussianCorrelation::operator()(ComplexMat &result, const ComplexMat &xf, const ComplexMat &yf,
668                                                   double sigma, bool auto_correlation, const KCF_Tracker &kcf)
669 {
670     TRACE("");
671     DEBUG_PRINTM(xf);
672     DEBUG_PRINT(xf_sqr_norm.num_elem);
673     xf.sqr_norm(xf_sqr_norm);
674     for (uint s = 0; s < xf.n_scales; ++s)
675         DEBUG_PRINT(xf_sqr_norm[s]);
676     if (auto_correlation) {
677         yf_sqr_norm = xf_sqr_norm;
678     } else {
679         DEBUG_PRINTM(yf);
680         yf.sqr_norm(yf_sqr_norm);
681     }
682     for (uint s = 0; s < yf.n_scales; ++s)
683         DEBUG_PRINTM(yf_sqr_norm[s]);
684     xyf = auto_correlation ? xf.sqr_mag() : xf * yf.conj(); // xf.muln(yf.conj());
685     DEBUG_PRINTM(xyf);
686
687     // ifft2 and sum over 3rd dimension, we dont care about individual channels
688     ComplexMat xyf_sum = xyf.sum_over_channels();
689     DEBUG_PRINTM(xyf_sum);
690     kcf.fft.inverse(xyf_sum, ifft_res);
691     DEBUG_PRINTM(ifft_res);
692
693     float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
694     for (uint i = 0; i < xf.n_scales; ++i) {
695         cv::Mat plane = ifft_res.plane(i);
696         DEBUG_PRINT(ifft_res.plane(i));
697         cv::exp(-1. / (sigma * sigma) * cv::max((xf_sqr_norm[i] + yf_sqr_norm[0] - 2 * ifft_res.plane(i))
698                 * numel_xf_inv, 0), plane);
699         DEBUG_PRINTM(plane);
700     }
701
702     kcf.fft.forward(ifft_res, result);
703 }
704
705 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
706 {
707     int x = pt.x;
708     int y = pt.y;
709     assert(response.dims == 2); // ensure .cols and .rows are valid
710     if (x < 0) x = response.cols + x;
711     if (y < 0) y = response.rows + y;
712     if (x >= response.cols) x = x - response.cols;
713     if (y >= response.rows) y = y - response.rows;
714
715     return response.at<float>(y, x);
716 }
717
718 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response) const
719 {
720     // find neighbourhood of max_loc (response is circular)
721     // 1 2 3
722     // 4   5
723     // 6 7 8
724     cv::Point2i p1(max_loc.x - 1, max_loc.y - 1), p2(max_loc.x, max_loc.y - 1), p3(max_loc.x + 1, max_loc.y - 1);
725     cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
726     cv::Point2i p6(max_loc.x - 1, max_loc.y + 1), p7(max_loc.x, max_loc.y + 1), p8(max_loc.x + 1, max_loc.y + 1);
727
728     // clang-format off
729     // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
730     cv::Mat A = (cv::Mat_<float>(9, 6) <<
731                  p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
732                  p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
733                  p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
734                  p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
735                  p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
736                  p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
737                  p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
738                  p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
739                  max_loc.x*max_loc.x, max_loc.x*max_loc.y, max_loc.y*max_loc.y, max_loc.x, max_loc.y, 1.f);
740     cv::Mat fval = (cv::Mat_<float>(9, 1) <<
741                     get_response_circular(p1, response),
742                     get_response_circular(p2, response),
743                     get_response_circular(p3, response),
744                     get_response_circular(p4, response),
745                     get_response_circular(p5, response),
746                     get_response_circular(p6, response),
747                     get_response_circular(p7, response),
748                     get_response_circular(p8, response),
749                     get_response_circular(max_loc, response));
750     // clang-format on
751     cv::Mat x;
752     cv::solve(A, fval, x, cv::DECOMP_SVD);
753
754     float a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2), d = x.at<float>(3), e = x.at<float>(4);
755
756     cv::Point2f sub_peak(max_loc.x, max_loc.y);
757     if (b > 0 || b < 0) {
758         sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
759         sub_peak.x = (-2 * c * sub_peak.y - e) / b;
760     }
761
762     return sub_peak;
763 }
764
765 double KCF_Tracker::sub_grid_scale(uint index)
766 {
767     cv::Mat A, fval;
768     if (index >= p_scales.size()) {
769         // interpolate from all values
770         // fit 1d quadratic function f(x) = a*x^2 + b*x + c
771         A.create(p_scales.size(), 3, CV_32FC1);
772         fval.create(p_scales.size(), 1, CV_32FC1);
773         for (size_t i = 0; i < p_scales.size(); ++i) {
774             A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
775             A.at<float>(i, 1) = float(p_scales[i]);
776             A.at<float>(i, 2) = 1;
777             fval.at<float>(i) = d.threadctxs.back().IF_BIG_BATCH(max[i].response, max.response);
778         }
779     } else {
780         // only from neighbours
781         if (index == 0 || index == p_scales.size() - 1)
782            return p_scales[index];
783
784         A = (cv::Mat_<float>(3, 3) <<
785              p_scales[index - 1] * p_scales[index - 1], p_scales[index - 1], 1,
786              p_scales[index + 0] * p_scales[index + 0], p_scales[index + 0], 1,
787              p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
788 #ifdef BIG_BATCH
789         fval = (cv::Mat_<float>(3, 1) <<
790                 d.threadctxs.back().max[index - 1].response,
791                 d.threadctxs.back().max[index + 0].response,
792                 d.threadctxs.back().max[index + 1].response);
793 #else
794         fval = (cv::Mat_<float>(3, 1) <<
795                 d.threadctxs[index - 1].max.response,
796                 d.threadctxs[index + 0].max.response,
797                 d.threadctxs[index + 1].max.response);
798 #endif
799     }
800
801     cv::Mat x;
802     cv::solve(A, fval, x, cv::DECOMP_SVD);
803     float a = x.at<float>(0), b = x.at<float>(1);
804     double scale = p_scales[index];
805     if (a > 0 || a < 0)
806         scale = -b / (2 * a);
807     return scale;
808 }