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