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