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