]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blob - src/kcf.cpp
Replace (p_windows_size.* / p_cell_size) with p_roi and remove useless typecasting
[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 KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor,
32                          double output_sigma_factor, int cell_size)
33     : fft(*new FFT()), p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
34       p_lambda(lambda), p_interp_factor(interp_factor), p_cell_size(cell_size)
35 {
36 }
37
38 KCF_Tracker::KCF_Tracker() : fft(*new FFT()) {}
39
40 KCF_Tracker::~KCF_Tracker()
41 {
42     delete &fft;
43 }
44
45 void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int fit_size_y)
46 {
47     // check boundary, enforce min size
48     double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
49     if (x1 < 0) x1 = 0.;
50     if (x2 > img.cols - 1) x2 = img.cols - 1;
51     if (y1 < 0) y1 = 0;
52     if (y2 > img.rows - 1) y2 = img.rows - 1;
53
54     if (x2 - x1 < 2 * p_cell_size) {
55         double diff = (2 * p_cell_size - x2 + x1) / 2.;
56         if (x1 - diff >= 0 && x2 + diff < img.cols) {
57             x1 -= diff;
58             x2 += diff;
59         } else if (x1 - 2 * diff >= 0) {
60             x1 -= 2 * diff;
61         } else {
62             x2 += 2 * diff;
63         }
64     }
65     if (y2 - y1 < 2 * p_cell_size) {
66         double diff = (2 * p_cell_size - y2 + y1) / 2.;
67         if (y1 - diff >= 0 && y2 + diff < img.rows) {
68             y1 -= diff;
69             y2 += diff;
70         } else if (y1 - 2 * diff >= 0) {
71             y1 -= 2 * diff;
72         } else {
73             y2 += 2 * diff;
74         }
75     }
76
77     p_pose.w = x2 - x1;
78     p_pose.h = y2 - y1;
79     p_pose.cx = x1 + p_pose.w / 2.;
80     p_pose.cy = y1 + p_pose.h / 2.;
81
82     cv::Mat input_gray, input_rgb = img.clone();
83     if (img.channels() == 3) {
84         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
85         input_gray.convertTo(input_gray, CV_32FC1);
86     } else
87         img.convertTo(input_gray, CV_32FC1);
88
89     // don't need too large image
90     if (p_pose.w * p_pose.h > 100. * 100. && (fit_size_x == -1 || fit_size_y == -1)) {
91         std::cout << "resizing image by factor of " << 1 / p_downscale_factor << std::endl;
92         p_resize_image = true;
93         p_pose.scale(p_downscale_factor);
94         cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
95         cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
96     } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
97         if (fit_size_x % p_cell_size != 0 || fit_size_y % p_cell_size != 0) {
98             std::cerr << "Error: Fit size is not multiple of HOG cell size (" << p_cell_size << ")" << std::endl;
99             std::exit(EXIT_FAILURE);
100         }
101         p_scale_factor_x = (double)fit_size_x / round(p_pose.w * (1. + p_padding));
102         p_scale_factor_y = (double)fit_size_y / round(p_pose.h * (1. + p_padding));
103         std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x << " and verticaly by factor of "
104                   << p_scale_factor_y << std::endl;
105         p_fit_to_pw2 = true;
106         p_pose.scale_x(p_scale_factor_x);
107         p_pose.scale_y(p_scale_factor_y);
108         if (fabs(p_scale_factor_x - 1) > p_floating_error || fabs(p_scale_factor_y - 1) > p_floating_error) {
109             if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
110                 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
111                 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
112             } else {
113                 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
114                 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
115             }
116         }
117     }
118
119     // compute win size + fit to fhog cell size
120     p_windows_size.width = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
121     p_windows_size.height = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
122     p_roi.width = p_windows_size.width / p_cell_size;
123     p_roi.height = p_windows_size.height / p_cell_size;
124
125     p_num_of_feats = 31;
126     if (m_use_color) p_num_of_feats += 3;
127     if (m_use_cnfeat) p_num_of_feats += 10;
128
129     p_scales.clear();
130     if (m_use_scale)
131         for (int i = -p_num_scales / 2; i <= p_num_scales / 2; ++i)
132             p_scales.push_back(std::pow(p_scale_step, i));
133     else
134         p_scales.push_back(1.);
135
136 #ifdef CUFFT
137     if (p_roi.height * (p_roi.width / 2 + 1) > 1024) {
138         std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
139                      "the window dimensions so its size is less or equal to "
140                   << 1024 * p_cell_size * p_cell_size * 2 + 1
141                   << " pixels . Currently the size of the window is: " << p_windows_size.width << "x" << p_windows_size.height
142                   << " which is  " << p_windows_size.width * p_windows_size.height << " pixels. " << std::endl;
143         std::exit(EXIT_FAILURE);
144     }
145
146     if (m_use_linearkernel) {
147         std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
148         std::exit(EXIT_FAILURE);
149     }
150     CudaSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost));
151     p_rot_labels_data = DynMem(p_roi.width * p_roi.height * sizeof(float));
152     p_rot_labels = cv::Mat(p_roi, CV_32FC1, p_rot_labels_data.hostMem());
153 #else
154     p_xf.create(p_roi.height, p_roi.height / 2 + 1, p_num_of_feats);
155 #endif
156
157 #if defined(CUFFT) || defined(FFTW)
158     p_model_xf.create(p_roi.height, p_roi.width / 2 + 1, p_num_of_feats);
159     p_yf.create(p_roi.height, p_roi.width / 2 + 1, 1);
160     p_xf.create(p_roi.height, p_roi.width / 2 + 1, p_num_of_feats);
161 #else
162     p_model_xf.create(p_roi.height, p_roi.width, p_num_of_feats);
163     p_yf.create(p_roi.height, p_roi.width, 1);
164     p_xf.create(p_roi.height, p_roi.width, p_num_of_feats);
165 #endif
166
167     int max = m_use_big_batch ? 2 : p_num_scales;
168     for (int i = 0; i < max; ++i) {
169         if (m_use_big_batch && i == 1)
170             p_threadctxs.emplace_back(p_roi, p_num_of_feats * p_num_scales, 1, p_num_scales);
171         else
172             p_threadctxs.emplace_back(p_roi, p_num_of_feats, p_scales[i], 1);
173     }
174
175     p_current_scale = 1.;
176
177     double min_size_ratio = std::max(5. * p_cell_size / p_windows_size.width, 5. * p_cell_size / p_windows_size.height);
178     double max_size_ratio =
179         std::min(floor((img.cols + p_windows_size.width / 3) / p_cell_size) * p_cell_size / p_windows_size.width,
180                  floor((img.rows + p_windows_size.height / 3) / p_cell_size) * p_cell_size / p_windows_size.height);
181     p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
182     p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
183
184     std::cout << "init: img size " << img.cols << " " << img.rows << std::endl;
185     std::cout << "init: win size. " << p_windows_size.width << " " << p_windows_size.height << std::endl;
186     std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
187
188     p_output_sigma = std::sqrt(p_pose.w * p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
189
190     fft.init(uint(p_roi.width), uint(p_roi.height), uint(p_num_of_feats),
191              uint(p_num_scales), m_use_big_batch);
192     fft.set_window(cosine_window_function(p_roi.width, p_roi.height));
193
194     // window weights, i.e. labels
195     fft.forward(
196         gaussian_shaped_labels(p_output_sigma, p_roi.width, p_roi.height), p_yf,
197         m_use_cuda ? p_rot_labels_data.deviceMem() : nullptr, p_threadctxs.front().stream);
198     DEBUG_PRINTM(p_yf);
199
200     // obtain a sub-window for training initial model
201     p_threadctxs.front().patch_feats.clear();
202     get_features(input_rgb, input_gray, int(p_pose.cx), int(p_pose.cy), p_windows_size.width, p_windows_size.height,
203                  p_threadctxs.front());
204     fft.forward_window(p_threadctxs.front().patch_feats, p_model_xf, p_threadctxs.front().fw_all,
205                        m_use_cuda ? p_threadctxs.front().data_features.deviceMem() : nullptr, p_threadctxs.front().stream);
206     DEBUG_PRINTM(p_model_xf);
207 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
208     p_threadctxs.front().model_xf = p_model_xf;
209     p_threadctxs.front().model_xf.set_stream(p_threadctxs.front().stream);
210     p_yf.set_stream(p_threadctxs.front().stream);
211     p_model_xf.set_stream(p_threadctxs.front().stream);
212     p_xf.set_stream(p_threadctxs.front().stream);
213 #endif
214
215     if (m_use_linearkernel) {
216         ComplexMat xfconj = p_model_xf.conj();
217         p_model_alphaf_num = xfconj.mul(p_yf);
218         p_model_alphaf_den = (p_model_xf * xfconj);
219     } else {
220         // Kernel Ridge Regression, calculate alphas (in Fourier domain)
221 #if  !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
222         gaussian_correlation(p_threadctxs.front(), p_threadctxs.front().model_xf, p_threadctxs.front().model_xf,
223                              p_kernel_sigma, true);
224 #else
225         gaussian_correlation(p_threadctxs.front(), p_model_xf, p_model_xf, p_kernel_sigma, true);
226 #endif
227         DEBUG_PRINTM(p_threadctxs.front().kf);
228         p_model_alphaf_num = p_yf * p_threadctxs.front().kf;
229         DEBUG_PRINTM(p_model_alphaf_num);
230         p_model_alphaf_den = p_threadctxs.front().kf * (p_threadctxs.front().kf + float(p_lambda));
231         DEBUG_PRINTM(p_model_alphaf_den);
232     }
233     p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
234     DEBUG_PRINTM(p_model_alphaf);
235     //        p_model_alphaf = p_yf / (kf + p_lambda);   //equation for fast training
236
237 #if  !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
238     for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
239         it->model_xf = p_model_xf;
240         it->model_xf.set_stream(it->stream);
241         it->model_alphaf = p_model_alphaf;
242         it->model_alphaf.set_stream(it->stream);
243     }
244 #endif
245 }
246
247 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat &img, int fit_size_x, int fit_size_y)
248 {
249     init(img, bbox.get_rect(), fit_size_x, fit_size_y);
250 }
251
252 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
253 {
254     if (p_resize_image) {
255         BBox_c tmp = bbox;
256         tmp.scale(p_downscale_factor);
257         p_pose.cx = tmp.cx;
258         p_pose.cy = tmp.cy;
259     } else if (p_fit_to_pw2) {
260         BBox_c tmp = bbox;
261         tmp.scale_x(p_scale_factor_x);
262         tmp.scale_y(p_scale_factor_y);
263         p_pose.cx = tmp.cx;
264         p_pose.cy = tmp.cy;
265     } else {
266         p_pose.cx = bbox.cx;
267         p_pose.cy = bbox.cy;
268     }
269 }
270
271 BBox_c KCF_Tracker::getBBox()
272 {
273     BBox_c tmp = p_pose;
274     tmp.w *= p_current_scale;
275     tmp.h *= p_current_scale;
276
277     if (p_resize_image) tmp.scale(1 / p_downscale_factor);
278     if (p_fit_to_pw2) {
279         tmp.scale_x(1 / p_scale_factor_x);
280         tmp.scale_y(1 / p_scale_factor_y);
281     }
282
283     return tmp;
284 }
285
286 double KCF_Tracker::getFilterResponse() const
287 {
288     return this->max_response;
289 }
290
291 void KCF_Tracker::track(cv::Mat &img)
292 {
293     if (m_debug) std::cout << "NEW FRAME" << '\n';
294     cv::Mat input_gray, input_rgb = img.clone();
295     if (img.channels() == 3) {
296         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
297         input_gray.convertTo(input_gray, CV_32FC1);
298     } else
299         img.convertTo(input_gray, CV_32FC1);
300
301     // don't need too large image
302     if (p_resize_image) {
303         cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
304         cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
305     } else if (p_fit_to_pw2 && fabs(p_scale_factor_x - 1) > p_floating_error &&
306                fabs(p_scale_factor_y - 1) > p_floating_error) {
307         if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
308             cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
309             cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
310         } else {
311             cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
312             cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
313         }
314     }
315
316     max_response = -1.;
317     ThreadCtx *max = nullptr;
318     cv::Point2i *max_response_pt = nullptr;
319     cv::Mat *max_response_map = nullptr;
320
321 #ifdef ASYNC
322     for (auto &it : p_threadctxs)
323         it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
324             scale_track(it, input_rgb, input_gray);
325         });
326     for (auto const &it : p_threadctxs)
327         it.async_res.wait();
328
329 #else  // !ASYNC
330     // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
331     NORMAL_OMP_PARALLEL_FOR
332     for (uint i = 0; i < p_threadctxs.size(); ++i)
333         scale_track(p_threadctxs[i], input_rgb, input_gray);
334 #endif
335
336 #ifndef BIG_BATCH
337     for (auto &it : p_threadctxs) {
338         if (it.max_response > max_response) {
339             max_response = it.max_response;
340             max_response_pt = &it.max_loc;
341             max_response_map = &it.response;
342             max = &it;
343         }
344     }
345 #else
346     // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
347     for (uint j = 0; j < p_scales.size(); ++j) {
348         if (p_threadctxs[0].max_responses[j] > max_response) {
349             max_response = p_threadctxs[0].max_responses[j];
350             max_response_pt = &p_threadctxs[0].max_locs[j];
351             max_response_map = &p_threadctxs[0].response_maps[j];
352             max = &p_threadctxs[0];
353         }
354     }
355 #endif
356
357     DEBUG_PRINTM(*max_response_map);
358     DEBUG_PRINT(*max_response_pt);
359
360     // sub pixel quadratic interpolation from neighbours
361     if (max_response_pt->y > max_response_map->rows / 2) // wrap around to negative half-space of vertical axis
362         max_response_pt->y = max_response_pt->y - max_response_map->rows;
363     if (max_response_pt->x > max_response_map->cols / 2) // same for horizontal axis
364         max_response_pt->x = max_response_pt->x - max_response_map->cols;
365
366     cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
367     DEBUG_PRINT(new_location);
368
369     if (m_use_subpixel_localization)
370         new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
371     DEBUG_PRINT(new_location);
372
373     p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
374     p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
375     if (p_fit_to_pw2) {
376         if (p_pose.cx < 0) p_pose.cx = 0;
377         if (p_pose.cx > (img.cols * p_scale_factor_x) - 1) p_pose.cx = (img.cols * p_scale_factor_x) - 1;
378         if (p_pose.cy < 0) p_pose.cy = 0;
379         if (p_pose.cy > (img.rows * p_scale_factor_y) - 1) p_pose.cy = (img.rows * p_scale_factor_y) - 1;
380     } else {
381         if (p_pose.cx < 0) p_pose.cx = 0;
382         if (p_pose.cx > img.cols - 1) p_pose.cx = img.cols - 1;
383         if (p_pose.cy < 0) p_pose.cy = 0;
384         if (p_pose.cy > img.rows - 1) p_pose.cy = img.rows - 1;
385     }
386
387     // sub grid scale interpolation
388     if (m_use_subgrid_scale) {
389         auto it = std::find_if(p_threadctxs.begin(), p_threadctxs.end(), [max](ThreadCtx &ctx) { return &ctx == max; });
390         p_current_scale *= sub_grid_scale(std::distance(p_threadctxs.begin(), it));
391     } else {
392         p_current_scale *= max->scale;
393     }
394
395
396     if (p_current_scale < p_min_max_scale[0]) p_current_scale = p_min_max_scale[0];
397     if (p_current_scale > p_min_max_scale[1]) p_current_scale = p_min_max_scale[1];
398
399     // obtain a subwindow for training at newly estimated target position
400     p_threadctxs.front().patch_feats.clear();
401     get_features(input_rgb, input_gray, int(p_pose.cx), int(p_pose.cy), p_windows_size.width, p_windows_size.height,
402                  p_threadctxs.front(), p_current_scale);
403     fft.forward_window(p_threadctxs.front().patch_feats, p_xf, p_threadctxs.front().fw_all,
404                        m_use_cuda ? p_threadctxs.front().data_features.deviceMem() : nullptr, p_threadctxs.front().stream);
405
406     // subsequent frames, interpolate model
407     p_model_xf = p_model_xf * float((1. - p_interp_factor)) + p_xf * float(p_interp_factor);
408
409     ComplexMat alphaf_num, alphaf_den;
410
411     if (m_use_linearkernel) {
412         ComplexMat xfconj = p_xf.conj();
413         alphaf_num = xfconj.mul(p_yf);
414         alphaf_den = (p_xf * xfconj);
415     } else {
416         // Kernel Ridge Regression, calculate alphas (in Fourier domain)
417         gaussian_correlation(p_threadctxs.front(), p_xf, p_xf, p_kernel_sigma,
418                              true);
419         //        ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
420         //        p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
421         alphaf_num = p_yf * p_threadctxs.front().kf;
422         alphaf_den = p_threadctxs.front().kf * (p_threadctxs.front().kf + float(p_lambda));
423     }
424
425     p_model_alphaf_num = p_model_alphaf_num * float((1. - p_interp_factor)) + alphaf_num * float(p_interp_factor);
426     p_model_alphaf_den = p_model_alphaf_den * float((1. - p_interp_factor)) + alphaf_den * float(p_interp_factor);
427     p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
428
429 #if  !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
430     for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
431         it->model_xf = p_model_xf;
432         it->model_xf.set_stream(it->stream);
433         it->model_alphaf = p_model_alphaf;
434         it->model_alphaf.set_stream(it->stream);
435     }
436 #endif
437 }
438
439 void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray)
440 {
441     if (m_use_big_batch) {
442         vars.patch_feats.clear();
443         BIG_BATCH_OMP_PARALLEL_FOR
444         for (uint i = 0; i < uint(p_num_scales); ++i) {
445             get_features(input_rgb, input_gray, int(this->p_pose.cx), int(this->p_pose.cy), this->p_windows_size.width,
446                          this->p_windows_size.height, vars, this->p_current_scale * this->p_scales[i]);
447         }
448     } else {
449         vars.patch_feats.clear();
450         get_features(input_rgb, input_gray, int(this->p_pose.cx), int(this->p_pose.cy), this->p_windows_size.width,
451                      this->p_windows_size.height, vars, this->p_current_scale * vars.scale);
452     }
453
454     fft.forward_window(vars.patch_feats, vars.zf, vars.fw_all, m_use_cuda ? vars.data_features.deviceMem() : nullptr,
455                        vars.stream);
456     DEBUG_PRINTM(vars.zf);
457
458     if (m_use_linearkernel) {
459         vars.kzf = m_use_big_batch ? (vars.zf.mul2(this->p_model_alphaf)).sum_over_channels()
460                                    : (p_model_alphaf * vars.zf).sum_over_channels();
461         fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr, vars.stream);
462     } else {
463 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
464         gaussian_correlation(vars, vars.zf, vars.model_xf, this->p_kernel_sigma);
465         vars.kzf = vars.model_alphaf * vars.kzf;
466 #else
467         gaussian_correlation(vars, vars.zf, this->p_model_xf, this->p_kernel_sigma);
468         DEBUG_PRINTM(this->p_model_alphaf);
469         DEBUG_PRINTM(vars.kzf);
470         vars.kzf = m_use_big_batch ? vars.kzf.mul(this->p_model_alphaf) : this->p_model_alphaf * vars.kzf;
471 #endif
472         fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr, vars.stream);
473     }
474
475     DEBUG_PRINTM(vars.response);
476
477     /* target location is at the maximum response. we must take into
478     account the fact that, if the target doesn't move, the peak
479     will appear at the top-left corner, not at the center (this is
480     discussed in the paper). the responses wrap around cyclically. */
481     if (m_use_big_batch) {
482         cv::split(vars.response, vars.response_maps);
483
484         for (size_t i = 0; i < p_scales.size(); ++i) {
485             double min_val, max_val;
486             cv::Point2i min_loc, max_loc;
487             cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
488             DEBUG_PRINT(max_loc);
489             double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
490             vars.max_responses[i] = max_val * weight;
491             vars.max_locs[i] = max_loc;
492         }
493     } else {
494         double min_val;
495         cv::Point2i min_loc;
496         cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
497
498         DEBUG_PRINT(vars.max_loc);
499
500         double weight = vars.scale < 1. ? vars.scale : 1. / vars.scale;
501         vars.max_response = vars.max_val * weight;
502     }
503     return;
504 }
505
506 // ****************************************************************************
507
508 void KCF_Tracker::get_features(cv::Mat &input_rgb, cv::Mat &input_gray, int cx, int cy, int size_x, int size_y,
509                                ThreadCtx &vars, double scale)
510 {
511     int size_x_scaled = int(floor(size_x * scale));
512     int size_y_scaled = int(floor(size_y * scale));
513
514     cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
515     cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
516
517     // resize to default size
518     if (scale > 1.) {
519         // if we downsample use  INTER_AREA interpolation
520         cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
521     } else {
522         cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
523     }
524
525     // get hog(Histogram of Oriented Gradients) features
526     FHoG::extract(patch_gray, vars, 2, p_cell_size, 9);
527
528     // get color rgb features (simple r,g,b channels)
529     std::vector<cv::Mat> color_feat;
530     if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
531         // resize to default size
532         if (scale > 1.) {
533             // if we downsample use  INTER_AREA interpolation
534             cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0.,
535                        cv::INTER_AREA);
536         } else {
537             cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0.,
538                        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     BIG_BATCH_OMP_ORDERED
559     vars.patch_feats.insert(vars.patch_feats.end(), color_feat.begin(), color_feat.end());
560     return;
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] = float(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 #ifdef CUFFT
734     xf.sqr_norm(vars.xf_sqr_norm.deviceMem());
735     if (!auto_correlation) yf.sqr_norm(vars.yf_sqr_norm.deviceMem());
736 #else
737     xf.sqr_norm(vars.xf_sqr_norm.hostMem());
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.hostMem());
742     }
743 #endif
744     vars.xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
745     DEBUG_PRINTM(vars.xyf);
746     fft.inverse(vars.xyf, vars.ifft2_res, m_use_cuda ? vars.data_i_features.deviceMem() : nullptr, vars.stream);
747 #ifdef CUFFT
748     if (auto_correlation)
749         cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(), vars.xf_sqr_norm.deviceMem(), vars.xf_sqr_norm.deviceMem(),
750                                   sigma, xf.n_channels, xf.n_scales, p_roi.height, p_roi.width, vars.stream);
751     else
752         cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(), vars.xf_sqr_norm.deviceMem(), vars.yf_sqr_norm.deviceMem(),
753                                   sigma, xf.n_channels, xf.n_scales, p_roi.height, p_roi.width, vars.stream);
754 #else
755     // ifft2 and sum over 3rd dimension, we dont care about individual channels
756     DEBUG_PRINTM(vars.ifft2_res);
757     cv::Mat xy_sum;
758     if (xf.channels() != p_num_scales * p_num_of_feats)
759         xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
760     else
761         xy_sum.create(vars.ifft2_res.size(), CV_32FC(int(p_scales.size())));
762     xy_sum.setTo(0);
763     for (int y = 0; y < vars.ifft2_res.rows; ++y) {
764         float *row_ptr = vars.ifft2_res.ptr<float>(y);
765         float *row_ptr_sum = xy_sum.ptr<float>(y);
766         for (int x = 0; x < vars.ifft2_res.cols; ++x) {
767             for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
768                 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
769                     row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
770                     (row_ptr + x * vars.ifft2_res.channels() +
771                      (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
772                     0.f);
773             }
774         }
775     }
776     DEBUG_PRINTM(xy_sum);
777
778     std::vector<cv::Mat> scales;
779     cv::split(xy_sum, scales);
780
781     float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
782     for (uint i = 0; i < uint(xf.n_scales); ++i) {
783         cv::Mat in_roi(vars.in_all, cv::Rect(0, int(i) * scales[0].rows, scales[0].cols, scales[0].rows));
784         cv::exp(
785             -1. / (sigma * sigma) *
786                 cv::max((double(vars.xf_sqr_norm.hostMem()[i] + vars.yf_sqr_norm.hostMem()[0]) - 2 * scales[i]) * double(numel_xf_inv), 0),
787             in_roi);
788         DEBUG_PRINTM(in_roi);
789     }
790 #endif
791     DEBUG_PRINTM(vars.in_all);
792     fft.forward(vars.in_all, auto_correlation ? vars.kf : vars.kzf, m_use_cuda ? vars.gauss_corr_res.deviceMem() : nullptr,
793                 vars.stream);
794     return;
795 }
796
797 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
798 {
799     int x = pt.x;
800     int y = pt.y;
801     if (x < 0) x = response.cols + x;
802     if (y < 0) y = response.rows + y;
803     if (x >= response.cols) x = x - response.cols;
804     if (y >= response.rows) y = y - response.rows;
805
806     return response.at<float>(y, x);
807 }
808
809 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response)
810 {
811     // find neighbourhood of max_loc (response is circular)
812     // 1 2 3
813     // 4   5
814     // 6 7 8
815     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);
816     cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
817     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);
818
819     // clang-format off
820     // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
821     cv::Mat A = (cv::Mat_<float>(9, 6) <<
822                  p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
823                  p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
824                  p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
825                  p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
826                  p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
827                  p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
828                  p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
829                  p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
830                  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);
831     cv::Mat fval = (cv::Mat_<float>(9, 1) <<
832                     get_response_circular(p1, response),
833                     get_response_circular(p2, response),
834                     get_response_circular(p3, response),
835                     get_response_circular(p4, response),
836                     get_response_circular(p5, response),
837                     get_response_circular(p6, response),
838                     get_response_circular(p7, response),
839                     get_response_circular(p8, response),
840                     get_response_circular(max_loc, response));
841     // clang-format on
842     cv::Mat x;
843     cv::solve(A, fval, x, cv::DECOMP_SVD);
844
845     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);
846
847     cv::Point2f sub_peak(max_loc.x, max_loc.y);
848     if (b > 0 || b < 0) {
849         sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
850         sub_peak.x = (-2 * c * sub_peak.y - e) / b;
851     }
852
853     return sub_peak;
854 }
855
856 double KCF_Tracker::sub_grid_scale(int index)
857 {
858     cv::Mat A, fval;
859     if (index < 0 || index > int(p_scales.size()) - 1) {
860         // interpolate from all values
861         // fit 1d quadratic function f(x) = a*x^2 + b*x + c
862         A.create(int(p_scales.size()), 3, CV_32FC1);
863         fval.create(int(p_scales.size()), 1, CV_32FC1);
864         for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
865             uint i = uint(std::distance(p_threadctxs.begin(), it));
866             int j = int(i);
867             A.at<float>(j, 0) = float(p_scales[i] * p_scales[i]);
868             A.at<float>(j, 1) = float(p_scales[i]);
869             A.at<float>(j, 2) = 1;
870             fval.at<float>(j) =
871                 m_use_big_batch ? float(p_threadctxs.back().max_responses[i]) : float(it->max_response);
872         }
873     } else {
874         // only from neighbours
875         if (index == 0 || index == int(p_scales.size()) - 1) return p_scales[uint(index)];
876
877         A = (cv::Mat_<float>(3, 3) << p_scales[uint(index) - 1] * p_scales[uint(index) - 1], p_scales[uint(index) - 1],
878              1, p_scales[uint(index)] * p_scales[uint(index)], p_scales[uint(index)], 1,
879              p_scales[uint(index) + 1] * p_scales[uint(index) + 1], p_scales[uint(index) + 1], 1);
880         auto it1 = p_threadctxs.begin();
881         std::advance(it1, index - 1);
882         auto it2 = p_threadctxs.begin();
883         std::advance(it2, index);
884         auto it3 = p_threadctxs.begin();
885         std::advance(it3, index + 1);
886         fval = (cv::Mat_<float>(3, 1) << (m_use_big_batch ? p_threadctxs.back().max_responses[uint(index) - 1]
887                                                           : it1->max_response),
888                 (m_use_big_batch ? p_threadctxs.back().max_responses[uint(index)] : it2->max_response),
889                 (m_use_big_batch ? p_threadctxs.back().max_responses[uint(index) + 1] : it3->max_response));
890     }
891
892     cv::Mat x;
893     cv::solve(A, fval, x, cv::DECOMP_SVD);
894     float a = x.at<float>(0), b = x.at<float>(1);
895     double scale = p_scales[uint(index)];
896     if (a > 0 || a < 0) scale = double(-b / (2 * a));
897     return scale;
898 }