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