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