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