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