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