]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blob - src/kcf.cpp
cufft big batch compiles
[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::track(cv::Mat &img)
311 {
312     if (m_debug) std::cout << "NEW FRAME" << '\n';
313     cv::Mat input_gray, input_rgb = img.clone();
314     if (img.channels() == 3) {
315         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
316         input_gray.convertTo(input_gray, CV_32FC1);
317     } else
318         img.convertTo(input_gray, CV_32FC1);
319
320     // don't need too large image
321     resizeImgs(input_rgb, input_gray);
322
323 #ifdef ASYNC
324     for (auto &it : d.threadctxs)
325         it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
326             scale_track(it, input_rgb, input_gray);
327         });
328     for (auto const &it : d.threadctxs)
329         it.async_res.wait();
330
331 #else  // !ASYNC
332     // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
333     NORMAL_OMP_PARALLEL_FOR
334     for (uint i = 0; i < d.threadctxs.size(); ++i)
335         scale_track(d.threadctxs[i], input_rgb, input_gray);
336 #endif
337
338     max_response = -1.;
339     cv::Point2i *max_response_pt = nullptr;
340     cv::Mat *max_response_map = nullptr;
341     uint max_idx = 0;
342
343 #ifndef BIG_BATCH
344     for (uint j = 0; j < d.threadctxs.size(); ++j) {
345         ThreadCtx &it = d.threadctxs[j];
346         if (it.max_response > max_response) {
347             max_response = it.max_response;
348             max_response_pt = &it.max_loc;
349             max_response_map = &it.response;
350             max_idx = j;
351         }
352     }
353 #else
354     // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
355     for (uint j = 0; j < p_scales.size(); ++j) {
356         if (d.threadctxs[0].max_responses[j] > max_response) {
357             max_response = d.threadctxs[0].max_responses[j];
358             max_response_pt = &d.threadctxs[0].max_locs[j];
359             max_response_map = &d.threadctxs[0].response_maps[j];
360             max_idx = j;
361         }
362     }
363 #endif
364
365     DEBUG_PRINTM(*max_response_map);
366     DEBUG_PRINT(*max_response_pt);
367
368     // sub pixel quadratic interpolation from neighbours
369     if (max_response_pt->y > max_response_map->rows / 2) // wrap around to negative half-space of vertical axis
370         max_response_pt->y = max_response_pt->y - max_response_map->rows;
371     if (max_response_pt->x > max_response_map->cols / 2) // same for horizontal axis
372         max_response_pt->x = max_response_pt->x - max_response_map->cols;
373
374     cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
375     DEBUG_PRINT(new_location);
376
377     if (m_use_subpixel_localization)
378         new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
379     DEBUG_PRINT(new_location);
380
381     p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
382     p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
383     if (p_fit_to_pw2) {
384         clamp2(p_pose.cx, 0.0, (img.cols * p_scale_factor_x) - 1);
385         clamp2(p_pose.cy, 0.0, (img.rows * p_scale_factor_y) - 1);
386     } else {
387         clamp2(p_pose.cx, 0.0, img.cols - 1.0);
388         clamp2(p_pose.cy, 0.0, img.rows - 1.0);
389     }
390
391     // sub grid scale interpolation
392     if (m_use_subgrid_scale) {
393         p_current_scale *= sub_grid_scale(max_idx);
394     } else {
395         p_current_scale *= p_scales[max_idx];
396     }
397
398     clamp2(p_current_scale, p_min_max_scale[0], p_min_max_scale[1]);
399
400     // train at newly estimated target position
401     train(input_rgb, input_gray, p_interp_factor);
402 }
403
404 void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray)
405 {
406     // TODO: Move matrices to thread ctx
407     int sizes[3] = {p_num_of_feats, p_windows_size.height, p_windows_size.width};
408     MatDynMem patch_feats(3, sizes, CV_32FC1);
409     MatDynMem temp(3, sizes, CV_32FC1);
410
411 #ifdef BIG_BATCH
412     BIG_BATCH_OMP_PARALLEL_FOR
413     for (uint i = 0; i < p_num_scales; ++i)
414 #endif
415     {
416         get_features(patch_feats, input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy,
417                      this->p_windows_size.width, this->p_windows_size.height,
418                      this->p_current_scale * IF_BIG_BATCH(this->p_scales[i], vars.scale));
419     }
420
421     fft.forward_window(patch_feats, vars.zf, temp);
422     DEBUG_PRINTM(vars.zf);
423
424     if (m_use_linearkernel) {
425         vars.kzf = vars.zf.mul(p_model_alphaf).sum_over_channels();
426     } else {
427         (*gaussian_correlation)(*this, vars.kzf, vars.zf, this->p_model_xf, this->p_kernel_sigma);
428         DEBUG_PRINTM(this->p_model_alphaf);
429         DEBUG_PRINTM(vars.kzf);
430         vars.kzf = vars.kzf.mul(this->p_model_alphaf);
431     }
432     fft.inverse(vars.kzf, vars.response);
433
434     DEBUG_PRINTM(vars.response);
435
436     /* target location is at the maximum response. we must take into
437     account the fact that, if the target doesn't move, the peak
438     will appear at the top-left corner, not at the center (this is
439     discussed in the paper). the responses wrap around cyclically. */
440 #ifdef BIG_BATCH
441     cv::split(vars.response, vars.response_maps);
442
443     for (size_t i = 0; i < p_scales.size(); ++i) {
444         double min_val, max_val;
445         cv::Point2i min_loc, max_loc;
446         cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
447         DEBUG_PRINT(max_loc);
448         double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
449         vars.max_responses[i] = max_val * weight;
450         vars.max_locs[i] = max_loc;
451     }
452 #else
453     double min_val;
454     cv::Point2i min_loc;
455     cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
456
457     DEBUG_PRINT(vars.max_loc);
458
459     double weight = vars.scale < 1. ? vars.scale : 1. / vars.scale;
460     vars.max_response = vars.max_val * weight;
461 #endif
462     return;
463 }
464
465 // ****************************************************************************
466
467 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)
468 {
469     assert(result_3d.size[0] == p_num_of_feats);
470     assert(result_3d.size[1] == size_x);
471     assert(result_3d.size[2] == size_y);
472
473     int size_x_scaled = floor(size_x * scale);
474     int size_y_scaled = floor(size_y * scale);
475
476     cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
477     cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
478
479     // resize to default size
480     if (scale > 1.) {
481         // if we downsample use  INTER_AREA interpolation
482         cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
483     } else {
484         cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
485     }
486
487     // get hog(Histogram of Oriented Gradients) features
488     std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
489
490     // get color rgb features (simple r,g,b channels)
491     std::vector<cv::Mat> color_feat;
492     if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
493         // resize to default size
494         if (scale > 1.) {
495             // if we downsample use  INTER_AREA interpolation
496             cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_AREA);
497         } else {
498             cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_LINEAR);
499         }
500     }
501
502     if (m_use_color && input_rgb.channels() == 3) {
503         // use rgb color space
504         cv::Mat patch_rgb_norm;
505         patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
506         cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
507         cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
508         cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
509         std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
510         cv::split(patch_rgb_norm, rgb);
511         color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
512     }
513
514     if (m_use_cnfeat && input_rgb.channels() == 3) {
515         std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
516         color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
517     }
518
519     hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
520
521     for (uint i = 0; i < hog_feat.size(); ++i) {
522         cv::Mat result_plane(result_3d.dims - 1, result_3d.size + 1, result_3d.cv::Mat::type(), result_3d.ptr<void>(i));
523         result_plane = hog_feat[i];
524     }
525 }
526
527 MatDynMem KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
528 {
529     MatDynMem labels(dim2, dim1, CV_32FC1);
530     int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
531     int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
532
533     double sigma_s = sigma * sigma;
534
535     for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
536         float *row_ptr = labels.ptr<float>(j);
537         double y_s = y * y;
538         for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
539             row_ptr[i] = std::exp(-0.5 * (y_s + x * x) / sigma_s); //-1/2*e^((y^2+x^2)/sigma^2)
540         }
541     }
542
543     // rotate so that 1 is at top-left corner (see KCF paper for explanation)
544     MatDynMem rot_labels = circshift(labels, range_x[0], range_y[0]);
545     // sanity check, 1 at top left corner
546     assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
547
548     return rot_labels;
549 }
550
551 MatDynMem KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
552 {
553     MatDynMem rot_patch(patch.size(), CV_32FC1);
554     cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
555
556     // circular rotate x-axis
557     if (x_rot < 0) {
558         // move part that does not rotate over the edge
559         cv::Range orig_range(-x_rot, patch.cols);
560         cv::Range rot_range(0, patch.cols - (-x_rot));
561         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
562
563         // rotated part
564         orig_range = cv::Range(0, -x_rot);
565         rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
566         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
567     } else if (x_rot > 0) {
568         // move part that does not rotate over the edge
569         cv::Range orig_range(0, patch.cols - x_rot);
570         cv::Range rot_range(x_rot, patch.cols);
571         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
572
573         // rotated part
574         orig_range = cv::Range(patch.cols - x_rot, patch.cols);
575         rot_range = cv::Range(0, x_rot);
576         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
577     } else { // zero rotation
578         // move part that does not rotate over the edge
579         cv::Range orig_range(0, patch.cols);
580         cv::Range rot_range(0, patch.cols);
581         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
582     }
583
584     // circular rotate y-axis
585     if (y_rot < 0) {
586         // move part that does not rotate over the edge
587         cv::Range orig_range(-y_rot, patch.rows);
588         cv::Range rot_range(0, patch.rows - (-y_rot));
589         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
590
591         // rotated part
592         orig_range = cv::Range(0, -y_rot);
593         rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
594         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
595     } else if (y_rot > 0) {
596         // move part that does not rotate over the edge
597         cv::Range orig_range(0, patch.rows - y_rot);
598         cv::Range rot_range(y_rot, patch.rows);
599         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
600
601         // rotated part
602         orig_range = cv::Range(patch.rows - y_rot, patch.rows);
603         rot_range = cv::Range(0, y_rot);
604         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
605     } else { // zero rotation
606         // move part that does not rotate over the edge
607         cv::Range orig_range(0, patch.rows);
608         cv::Range rot_range(0, patch.rows);
609         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
610     }
611
612     return rot_patch;
613 }
614
615 // hann window actually (Power-of-cosine windows)
616 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
617 {
618     cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
619     double N_inv = 1. / (static_cast<double>(dim1) - 1.);
620     for (int i = 0; i < dim1; ++i)
621         m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
622     N_inv = 1. / (static_cast<double>(dim2) - 1.);
623     for (int i = 0; i < dim2; ++i)
624         m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
625     cv::Mat ret = m2 * m1;
626     return ret;
627 }
628
629 // Returns sub-window of image input centered at [cx, cy] coordinates),
630 // with size [width, height]. If any pixels are outside of the image,
631 // they will replicate the values at the borders.
632 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
633 {
634     cv::Mat patch;
635
636     int x1 = cx - width / 2;
637     int y1 = cy - height / 2;
638     int x2 = cx + width / 2;
639     int y2 = cy + height / 2;
640
641     // out of image
642     if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
643         patch.create(height, width, input.type());
644         patch.setTo(double(0.f));
645         return patch;
646     }
647
648     int top = 0, bottom = 0, left = 0, right = 0;
649
650     // fit to image coordinates, set border extensions;
651     if (x1 < 0) {
652         left = -x1;
653         x1 = 0;
654     }
655     if (y1 < 0) {
656         top = -y1;
657         y1 = 0;
658     }
659     if (x2 >= input.cols) {
660         right = x2 - input.cols + width % 2;
661         x2 = input.cols;
662     } else
663         x2 += width % 2;
664
665     if (y2 >= input.rows) {
666         bottom = y2 - input.rows + height % 2;
667         y2 = input.rows;
668     } else
669         y2 += height % 2;
670
671     if (x2 - x1 == 0 || y2 - y1 == 0)
672         patch = cv::Mat::zeros(height, width, CV_32FC1);
673     else {
674         cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
675                            cv::BORDER_REPLICATE);
676         //      imshow( "copyMakeBorder", patch);
677         //      cv::waitKey();
678     }
679
680     // sanity check
681     assert(patch.cols == width && patch.rows == height);
682
683     return patch;
684 }
685
686 void KCF_Tracker::GaussianCorrelation::operator()(const KCF_Tracker &kcf, ComplexMat &result, const ComplexMat &xf,
687                                                    const ComplexMat &yf, double sigma, bool auto_correlation)
688 {
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.mul2(yf.conj());
696     //DEBUG_PRINTM(xyf);
697     kcf.fft.inverse(xyf, ifft_res);
698 #ifdef CUFFT
699     cuda_gaussian_correlation(ifft_res.deviceMem(), k.deviceMem(), xf_sqr_norm.deviceMem(),
700                               auto_correlation ? xf_sqr_norm.deviceMem() : yf_sqr_norm.deviceMem(), sigma,
701                               xf.n_channels, xf.n_scales, kcf.p_roi.height, kcf.p_roi.width);
702 #else
703     // ifft2 and sum over 3rd dimension, we dont care about individual channels
704     //DEBUG_PRINTM(vars.ifft2_res);
705     cv::Mat xy_sum;
706     if (xf.channels() != p_num_scales * p_num_of_feats)
707         xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
708     else
709         xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
710     xy_sum.setTo(0);
711     for (int y = 0; y < vars.ifft2_res.rows; ++y) {
712         float *row_ptr = vars.ifft2_res.ptr<float>(y);
713         float *row_ptr_sum = xy_sum.ptr<float>(y);
714         for (int x = 0; x < vars.ifft2_res.cols; ++x) {
715             for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
716                 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
717                     row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
718                     (row_ptr + x * vars.ifft2_res.channels() +
719                      (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
720                     0.f);
721             }
722         }
723     }
724     DEBUG_PRINTM(xy_sum);
725
726     std::vector<cv::Mat> scales;
727     cv::split(xy_sum, scales);
728
729     float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
730     for (uint i = 0; i < xf.n_scales; ++i) {
731         cv::Mat in_roi(vars.in_all, cv::Rect(0, i * scales[0].rows, scales[0].cols, scales[0].rows));
732         cv::exp(
733             -1. / (sigma * sigma) *
734                 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),
735             in_roi);
736         DEBUG_PRINTM(in_roi);
737     }
738 #endif
739     kcf.fft.forward(k, result);
740     return;
741 }
742
743 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
744 {
745     int x = pt.x;
746     int y = pt.y;
747     if (x < 0) x = response.cols + x;
748     if (y < 0) y = response.rows + y;
749     if (x >= response.cols) x = x - response.cols;
750     if (y >= response.rows) y = y - response.rows;
751
752     return response.at<float>(y, x);
753 }
754
755 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response)
756 {
757     // find neighbourhood of max_loc (response is circular)
758     // 1 2 3
759     // 4   5
760     // 6 7 8
761     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);
762     cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
763     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);
764
765     // clang-format off
766     // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
767     cv::Mat A = (cv::Mat_<float>(9, 6) <<
768                  p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
769                  p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
770                  p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
771                  p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
772                  p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
773                  p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
774                  p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
775                  p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
776                  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);
777     cv::Mat fval = (cv::Mat_<float>(9, 1) <<
778                     get_response_circular(p1, response),
779                     get_response_circular(p2, response),
780                     get_response_circular(p3, response),
781                     get_response_circular(p4, response),
782                     get_response_circular(p5, response),
783                     get_response_circular(p6, response),
784                     get_response_circular(p7, response),
785                     get_response_circular(p8, response),
786                     get_response_circular(max_loc, response));
787     // clang-format on
788     cv::Mat x;
789     cv::solve(A, fval, x, cv::DECOMP_SVD);
790
791     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);
792
793     cv::Point2f sub_peak(max_loc.x, max_loc.y);
794     if (b > 0 || b < 0) {
795         sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
796         sub_peak.x = (-2 * c * sub_peak.y - e) / b;
797     }
798
799     return sub_peak;
800 }
801
802 double KCF_Tracker::sub_grid_scale(uint index)
803 {
804     cv::Mat A, fval;
805     if (index >= p_scales.size()) {
806         // interpolate from all values
807         // fit 1d quadratic function f(x) = a*x^2 + b*x + c
808         A.create(p_scales.size(), 3, CV_32FC1);
809         fval.create(p_scales.size(), 1, CV_32FC1);
810         for (size_t i = 0; i < p_scales.size(); ++i) {
811             A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
812             A.at<float>(i, 1) = float(p_scales[i]);
813             A.at<float>(i, 2) = 1;
814 #ifdef BIG_BATCH
815             fval.at<float>(i) = d.threadctxs.back().max_responses[i];
816 #else
817             fval.at<float>(i) = d.threadctxs[i].max_response;
818 #endif
819         }
820     } else {
821         // only from neighbours
822         if (index == 0 || index == p_scales.size() - 1)
823            return p_scales[index];
824
825         A = (cv::Mat_<float>(3, 3) <<
826              p_scales[index - 1] * p_scales[index - 1], p_scales[index - 1], 1,
827              p_scales[index + 0] * p_scales[index + 0], p_scales[index + 0], 1,
828              p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
829 #ifdef BIG_BATCH
830         fval = (cv::Mat_<float>(3, 1) <<
831                 d.threadctxs.back().max_responses[index - 1],
832                 d.threadctxs.back().max_responses[index + 0],
833                 d.threadctxs.back().max_responses[index + 1]);
834 #else
835         fval = (cv::Mat_<float>(3, 1) <<
836                 d.threadctxs[index - 1].max_response,
837                 d.threadctxs[index + 0].max_response,
838                 d.threadctxs[index + 1].max_response);
839 #endif
840     }
841
842     cv::Mat x;
843     cv::solve(A, fval, x, cv::DECOMP_SVD);
844     float a = x.at<float>(0), b = x.at<float>(1);
845     double scale = p_scales[index];
846     if (a > 0 || a < 0)
847         scale = -b / (2 * a);
848     return scale;
849 }