]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blob - src/kcf.cpp
8c08ef0a25cfed48c588b3ffc34a022d1dc35469
[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);
560     cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
561
562     geometric_transformations(patch_gray, scale, size_x, size_y, angle);
563
564     // get hog(Histogram of Oriented Gradients) features
565     FHoG::extract(patch_gray, vars, 2, p_cell_size, 9);
566
567     // get color rgb features (simple r,g,b channels)
568     std::vector<cv::Mat> color_feat;
569     if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3)
570         geometric_transformations(patch_rgb, scale, size_x, size_y, angle);
571
572     if (m_use_color && input_rgb.channels() == 3) {
573         // use rgb color space
574         cv::Mat patch_rgb_norm;
575         patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
576         cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
577         cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
578         cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
579         std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
580         cv::split(patch_rgb_norm, rgb);
581         color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
582     }
583
584     if (m_use_cnfeat && input_rgb.channels() == 3) {
585         std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
586         color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
587     }
588     BIG_BATCH_OMP_ORDERED
589     vars.patch_feats.insert(vars.patch_feats.end(), color_feat.begin(), color_feat.end());
590     return;
591 }
592
593 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
594 {
595     cv::Mat labels(dim2, dim1, CV_32FC1);
596     int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
597     int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
598
599     double sigma_s = sigma * sigma;
600
601     for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
602         float *row_ptr = labels.ptr<float>(j);
603         double y_s = y * y;
604         for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
605             row_ptr[i] = float(std::exp(-0.5 * (y_s + x * x) / sigma_s)); //-1/2*e^((y^2+x^2)/sigma^2)
606         }
607     }
608
609     // rotate so that 1 is at top-left corner (see KCF paper for explanation)
610 #ifdef CUFFT
611     cv::Mat tmp = circshift(labels, range_x[0], range_y[0]);
612     tmp.copyTo(p_rot_labels);
613
614     assert(p_rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
615     return tmp;
616 #else
617     cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
618     // sanity check, 1 at top left corner
619     assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
620
621     return rot_labels;
622 #endif
623 }
624
625 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
626 {
627     cv::Mat rot_patch(patch.size(), CV_32FC1);
628     cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
629
630     // circular rotate x-axis
631     if (x_rot < 0) {
632         // move part that does not rotate over the edge
633         cv::Range orig_range(-x_rot, patch.cols);
634         cv::Range rot_range(0, patch.cols - (-x_rot));
635         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
636
637         // rotated part
638         orig_range = cv::Range(0, -x_rot);
639         rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
640         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
641     } else if (x_rot > 0) {
642         // move part that does not rotate over the edge
643         cv::Range orig_range(0, patch.cols - x_rot);
644         cv::Range rot_range(x_rot, patch.cols);
645         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
646
647         // rotated part
648         orig_range = cv::Range(patch.cols - x_rot, patch.cols);
649         rot_range = cv::Range(0, x_rot);
650         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
651     } else { // zero rotation
652         // move part that does not rotate over the edge
653         cv::Range orig_range(0, patch.cols);
654         cv::Range rot_range(0, patch.cols);
655         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
656     }
657
658     // circular rotate y-axis
659     if (y_rot < 0) {
660         // move part that does not rotate over the edge
661         cv::Range orig_range(-y_rot, patch.rows);
662         cv::Range rot_range(0, patch.rows - (-y_rot));
663         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
664
665         // rotated part
666         orig_range = cv::Range(0, -y_rot);
667         rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
668         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
669     } else if (y_rot > 0) {
670         // move part that does not rotate over the edge
671         cv::Range orig_range(0, patch.rows - y_rot);
672         cv::Range rot_range(y_rot, patch.rows);
673         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
674
675         // rotated part
676         orig_range = cv::Range(patch.rows - y_rot, patch.rows);
677         rot_range = cv::Range(0, y_rot);
678         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
679     } else { // zero rotation
680         // move part that does not rotate over the edge
681         cv::Range orig_range(0, patch.rows);
682         cv::Range rot_range(0, patch.rows);
683         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
684     }
685
686     return rot_patch;
687 }
688
689 // hann window actually (Power-of-cosine windows)
690 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
691 {
692     cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
693     double N_inv = 1. / (static_cast<double>(dim1) - 1.);
694     for (int i = 0; i < dim1; ++i)
695         m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
696     N_inv = 1. / (static_cast<double>(dim2) - 1.);
697     for (int i = 0; i < dim2; ++i)
698         m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
699     cv::Mat ret = m2 * m1;
700     return ret;
701 }
702
703 // Returns sub-window of image input centered at [cx, cy] coordinates),
704 // with size [width, height]. If any pixels are outside of the image,
705 // they will replicate the values at the borders.
706 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height/*, int angle*/)
707 {
708     cv::Mat patch;
709
710     int x1 = cx - width / 2;
711     int y1 = cy - height / 2;
712     int x2 = cx + width / 2;
713     int y2 = cy + height / 2;
714
715     // out of image
716     if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
717         patch.create(height, width, input.type());
718         patch.setTo(double(0.f));
719         return patch;
720     }
721
722     int top = 0, bottom = 0, left = 0, right = 0;
723
724     // fit to image coordinates, set border extensions;
725     if (x1 < 0) {
726         left = -x1;
727         x1 = 0;
728     }
729     if (y1 < 0) {
730         top = -y1;
731         y1 = 0;
732     }
733     if (x2 >= input.cols) {
734         right = x2 - input.cols + width % 2;
735         x2 = input.cols;
736     } else
737         x2 += width % 2;
738
739     if (y2 >= input.rows) {
740         bottom = y2 - input.rows + height % 2;
741         y2 = input.rows;
742     } else
743         y2 += height % 2;
744
745     //     cv::Point2f center(x1+width/2, y1+height/2);
746     //     cv::Mat r = getRotationMatrix2D(center, angle, 1.0);
747     //
748     //     cv::Mat input_clone = input.clone();
749     //
750     //     cv::warpAffine(input_clone, input_clone, r, cv::Size(input_clone.cols, input_clone.rows), cv::INTER_LINEAR,
751     //     cv::BORDER_CONSTANT);
752     cv::Mat input_clone;
753     if (m_visual_debug) {
754         input_clone = input.clone();
755         cv::rectangle(input_clone, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0));
756         cv::line(input_clone, cv::Point(0, (input_clone.rows - 1) / 2),
757                  cv::Point(input_clone.cols - 1, (input_clone.rows - 1) / 2), cv::Scalar(0, 0, 255));
758         cv::line(input_clone, cv::Point((input_clone.cols - 1) / 2, 0),
759                  cv::Point((input_clone.cols - 1) / 2, input_clone.rows - 1), cv::Scalar(0, 0, 255));
760
761         cv::imshow("Patch before copyMakeBorder", input_clone);
762     }
763
764     if (x2 - x1 == 0 || y2 - y1 == 0)
765         patch = cv::Mat::zeros(height, width, CV_32FC1);
766     else {
767         cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
768                            cv::BORDER_REPLICATE);
769         if (m_visual_debug) {
770             cv::Mat patch_dummy;
771             cv::copyMakeBorder(input_clone(cv::Range(y1, y2), cv::Range(x1, x2)), patch_dummy, top, bottom, left, right,
772                                cv::BORDER_REPLICATE);
773             cv::imshow("Patch after copyMakeBorder", patch_dummy);
774         }
775     }
776
777     // sanity check
778     assert(patch.cols == width && patch.rows == height);
779
780     return patch;
781 }
782
783 void KCF_Tracker::geometric_transformations(cv::Mat &patch, double scale, int size_x, int size_y, int angle)
784 {
785     if (m_use_angle) {
786         cv::Point2f center((patch.cols - 1) / 2., (patch.rows - 1) / 2.);
787         cv::Mat r = cv::getRotationMatrix2D(center, angle, 1.0);
788
789         cv::warpAffine(patch, patch, r, cv::Size(patch.cols, patch.rows), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
790
791         if (m_visual_debug) {
792             cv::Mat patch_copy = patch.clone();
793             cv::namedWindow("Patch RGB copy", CV_WINDOW_AUTOSIZE);
794             cv::putText(patch_copy, std::to_string(angle), cv::Point(0, patch_copy.rows - 1),
795                         cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(0, 255, 0), 2, cv::LINE_AA);
796             cv::imshow("Rotated patch", patch_copy);
797         }
798     }
799     // resize to default size
800     if (patch.channels() != 3) {
801         if (scale > 1.) {
802             // if we downsample use  INTER_AREA interpolation
803             cv::resize(patch, patch, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
804         } else {
805             cv::resize(patch, patch, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
806         }
807     } else {
808         if (scale > 1.) {
809             // if we downsample use  INTER_AREA interpolation
810             cv::resize(patch, patch, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_AREA);
811         } else {
812             cv::resize(patch, patch, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_LINEAR);
813         }
814     }
815 }
816
817 void KCF_Tracker::gaussian_correlation(struct ThreadCtx &vars, const ComplexMat &xf, const ComplexMat &yf,
818                                        double sigma, bool auto_correlation)
819 {
820 #ifdef CUFFT
821     xf.sqr_norm(vars.xf_sqr_norm.deviceMem());
822     if (!auto_correlation) yf.sqr_norm(vars.yf_sqr_norm.deviceMem());
823 #else
824     xf.sqr_norm(vars.xf_sqr_norm.hostMem());
825     if (auto_correlation) {
826         vars.yf_sqr_norm.hostMem()[0] = vars.xf_sqr_norm.hostMem()[0];
827     } else {
828         yf.sqr_norm(vars.yf_sqr_norm.hostMem());
829     }
830 #endif
831     vars.xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
832     DEBUG_PRINTM(vars.xyf);
833     fft.inverse(vars.xyf, vars.ifft2_res, m_use_cuda ? vars.data_i_features.deviceMem() : nullptr, vars.stream);
834 #ifdef CUFFT
835     if (auto_correlation)
836         cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(), vars.xf_sqr_norm.deviceMem(), vars.xf_sqr_norm.deviceMem(),
837                                   sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width, vars.stream);
838     else
839         cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(), vars.xf_sqr_norm.deviceMem(), vars.yf_sqr_norm.deviceMem(),
840                                   sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width, vars.stream);
841 #else
842     // ifft2 and sum over 3rd dimension, we dont care about individual channels
843     DEBUG_PRINTM(vars.ifft2_res);
844     cv::Mat xy_sum;
845     if (xf.channels() != p_num_scales * p_num_of_feats)
846         xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
847     else
848         xy_sum.create(vars.ifft2_res.size(), CV_32FC(int(p_scales.size())));
849     xy_sum.setTo(0);
850     for (int y = 0; y < vars.ifft2_res.rows; ++y) {
851         float *row_ptr = vars.ifft2_res.ptr<float>(y);
852         float *row_ptr_sum = xy_sum.ptr<float>(y);
853         for (int x = 0; x < vars.ifft2_res.cols; ++x) {
854             for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
855                 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
856                     row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
857                     (row_ptr + x * vars.ifft2_res.channels() +
858                      (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
859                     0.f);
860             }
861         }
862     }
863     DEBUG_PRINTM(xy_sum);
864
865     std::vector<cv::Mat> scales;
866     cv::split(xy_sum, scales);
867
868     float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
869     for (uint i = 0; i < uint(xf.n_scales); ++i) {
870         cv::Mat in_roi(vars.in_all, cv::Rect(0, int(i) * scales[0].rows, scales[0].cols, scales[0].rows));
871         cv::exp(
872             -1. / (sigma * sigma) *
873                 cv::max((double(vars.xf_sqr_norm.hostMem()[i] + vars.yf_sqr_norm.hostMem()[0]) - 2 * scales[i]) * double(numel_xf_inv), 0),
874             in_roi);
875         DEBUG_PRINTM(in_roi);
876     }
877 #endif
878     DEBUG_PRINTM(vars.in_all);
879     fft.forward(vars.in_all, auto_correlation ? vars.kf : vars.kzf, m_use_cuda ? vars.gauss_corr_res.deviceMem() : nullptr,
880                 vars.stream);
881     return;
882 }
883
884 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
885 {
886     int x = pt.x;
887     int y = pt.y;
888     if (x < 0) x = response.cols + x;
889     if (y < 0) y = response.rows + y;
890     if (x >= response.cols) x = x - response.cols;
891     if (y >= response.rows) y = y - response.rows;
892
893     return response.at<float>(y, x);
894 }
895
896 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response)
897 {
898     // find neighbourhood of max_loc (response is circular)
899     // 1 2 3
900     // 4   5
901     // 6 7 8
902     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);
903     cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
904     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);
905
906     // clang-format off
907     // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
908     cv::Mat A = (cv::Mat_<float>(9, 6) <<
909                  p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
910                  p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
911                  p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
912                  p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
913                  p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
914                  p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
915                  p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
916                  p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
917                  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);
918     cv::Mat fval = (cv::Mat_<float>(9, 1) <<
919                     get_response_circular(p1, response),
920                     get_response_circular(p2, response),
921                     get_response_circular(p3, response),
922                     get_response_circular(p4, response),
923                     get_response_circular(p5, response),
924                     get_response_circular(p6, response),
925                     get_response_circular(p7, response),
926                     get_response_circular(p8, response),
927                     get_response_circular(max_loc, response));
928     // clang-format on
929     cv::Mat x;
930     cv::solve(A, fval, x, cv::DECOMP_SVD);
931
932     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);
933
934     cv::Point2f sub_peak(max_loc.x, max_loc.y);
935     if (b > 0 || b < 0) {
936         sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
937         sub_peak.x = (-2 * c * sub_peak.y - e) / b;
938     }
939
940     return sub_peak;
941 }
942
943 double KCF_Tracker::sub_grid_scale(int index)
944 {
945     cv::Mat A, fval;
946     if (index < 0 || index > int(p_scales.size()) - 1) {
947         // interpolate from all values
948         // fit 1d quadratic function f(x) = a*x^2 + b*x + c
949         A.create(int(p_scales.size()), 3, CV_32FC1);
950         fval.create(int(p_scales.size()), 1, CV_32FC1);
951         for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
952             uint i = uint(std::distance(p_threadctxs.begin(), it));
953             int j = int(i);
954             A.at<float>(j, 0) = float(p_scales[i] * p_scales[i]);
955             A.at<float>(j, 1) = float(p_scales[i]);
956             A.at<float>(j, 2) = 1;
957             fval.at<float>(j) =
958                 m_use_big_batch ? float(p_threadctxs.back()->max_responses[i]) : float((*it)->max_response);
959         }
960     } else {
961         // only from neighbours
962         if (index == 0 || index == int(p_scales.size()) - 1) return p_scales[uint(index)];
963
964         A = (cv::Mat_<float>(3, 3) << p_scales[uint(index) - 1] * p_scales[uint(index) - 1], p_scales[uint(index) - 1],
965              1, p_scales[uint(index)] * p_scales[uint(index)], p_scales[uint(index)], 1,
966              p_scales[uint(index) + 1] * p_scales[uint(index) + 1], p_scales[uint(index) + 1], 1);
967         auto it1 = p_threadctxs.begin();
968         std::advance(it1, index - 1);
969         auto it2 = p_threadctxs.begin();
970         std::advance(it2, index);
971         auto it3 = p_threadctxs.begin();
972         std::advance(it3, index + 1);
973         fval = (cv::Mat_<float>(3, 1) << (m_use_big_batch ? p_threadctxs.back()->max_responses[uint(index) - 1]
974                                                           : (*it1)->max_response),
975                 (m_use_big_batch ? p_threadctxs.back()->max_responses[uint(index)] : (*it2)->max_response),
976                 (m_use_big_batch ? p_threadctxs.back()->max_responses[uint(index) + 1] : (*it3)->max_response));
977     }
978
979     cv::Mat x;
980     cv::solve(A, fval, x, cv::DECOMP_SVD);
981     float a = x.at<float>(0), b = x.at<float>(1);
982     double scale = p_scales[uint(index)];
983     if (a > 0 || a < 0) scale = double(-b / (2 * a));
984     return scale;
985 }