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