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