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