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