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