]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blob - src/kcf.cpp
Improve error message
[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) p_scale_factor_x = fit_size_x / tmp;
104         tmp = (p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
105         if (fabs(tmp - fit_size_y) > p_floating_error) p_scale_factor_y = fit_size_y / tmp;
106         std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x << " and verticaly by factor of "
107                   << p_scale_factor_y << std::endl;
108         p_fit_to_pw2 = true;
109         p_pose.scale_x(p_scale_factor_x);
110         p_pose.scale_y(p_scale_factor_y);
111         if (fabs(p_scale_factor_x - 1) > p_floating_error && fabs(p_scale_factor_y - 1) > p_floating_error) {
112             if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
113                 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
114                 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
115             } else {
116                 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y,
117                            cv::INTER_LINEAR);
118                 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
119             }
120         }
121     }
122
123     // compute win size + fit to fhog cell size
124     p_windows_size.width = int(round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size);
125     p_windows_size.height = int(round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size);
126
127     p_num_of_feats = 31;
128     if (m_use_color) p_num_of_feats += 3;
129     if (m_use_cnfeat) p_num_of_feats += 10;
130     p_roi_width = p_windows_size.width / p_cell_size;
131     p_roi_height = p_windows_size.height / p_cell_size;
132
133     p_scales.clear();
134     if (m_use_scale)
135         for (int i = -p_num_scales / 2; i <= p_num_scales / 2; ++i)
136             p_scales.push_back(std::pow(p_scale_step, i));
137     else
138         p_scales.push_back(1.);
139
140 #ifdef CUFFT
141     if (p_windows_size.height / p_cell_size * (p_windows_size.width / p_cell_size / 2 + 1) > 1024) {
142         std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
143                      "the window dimensions so its size is less or equal to "
144                   << 1024 * p_cell_size * p_cell_size * 2 + 1
145                   << " pixels . Currently the size of the window is: " << p_windows_size.width << "x" << p_windows_size.height
146                   << " which is  " << p_windows_size.width * p_windows_size.height << " pixels. " << std::endl;
147         std::exit(EXIT_FAILURE);
148     }
149
150     if (m_use_linearkernel) {
151         std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
152         std::exit(EXIT_FAILURE);
153     }
154     CudaSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost));
155     p_rot_labels_data = DynMem(
156         ((uint(p_windows_size.width) / p_cell_size) * (uint(p_windows_size.height) / p_cell_size)) * sizeof(float));
157     p_rot_labels = cv::Mat(p_windows_size.height / int(p_cell_size), p_windows_size.width / int(p_cell_size), CV_32FC1,
158                            p_rot_labels_data.hostMem());
159 #else
160     p_xf.create(uint(p_windows_size.height / p_cell_size), (uint(p_windows_size.height / p_cell_size)) / 2 + 1,
161                 p_num_of_feats);
162 #endif
163
164 #if defined(CUFFT) || defined(FFTW)
165     p_model_xf.create(uint(p_windows_size.height / p_cell_size), (uint(p_windows_size.width / p_cell_size)) / 2 + 1,
166                       uint(p_num_of_feats));
167     p_yf.create(uint(p_windows_size.height / p_cell_size), (uint(p_windows_size.width / p_cell_size)) / 2 + 1, 1);
168     p_xf.create(uint(p_windows_size.height) / p_cell_size, (uint(p_windows_size.width) / p_cell_size) / 2 + 1,
169                 p_num_of_feats);
170 #else
171     p_model_xf.create(uint(p_windows_size.height / p_cell_size), (uint(p_windows_size.width / p_cell_size)),
172                       uint(p_num_of_feats));
173     p_yf.create(uint(p_windows_size.height / p_cell_size), (uint(p_windows_size.width / p_cell_size)), 1);
174     p_xf.create(uint(p_windows_size.height) / p_cell_size, (uint(p_windows_size.width) / p_cell_size), p_num_of_feats);
175 #endif
176
177     int max = m_use_big_batch ? 2 : p_num_scales;
178     for (int i = 0; i < max; ++i) {
179         if (m_use_big_batch && i == 1) {
180             p_threadctxs.emplace_back(
181                 new ThreadCtx(p_windows_size, p_cell_size, p_num_of_feats * p_num_scales, p_num_scales));
182         } else {
183             p_threadctxs.emplace_back(new ThreadCtx(p_windows_size, p_cell_size, p_num_of_feats, 1));
184         }
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     int 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 = int(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 = int(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 = int(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) new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
391     DEBUG_PRINT(new_location);
392
393     p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
394     p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
395     if (p_fit_to_pw2) {
396         if (p_pose.cx < 0) p_pose.cx = 0;
397         if (p_pose.cx > (img.cols * p_scale_factor_x) - 1) p_pose.cx = (img.cols * p_scale_factor_x) - 1;
398         if (p_pose.cy < 0) p_pose.cy = 0;
399         if (p_pose.cy > (img.rows * p_scale_factor_y) - 1) p_pose.cy = (img.rows * p_scale_factor_y) - 1;
400     } else {
401         if (p_pose.cx < 0) p_pose.cx = 0;
402         if (p_pose.cx > img.cols - 1) p_pose.cx = img.cols - 1;
403         if (p_pose.cy < 0) p_pose.cy = 0;
404         if (p_pose.cy > img.rows - 1) p_pose.cy = img.rows - 1;
405     }
406
407     // sub grid scale interpolation
408     double new_scale = p_scales[uint(scale_index)];
409     if (m_use_subgrid_scale) new_scale = sub_grid_scale(scale_index);
410
411     p_current_scale *= new_scale;
412
413     if (p_current_scale < p_min_max_scale[0]) p_current_scale = p_min_max_scale[0];
414     if (p_current_scale > p_min_max_scale[1]) p_current_scale = p_min_max_scale[1];
415
416     // obtain a subwindow for training at newly estimated target position
417     p_threadctxs.front()->patch_feats.clear();
418     get_features(input_rgb, input_gray, int(p_pose.cx), int(p_pose.cy), p_windows_size.width, p_windows_size.height,
419                  *p_threadctxs.front(), p_current_scale);
420     fft.forward_window(p_threadctxs.front()->patch_feats, p_xf, p_threadctxs.front()->fw_all,
421                        m_use_cuda ? p_threadctxs.front()->data_features.deviceMem() : nullptr, p_threadctxs.front()->stream);
422
423     // subsequent frames, interpolate model
424     p_model_xf = p_model_xf * float((1. - p_interp_factor)) + p_xf * float(p_interp_factor);
425
426     ComplexMat alphaf_num, alphaf_den;
427
428     if (m_use_linearkernel) {
429         ComplexMat xfconj = p_xf.conj();
430         alphaf_num = xfconj.mul(p_yf);
431         alphaf_den = (p_xf * xfconj);
432     } else {
433         // Kernel Ridge Regression, calculate alphas (in Fourier domain)
434         gaussian_correlation(*p_threadctxs.front(), p_xf, p_xf, p_kernel_sigma,
435                              true);
436         //        ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
437         //        p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
438         alphaf_num = p_yf * p_threadctxs.front()->kf;
439         alphaf_den = p_threadctxs.front()->kf * (p_threadctxs.front()->kf + float(p_lambda));
440     }
441
442     p_model_alphaf_num = p_model_alphaf_num * float((1. - p_interp_factor)) + alphaf_num * float(p_interp_factor);
443     p_model_alphaf_den = p_model_alphaf_den * float((1. - p_interp_factor)) + alphaf_den * float(p_interp_factor);
444     p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
445
446 #if  !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
447     for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
448         (*it)->model_xf = p_model_xf;
449         (*it)->model_xf.set_stream((*it)->stream);
450         (*it)->model_alphaf = p_model_alphaf;
451         (*it)->model_alphaf.set_stream((*it)->stream);
452     }
453 #endif
454 }
455
456 void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray, double scale)
457 {
458     if (m_use_big_batch) {
459         vars.patch_feats.clear();
460         BIG_BATCH_OMP_PARALLEL_FOR
461         for (uint i = 0; i < uint(p_num_scales); ++i) {
462             get_features(input_rgb, input_gray, int(this->p_pose.cx), int(this->p_pose.cy), this->p_windows_size.width,
463                          this->p_windows_size.height, vars, this->p_current_scale * this->p_scales[i]);
464         }
465     } else {
466         vars.patch_feats.clear();
467         get_features(input_rgb, input_gray, int(this->p_pose.cx), int(this->p_pose.cy), this->p_windows_size.width,
468                      this->p_windows_size.height, vars, this->p_current_scale *scale);
469     }
470
471     fft.forward_window(vars.patch_feats, vars.zf, vars.fw_all, m_use_cuda ? vars.data_features.deviceMem() : nullptr,
472                        vars.stream);
473     DEBUG_PRINTM(vars.zf);
474
475     if (m_use_linearkernel) {
476         vars.kzf = m_use_big_batch ? (vars.zf.mul2(this->p_model_alphaf)).sum_over_channels()
477                                    : (p_model_alphaf * vars.zf).sum_over_channels();
478         fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr, vars.stream);
479     } else {
480 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
481         gaussian_correlation(vars, vars.zf, vars.model_xf, this->p_kernel_sigma);
482         vars.kzf = vars.model_alphaf * vars.kzf;
483 #else
484         gaussian_correlation(vars, vars.zf, this->p_model_xf, this->p_kernel_sigma);
485         DEBUG_PRINTM(this->p_model_alphaf);
486         DEBUG_PRINTM(vars.kzf);
487         vars.kzf = m_use_big_batch ? vars.kzf.mul(this->p_model_alphaf) : this->p_model_alphaf * vars.kzf;
488 #endif
489         fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr, vars.stream);
490     }
491
492     DEBUG_PRINTM(vars.response);
493
494     /* target location is at the maximum response. we must take into
495     account the fact that, if the target doesn't move, the peak
496     will appear at the top-left corner, not at the center (this is
497     discussed in the paper). the responses wrap around cyclically. */
498     if (m_use_big_batch) {
499         cv::split(vars.response, vars.response_maps);
500
501         for (size_t i = 0; i < p_scales.size(); ++i) {
502             double min_val, max_val;
503             cv::Point2i min_loc, max_loc;
504             cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
505             DEBUG_PRINT(max_loc);
506             double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
507             vars.max_responses[i] = max_val * weight;
508             vars.max_locs[i] = max_loc;
509         }
510     } else {
511         double min_val;
512         cv::Point2i min_loc;
513         cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
514
515         DEBUG_PRINT(vars.max_loc);
516
517         double weight = scale < 1. ? scale : 1. / scale;
518         vars.max_response = vars.max_val * weight;
519     }
520     return;
521 }
522
523 // ****************************************************************************
524
525 void KCF_Tracker::get_features(cv::Mat &input_rgb, cv::Mat &input_gray, int cx, int cy, int size_x, int size_y,
526                                ThreadCtx &vars, double scale)
527 {
528     int size_x_scaled = int(floor(size_x * scale));
529     int size_y_scaled = int(floor(size_y * scale));
530
531     cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
532     cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
533
534     // resize to default size
535     if (scale > 1.) {
536         // if we downsample use  INTER_AREA interpolation
537         cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
538     } else {
539         cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
540     }
541
542     // get hog(Histogram of Oriented Gradients) features
543     FHoG::extract(patch_gray, vars, 2, p_cell_size, 9);
544
545     // get color rgb features (simple r,g,b channels)
546     std::vector<cv::Mat> color_feat;
547     if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
548         // resize to default size
549         if (scale > 1.) {
550             // if we downsample use  INTER_AREA interpolation
551             cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0.,
552                        cv::INTER_AREA);
553         } else {
554             cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0.,
555                        cv::INTER_LINEAR);
556         }
557     }
558
559     if (m_use_color && input_rgb.channels() == 3) {
560         // use rgb color space
561         cv::Mat patch_rgb_norm;
562         patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
563         cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
564         cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
565         cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
566         std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
567         cv::split(patch_rgb_norm, rgb);
568         color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
569     }
570
571     if (m_use_cnfeat && input_rgb.channels() == 3) {
572         std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
573         color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
574     }
575     BIG_BATCH_OMP_ORDERED
576     vars.patch_feats.insert(vars.patch_feats.end(), color_feat.begin(), color_feat.end());
577     return;
578 }
579
580 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
581 {
582     cv::Mat labels(dim2, dim1, CV_32FC1);
583     int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
584     int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
585
586     double sigma_s = sigma * sigma;
587
588     for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
589         float *row_ptr = labels.ptr<float>(j);
590         double y_s = y * y;
591         for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
592             row_ptr[i] = float(std::exp(-0.5 * (y_s + x * x) / sigma_s)); //-1/2*e^((y^2+x^2)/sigma^2)
593         }
594     }
595
596     // rotate so that 1 is at top-left corner (see KCF paper for explanation)
597 #ifdef CUFFT
598     cv::Mat tmp = circshift(labels, range_x[0], range_y[0]);
599     tmp.copyTo(p_rot_labels);
600
601     assert(p_rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
602     return tmp;
603 #else
604     cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
605     // sanity check, 1 at top left corner
606     assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
607
608     return rot_labels;
609 #endif
610 }
611
612 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
613 {
614     cv::Mat rot_patch(patch.size(), CV_32FC1);
615     cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
616
617     // circular rotate x-axis
618     if (x_rot < 0) {
619         // move part that does not rotate over the edge
620         cv::Range orig_range(-x_rot, patch.cols);
621         cv::Range rot_range(0, patch.cols - (-x_rot));
622         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
623
624         // rotated part
625         orig_range = cv::Range(0, -x_rot);
626         rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
627         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
628     } else if (x_rot > 0) {
629         // move part that does not rotate over the edge
630         cv::Range orig_range(0, patch.cols - x_rot);
631         cv::Range rot_range(x_rot, patch.cols);
632         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
633
634         // rotated part
635         orig_range = cv::Range(patch.cols - x_rot, patch.cols);
636         rot_range = cv::Range(0, x_rot);
637         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
638     } else { // zero rotation
639         // move part that does not rotate over the edge
640         cv::Range orig_range(0, patch.cols);
641         cv::Range rot_range(0, patch.cols);
642         patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
643     }
644
645     // circular rotate y-axis
646     if (y_rot < 0) {
647         // move part that does not rotate over the edge
648         cv::Range orig_range(-y_rot, patch.rows);
649         cv::Range rot_range(0, patch.rows - (-y_rot));
650         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
651
652         // rotated part
653         orig_range = cv::Range(0, -y_rot);
654         rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
655         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
656     } else if (y_rot > 0) {
657         // move part that does not rotate over the edge
658         cv::Range orig_range(0, patch.rows - y_rot);
659         cv::Range rot_range(y_rot, patch.rows);
660         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
661
662         // rotated part
663         orig_range = cv::Range(patch.rows - y_rot, patch.rows);
664         rot_range = cv::Range(0, y_rot);
665         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
666     } else { // zero rotation
667         // move part that does not rotate over the edge
668         cv::Range orig_range(0, patch.rows);
669         cv::Range rot_range(0, patch.rows);
670         tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
671     }
672
673     return rot_patch;
674 }
675
676 // hann window actually (Power-of-cosine windows)
677 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
678 {
679     cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
680     double N_inv = 1. / (static_cast<double>(dim1) - 1.);
681     for (int i = 0; i < dim1; ++i)
682         m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
683     N_inv = 1. / (static_cast<double>(dim2) - 1.);
684     for (int i = 0; i < dim2; ++i)
685         m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
686     cv::Mat ret = m2 * m1;
687     return ret;
688 }
689
690 // Returns sub-window of image input centered at [cx, cy] coordinates),
691 // with size [width, height]. If any pixels are outside of the image,
692 // they will replicate the values at the borders.
693 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
694 {
695     cv::Mat patch;
696
697     int x1 = cx - width / 2;
698     int y1 = cy - height / 2;
699     int x2 = cx + width / 2;
700     int y2 = cy + height / 2;
701
702     // out of image
703     if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
704         patch.create(height, width, input.type());
705         patch.setTo(double(0.f));
706         return patch;
707     }
708
709     int top = 0, bottom = 0, left = 0, right = 0;
710
711     // fit to image coordinates, set border extensions;
712     if (x1 < 0) {
713         left = -x1;
714         x1 = 0;
715     }
716     if (y1 < 0) {
717         top = -y1;
718         y1 = 0;
719     }
720     if (x2 >= input.cols) {
721         right = x2 - input.cols + width % 2;
722         x2 = input.cols;
723     } else
724         x2 += width % 2;
725
726     if (y2 >= input.rows) {
727         bottom = y2 - input.rows + height % 2;
728         y2 = input.rows;
729     } else
730         y2 += height % 2;
731
732     if (x2 - x1 == 0 || y2 - y1 == 0)
733         patch = cv::Mat::zeros(height, width, CV_32FC1);
734     else {
735         cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
736                            cv::BORDER_REPLICATE);
737         //      imshow( "copyMakeBorder", patch);
738         //      cv::waitKey();
739     }
740
741     // sanity check
742     assert(patch.cols == width && patch.rows == height);
743
744     return patch;
745 }
746
747 void KCF_Tracker::gaussian_correlation(struct ThreadCtx &vars, const ComplexMat &xf, const ComplexMat &yf,
748                                        double sigma, bool auto_correlation)
749 {
750 #ifdef CUFFT
751     xf.sqr_norm(vars.xf_sqr_norm.deviceMem());
752     if (!auto_correlation) yf.sqr_norm(vars.yf_sqr_norm.deviceMem());
753 #else
754     xf.sqr_norm(vars.xf_sqr_norm.hostMem());
755     if (auto_correlation) {
756         vars.yf_sqr_norm.hostMem()[0] = vars.xf_sqr_norm.hostMem()[0];
757     } else {
758         yf.sqr_norm(vars.yf_sqr_norm.hostMem());
759     }
760 #endif
761     vars.xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
762     DEBUG_PRINTM(vars.xyf);
763     fft.inverse(vars.xyf, vars.ifft2_res, m_use_cuda ? vars.data_i_features.deviceMem() : nullptr, vars.stream);
764 #ifdef CUFFT
765     if (auto_correlation)
766         cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(), vars.xf_sqr_norm.deviceMem(), vars.xf_sqr_norm.deviceMem(),
767                                   sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width, vars.stream);
768     else
769         cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(), vars.xf_sqr_norm.deviceMem(), vars.yf_sqr_norm.deviceMem(),
770                                   sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width, vars.stream);
771 #else
772     // ifft2 and sum over 3rd dimension, we dont care about individual channels
773     DEBUG_PRINTM(vars.ifft2_res);
774     cv::Mat xy_sum;
775     if (xf.channels() != p_num_scales * p_num_of_feats)
776         xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
777     else
778         xy_sum.create(vars.ifft2_res.size(), CV_32FC(int(p_scales.size())));
779     xy_sum.setTo(0);
780     for (int y = 0; y < vars.ifft2_res.rows; ++y) {
781         float *row_ptr = vars.ifft2_res.ptr<float>(y);
782         float *row_ptr_sum = xy_sum.ptr<float>(y);
783         for (int x = 0; x < vars.ifft2_res.cols; ++x) {
784             for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
785                 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
786                     row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
787                     (row_ptr + x * vars.ifft2_res.channels() +
788                      (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
789                     0.f);
790             }
791         }
792     }
793     DEBUG_PRINTM(xy_sum);
794
795     std::vector<cv::Mat> scales;
796     cv::split(xy_sum, scales);
797
798     float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
799     for (uint i = 0; i < uint(xf.n_scales); ++i) {
800         cv::Mat in_roi(vars.in_all, cv::Rect(0, int(i) * scales[0].rows, scales[0].cols, scales[0].rows));
801         cv::exp(
802             -1. / (sigma * sigma) *
803                 cv::max((double(vars.xf_sqr_norm.hostMem()[i] + vars.yf_sqr_norm.hostMem()[0]) - 2 * scales[i]) * double(numel_xf_inv), 0),
804             in_roi);
805         DEBUG_PRINTM(in_roi);
806     }
807 #endif
808     DEBUG_PRINTM(vars.in_all);
809     fft.forward(vars.in_all, auto_correlation ? vars.kf : vars.kzf, m_use_cuda ? vars.gauss_corr_res.deviceMem() : nullptr,
810                 vars.stream);
811     return;
812 }
813
814 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
815 {
816     int x = pt.x;
817     int y = pt.y;
818     if (x < 0) x = response.cols + x;
819     if (y < 0) y = response.rows + y;
820     if (x >= response.cols) x = x - response.cols;
821     if (y >= response.rows) y = y - response.rows;
822
823     return response.at<float>(y, x);
824 }
825
826 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response)
827 {
828     // find neighbourhood of max_loc (response is circular)
829     // 1 2 3
830     // 4   5
831     // 6 7 8
832     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);
833     cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
834     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);
835
836     // clang-format off
837     // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
838     cv::Mat A = (cv::Mat_<float>(9, 6) <<
839                  p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
840                  p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
841                  p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
842                  p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
843                  p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
844                  p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
845                  p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
846                  p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
847                  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);
848     cv::Mat fval = (cv::Mat_<float>(9, 1) <<
849                     get_response_circular(p1, response),
850                     get_response_circular(p2, response),
851                     get_response_circular(p3, response),
852                     get_response_circular(p4, response),
853                     get_response_circular(p5, response),
854                     get_response_circular(p6, response),
855                     get_response_circular(p7, response),
856                     get_response_circular(p8, response),
857                     get_response_circular(max_loc, response));
858     // clang-format on
859     cv::Mat x;
860     cv::solve(A, fval, x, cv::DECOMP_SVD);
861
862     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);
863
864     cv::Point2f sub_peak(max_loc.x, max_loc.y);
865     if (b > 0 || b < 0) {
866         sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
867         sub_peak.x = (-2 * c * sub_peak.y - e) / b;
868     }
869
870     return sub_peak;
871 }
872
873 double KCF_Tracker::sub_grid_scale(int index)
874 {
875     cv::Mat A, fval;
876     if (index < 0 || index > int(p_scales.size()) - 1) {
877         // interpolate from all values
878         // fit 1d quadratic function f(x) = a*x^2 + b*x + c
879         A.create(int(p_scales.size()), 3, CV_32FC1);
880         fval.create(int(p_scales.size()), 1, CV_32FC1);
881         for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
882             uint i = uint(std::distance(p_threadctxs.begin(), it));
883             int j = int(i);
884             A.at<float>(j, 0) = float(p_scales[i] * p_scales[i]);
885             A.at<float>(j, 1) = float(p_scales[i]);
886             A.at<float>(j, 2) = 1;
887             fval.at<float>(j) =
888                 m_use_big_batch ? float(p_threadctxs.back()->max_responses[i]) : float((*it)->max_response);
889         }
890     } else {
891         // only from neighbours
892         if (index == 0 || index == int(p_scales.size()) - 1) return p_scales[uint(index)];
893
894         A = (cv::Mat_<float>(3, 3) << p_scales[uint(index) - 1] * p_scales[uint(index) - 1], p_scales[uint(index) - 1],
895              1, p_scales[uint(index)] * p_scales[uint(index)], p_scales[uint(index)], 1,
896              p_scales[uint(index) + 1] * p_scales[uint(index) + 1], p_scales[uint(index) + 1], 1);
897         auto it1 = p_threadctxs.begin();
898         std::advance(it1, index - 1);
899         auto it2 = p_threadctxs.begin();
900         std::advance(it2, index);
901         auto it3 = p_threadctxs.begin();
902         std::advance(it3, index + 1);
903         fval = (cv::Mat_<float>(3, 1) << (m_use_big_batch ? p_threadctxs.back()->max_responses[uint(index) - 1]
904                                                           : (*it1)->max_response),
905                 (m_use_big_batch ? p_threadctxs.back()->max_responses[uint(index)] : (*it2)->max_response),
906                 (m_use_big_batch ? p_threadctxs.back()->max_responses[uint(index) + 1] : (*it3)->max_response));
907     }
908
909     cv::Mat x;
910     cv::solve(A, fval, x, cv::DECOMP_SVD);
911     float a = x.at<float>(0), b = x.at<float>(1);
912     double scale = p_scales[uint(index)];
913     if (a > 0 || a < 0) scale = double(-b / (2 * a));
914     return scale;
915 }