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