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