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