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