]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blob - src/kcf.cpp
Scale_vars version now supports FFTW
[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 defined(CUFFT)
11   #include "fft_cufft.h"
12   #define FFT cuFFT
13 #else
14   #include "fft_opencv.h"
15   #define FFT FftOpencv
16 #endif
17
18 #ifdef OPENMP
19 #include <omp.h>
20 #endif //OPENMP
21
22 #define DEBUG_PRINT(obj) 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     for (int i = 0;i < p_num_scales;++i) {
38         CudaSafeCall(cudaFreeHost(scale_vars[i].xf_sqr_norm));
39         CudaSafeCall(cudaFreeHost(scale_vars[i].yf_sqr_norm));
40         CudaSafeCall(cudaFree(scale_vars[i].gauss_corr_res));
41     }
42 #else
43     for (int i = 0;i < p_num_scales;++i) {
44         free(scale_vars[i].xf_sqr_norm);
45         free(scale_vars[i].yf_sqr_norm);
46     }
47 #endif
48 }
49
50 void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox, int fit_size_x, int fit_size_y)
51 {
52     //check boundary, enforce min size
53     double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
54     if (x1 < 0) x1 = 0.;
55     if (x2 > img.cols-1) x2 = img.cols - 1;
56     if (y1 < 0) y1 = 0;
57     if (y2 > img.rows-1) y2 = img.rows - 1;
58
59     if (x2-x1 < 2*p_cell_size) {
60         double diff = (2*p_cell_size -x2+x1)/2.;
61         if (x1 - diff >= 0 && x2 + diff < img.cols){
62             x1 -= diff;
63             x2 += diff;
64         } else if (x1 - 2*diff >= 0) {
65             x1 -= 2*diff;
66         } else {
67             x2 += 2*diff;
68         }
69     }
70     if (y2-y1 < 2*p_cell_size) {
71         double diff = (2*p_cell_size -y2+y1)/2.;
72         if (y1 - diff >= 0 && y2 + diff < img.rows){
73             y1 -= diff;
74             y2 += diff;
75         } else if (y1 - 2*diff >= 0) {
76             y1 -= 2*diff;
77         } else {
78             y2 += 2*diff;
79         }
80     }
81
82     p_pose.w = x2-x1;
83     p_pose.h = y2-y1;
84     p_pose.cx = x1 + p_pose.w/2.;
85     p_pose.cy = y1 + p_pose.h /2.;
86
87
88     cv::Mat input_gray, input_rgb = img.clone();
89     if (img.channels() == 3){
90         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
91         input_gray.convertTo(input_gray, CV_32FC1);
92     }else
93         img.convertTo(input_gray, CV_32FC1);
94
95     // don't need too large image
96     if (p_pose.w * p_pose.h > 100.*100. && (fit_size_x == -1 || fit_size_y == -1)) {
97         std::cout << "resizing image by factor of " << 1/p_downscale_factor << std::endl;
98         p_resize_image = true;
99         p_pose.scale(p_downscale_factor);
100         cv::resize(input_gray, input_gray, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
101         cv::resize(input_rgb, input_rgb, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
102     } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
103         if (fit_size_x%p_cell_size != 0 || fit_size_y%p_cell_size != 0) {
104             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;;
105             std::exit(EXIT_FAILURE);
106         }
107         double tmp;
108         if (( tmp = (p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_x)
109             p_scale_factor_x = fit_size_x/tmp;
110         if (( tmp = (p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_y)
111             p_scale_factor_y = fit_size_y/tmp;
112         std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x
113                   << " and verticaly by factor of " << p_scale_factor_y << std::endl;
114         p_fit_to_pw2 = true;
115         p_pose.scale_x(p_scale_factor_x);
116         p_pose.scale_y(p_scale_factor_y);
117         if (p_scale_factor_x != 1 && p_scale_factor_y != 1) {
118             if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
119                 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
120                 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
121             } else {
122                 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
123                 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
124             }
125         }
126     }
127
128     //compute win size + fit to fhog cell size
129     p_windows_size[0] = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
130     p_windows_size[1] = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
131
132     p_scales.clear();
133     if (m_use_scale)
134         for (int i = -p_num_scales/2; i <= p_num_scales/2; ++i)
135             p_scales.push_back(std::pow(p_scale_step, i));
136     else
137         p_scales.push_back(1.);
138
139     for (int i = 0;i<p_num_scales;++i) {
140         scale_vars.push_back(Scale_vars());
141     }
142
143     p_num_of_feats = 31;
144     if(m_use_color) p_num_of_feats += 3;
145     if(m_use_cnfeat) p_num_of_feats += 10;
146     p_roi_width = p_windows_size[0]/p_cell_size;
147     p_roi_height = p_windows_size[1]/p_cell_size;
148
149 #ifdef BIG_BATCH
150     int alloc_size = p_num_scales;
151 #else
152     int alloc_size = 1;
153 #endif
154
155 #ifdef CUFFT
156     if (p_windows_size[1]/p_cell_size*(p_windows_size[0]/p_cell_size/2+1) > 1024) {
157         std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
158         "the window dimensions so its size is less or equal to " << 1024*p_cell_size*p_cell_size*2+1 <<
159         " pixels . Currently the size of the window is: " <<  p_windows_size[0] << "x" <<  p_windows_size[1] <<
160         " which is  " <<  p_windows_size[0]*p_windows_size[1] << " pixels. " << std::endl;
161         std::exit(EXIT_FAILURE);
162     }
163
164     if (m_use_linearkernel){
165         std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
166         std::exit(EXIT_FAILURE);
167     }
168     cudaSetDeviceFlags(cudaDeviceMapHost);
169
170     for (int i = 0;i<p_num_scales;++i) {
171         CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].xf_sqr_norm, alloc_size*sizeof(float), cudaHostAllocMapped));
172         CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].xf_sqr_norm_d, (void*)scale_vars[i].xf_sqr_norm, 0));
173
174         CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].yf_sqr_norm, sizeof(float), cudaHostAllocMapped));
175         CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].yf_sqr_norm_d, (void*)scale_vars[i].yf_sqr_norm, 0));
176
177         CudaSafeCall(cudaMalloc((void**)&scale_vars[i].gauss_corr_res, (p_windows_size[0]/p_cell_size)*(p_windows_size[1]/p_cell_size)*alloc_size*sizeof(float)));
178     }
179 #else
180     for (int i = 0;i<p_num_scales;++i) {
181         scale_vars[i].xf_sqr_norm = (float*) malloc(alloc_size*sizeof(float));
182         scale_vars[i].yf_sqr_norm = (float*) malloc(sizeof(float));
183
184         scale_vars[i].patch_feats.reserve(p_num_of_feats);
185 #ifdef FFTW
186         scale_vars[i].ifft2_res = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC(p_num_of_feats));
187         scale_vars[i].response = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC1);
188
189         scale_vars[i].zf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
190         scale_vars[i].kzf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
191         scale_vars[i].kf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
192         //We use scale_vars[0] for updating the tracker, so we only allocate memory for  its xf only.
193         if (i==0)
194             scale_vars[i].xf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
195 #else
196         scale_vars[i].zf = ComplexMat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, p_num_of_feats);
197         if (i==0)
198             scale_vars[i].xf = ComplexMat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, p_num_of_feats);
199 #endif
200     }
201 #endif
202
203     p_current_scale = 1.;
204
205     double min_size_ratio = std::max(5.*p_cell_size/p_windows_size[0], 5.*p_cell_size/p_windows_size[1]);
206     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]);
207     p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
208     p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
209
210     std::cout << "init: img size " << img.cols << " " << img.rows << std::endl;
211     std::cout << "init: win size. " << p_windows_size[0] << " " << p_windows_size[1] << std::endl;
212     std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
213
214     p_output_sigma = std::sqrt(p_pose.w*p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
215
216     //window weights, i.e. labels
217     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);
218     p_yf = fft.forward(gaussian_shaped_labels(p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
219     fft.set_window(cosine_window_function(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
220
221     //obtain a sub-window for training initial model
222     get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], scale_vars[0]);
223     p_model_xf = fft.forward_window(scale_vars[0].patch_feats);
224     DEBUG_PRINTM(p_model_xf);
225     scale_vars[0].flag = Track_flags::AUTO_CORRELATION;
226
227     if (m_use_linearkernel) {
228         ComplexMat xfconj = p_model_xf.conj();
229         p_model_alphaf_num = xfconj.mul(p_yf);
230         p_model_alphaf_den = (p_model_xf * xfconj);
231     } else {
232         //Kernel Ridge Regression, calculate alphas (in Fourier domain)
233         gaussian_correlation(scale_vars[0], p_model_xf, p_model_xf, p_kernel_sigma, true);
234         DEBUG_PRINTM(scale_vars[0].kf);
235         p_model_alphaf_num = p_yf * scale_vars[0].kf;
236         DEBUG_PRINTM(p_model_alphaf_num);
237         p_model_alphaf_den = scale_vars[0].kf * (scale_vars[0].kf + p_lambda);
238         DEBUG_PRINTM(p_model_alphaf_den);
239     }
240     p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
241     DEBUG_PRINTM(p_model_alphaf);
242 //        p_model_alphaf = p_yf / (kf + p_lambda);   //equation for fast training
243 }
244
245 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img, int fit_size_x, int fit_size_y)
246 {
247     init(img, bbox.get_rect(), fit_size_x, fit_size_y);
248 }
249
250 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
251 {
252     if (p_resize_image) {
253         BBox_c tmp = bbox;
254         tmp.scale(p_downscale_factor);
255         p_pose.cx = tmp.cx;
256         p_pose.cy = tmp.cy;
257     } else if (p_fit_to_pw2) {
258         BBox_c tmp = bbox;
259         tmp.scale_x(p_scale_factor_x);
260         tmp.scale_y(p_scale_factor_y);
261         p_pose.cx = tmp.cx;
262         p_pose.cy = tmp.cy;
263     } else {
264         p_pose.cx = bbox.cx;
265         p_pose.cy = bbox.cy;
266     }
267 }
268
269 BBox_c KCF_Tracker::getBBox()
270 {
271     BBox_c tmp = p_pose;
272     tmp.w *= p_current_scale;
273     tmp.h *= p_current_scale;
274
275     if (p_resize_image)
276         tmp.scale(1/p_downscale_factor);
277     if (p_fit_to_pw2) {
278         tmp.scale_x(1/p_scale_factor_x);
279         tmp.scale_y(1/p_scale_factor_y);
280     }
281
282     return tmp;
283 }
284
285 void KCF_Tracker::track(cv::Mat &img)
286 {
287     if (m_debug)
288         std::cout << "NEW FRAME" << '\n';
289     cv::Mat input_gray, input_rgb = img.clone();
290     if (img.channels() == 3){
291         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
292         input_gray.convertTo(input_gray, CV_32FC1);
293     }else
294         img.convertTo(input_gray, CV_32FC1);
295
296     // don't need too large image
297     if (p_resize_image) {
298         cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
299         cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
300     } else if (p_fit_to_pw2 && p_scale_factor_x != 1 && p_scale_factor_y != 1) {
301         if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
302             cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
303             cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
304         } else {
305             cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
306             cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
307         }
308     }
309
310     double max_response = -1.;
311     int scale_index = 0;
312     cv::Point2i *max_response_pt = nullptr;
313     cv::Mat *max_response_map = nullptr;
314
315     if(m_use_multithreading) {
316         std::vector<std::future<void>> async_res(p_scales.size());
317         for (size_t i = 0; i < scale_vars.size(); ++i) {
318             async_res[i] = std::async(std::launch::async,
319                                 [this, &input_gray, &input_rgb, i]() -> void
320                                 {return scale_track(this->scale_vars[i], input_rgb, input_gray, this->p_scales[i]);});
321         }
322         for (size_t i = 0; i < p_scales.size(); ++i) {
323             async_res[i].wait();
324             if (this->scale_vars[i].max_response > max_response) {
325                 max_response = this->scale_vars[i].max_response;
326                 max_response_pt = & this->scale_vars[i].max_loc;
327                 max_response_map = & this->scale_vars[i].response;
328                 scale_index = i;
329             }
330         }
331     } else {
332 #pragma omp parallel for schedule(dynamic)
333         for (size_t i = 0; i < scale_vars.size(); ++i) {
334             scale_track(this->scale_vars[i], input_rgb, input_gray, this->p_scales[i]);
335 #pragma omp critical
336             {
337                 if (this->scale_vars[i].max_response > max_response) {
338                     max_response = this->scale_vars[i].max_response;
339                     max_response_pt = & this->scale_vars[i].max_loc;
340                     max_response_map = & this->scale_vars[i].response;
341                     scale_index = i;
342                 }
343             }
344         }
345     }
346
347     DEBUG_PRINTM(*max_response_map);
348     DEBUG_PRINT(*max_response_pt);
349
350     //sub pixel quadratic interpolation from neighbours
351     if (max_response_pt->y > max_response_map->rows / 2) //wrap around to negative half-space of vertical axis
352         max_response_pt->y = max_response_pt->y - max_response_map->rows;
353     if (max_response_pt->x > max_response_map->cols / 2) //same for horizontal axis
354         max_response_pt->x = max_response_pt->x - max_response_map->cols;
355
356     cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
357     DEBUG_PRINT(new_location);
358
359     if (m_use_subpixel_localization)
360         new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
361     DEBUG_PRINT(new_location);
362
363     p_pose.cx += p_current_scale*p_cell_size*new_location.x;
364     p_pose.cy += p_current_scale*p_cell_size*new_location.y;
365     if (p_fit_to_pw2) {
366         if (p_pose.cx < 0) p_pose.cx = 0;
367         if (p_pose.cx > (img.cols*p_scale_factor_x)-1) p_pose.cx = (img.cols*p_scale_factor_x)-1;
368         if (p_pose.cy < 0) p_pose.cy = 0;
369         if (p_pose.cy > (img.rows*p_scale_factor_y)-1) p_pose.cy = (img.rows*p_scale_factor_y)-1;
370     } else {
371         if (p_pose.cx < 0) p_pose.cx = 0;
372         if (p_pose.cx > img.cols-1) p_pose.cx = img.cols-1;
373         if (p_pose.cy < 0) p_pose.cy = 0;
374         if (p_pose.cy > img.rows-1) p_pose.cy = img.rows-1;
375     }
376
377     //sub grid scale interpolation
378     double new_scale = p_scales[scale_index];
379     if (m_use_subgrid_scale)
380         new_scale = sub_grid_scale(scale_index);
381
382     p_current_scale *= new_scale;
383
384     if (p_current_scale < p_min_max_scale[0])
385         p_current_scale = p_min_max_scale[0];
386     if (p_current_scale > p_min_max_scale[1])
387         p_current_scale = p_min_max_scale[1];
388     //obtain a subwindow for training at newly estimated target position
389     get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], scale_vars[0], p_current_scale);
390     scale_vars[0].flag = Track_flags::TRACKER_UPDATE;
391     fft.forward_window(scale_vars[0]);
392
393     //subsequent frames, interpolate model
394     p_model_xf = p_model_xf * (1. - p_interp_factor) + scale_vars[0].xf * p_interp_factor;
395
396     ComplexMat alphaf_num, alphaf_den;
397
398     if (m_use_linearkernel) {
399         ComplexMat xfconj = scale_vars[0].xf.conj();
400         alphaf_num = xfconj.mul(p_yf);
401         alphaf_den = (scale_vars[0].xf * xfconj);
402     } else {
403         scale_vars[0].flag = Track_flags::AUTO_CORRELATION;
404         //Kernel Ridge Regression, calculate alphas (in Fourier domain)
405         gaussian_correlation(scale_vars[0], scale_vars[0].xf, scale_vars[0].xf, p_kernel_sigma, true);
406 //        ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
407 //        p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
408         alphaf_num = p_yf * scale_vars[0].kf;
409         alphaf_den = scale_vars[0].kf * (scale_vars[0].kf + p_lambda);
410     }
411
412     p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
413     p_model_alphaf_den = p_model_alphaf_den * (1. - p_interp_factor) + alphaf_den * p_interp_factor;
414     p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
415 }
416
417 // ****************************************************************************
418
419 void KCF_Tracker::scale_track(Scale_vars & vars, cv::Mat & input_rgb, cv::Mat & input_gray, double scale)
420 {
421     get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy, this->p_windows_size[0], this->p_windows_size[1],
422                                 vars, this->p_current_scale * scale);
423
424     vars.flag = Track_flags::SCALE_RESPONSE;
425     fft.forward_window(vars);
426     DEBUG_PRINTM(vars.zf);
427
428     if (m_use_linearkernel) {
429                 vars.kzf = (vars.zf.mul2(this->p_model_alphaf)).sum_over_channels();
430                 vars.flag = Track_flags::RESPONSE;
431                 fft.inverse(vars);
432     } else {
433         vars.flag = Track_flags::CROSS_CORRELATION;
434         gaussian_correlation(vars, vars.zf, this->p_model_xf, this->p_kernel_sigma);
435         DEBUG_PRINTM(this->p_model_alphaf);
436         DEBUG_PRINTM(vars.kzf);
437         DEBUG_PRINTM(this->p_model_alphaf * vars.kzf);
438         vars.flag = Track_flags::RESPONSE;
439         vars.kzf = this->p_model_alphaf * vars.kzf;
440         fft.inverse(vars);
441     }
442
443     DEBUG_PRINTM(vars.response);
444
445     /* target location is at the maximum response. we must take into
446     account the fact that, if the target doesn't move, the peak
447     will appear at the top-left corner, not at the center (this is
448     discussed in the paper). the responses wrap around cyclically. */
449     double min_val;
450     cv::Point2i min_loc;
451     cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
452
453     DEBUG_PRINT(vars.max_loc);
454
455     double weight = scale < 1. ? scale : 1./scale;
456     vars.max_response = vars.max_val*weight;
457 }
458
459 void KCF_Tracker::get_features(cv::Mat & input_rgb, cv::Mat & input_gray, int cx, int cy, int size_x, int size_y, Scale_vars &vars, 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     FHoG::extract(patch_gray, vars, 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     vars.patch_feats.insert(vars.patch_feats.end(), color_feat.begin(), color_feat.end());
508     return;
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 void KCF_Tracker::gaussian_correlation(struct Scale_vars & vars, const ComplexMat & xf, const ComplexMat & yf, double sigma, bool auto_correlation)
671 {
672 #ifdef CUFFT
673     xf.sqr_norm(vars.xf_sqr_norm_d);
674     if (!auto_correlation)
675         yf.sqr_norm(vars.yf_sqr_norm_d);
676 #else
677     xf.sqr_norm(vars.xf_sqr_norm);
678     if (auto_correlation){
679       vars.yf_sqr_norm[0] = vars.xf_sqr_norm[0];
680     } else {
681        yf.sqr_norm(vars.yf_sqr_norm);
682     }
683 #endif
684     vars.xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
685     DEBUG_PRINTM(vars.xyf);
686 #ifdef CUFFT
687     if(auto_correlation)
688         cuda_gaussian_correlation(fft.inverse_raw(xyf), vars.gauss_corr_res, vars.xf_sqr_norm_d, vars.xf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
689     else
690         cuda_gaussian_correlation(fft.inverse_raw(xyf), vars.gauss_corr_res, vars.xf_sqr_norm_d, vars.yf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
691
692     return fft.forward_raw(vars.gauss_corr_res, xf.n_scales==p_num_scales);
693 #else
694     //ifft2 and sum over 3rd dimension, we dont care about individual channels
695     fft.inverse(vars);
696     DEBUG_PRINTM(vars.ifft2_res);
697     cv::Mat xy_sum;
698     if (xf.channels() != p_num_scales*p_num_of_feats)
699         xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
700     else
701         xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
702     xy_sum.setTo(0);
703     for (int y = 0; y < vars.ifft2_res.rows; ++y) {
704         float * row_ptr = vars.ifft2_res.ptr<float>(y);
705         float * row_ptr_sum = xy_sum.ptr<float>(y);
706         for (int x = 0; x < vars.ifft2_res.cols; ++x) {
707             for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
708                 row_ptr_sum[(x*xy_sum.channels())+sum_ch] += std::accumulate(row_ptr + x*vars.ifft2_res.channels() + sum_ch*(vars.ifft2_res.channels()/xy_sum.channels()),
709                                                                                                                                                         (row_ptr + x*vars.ifft2_res.channels() + (sum_ch+1)*(vars.ifft2_res.channels()/xy_sum.channels())), 0.f);
710             }
711         }
712     }
713     DEBUG_PRINTM(xy_sum);
714
715     std::vector<cv::Mat> scales;
716     cv::split(xy_sum,scales);
717     vars.in_all = cv::Mat(scales[0].rows * xf.n_scales, scales[0].cols, CV_32F);
718
719     float numel_xf_inv = 1.f/(xf.cols * xf.rows * (xf.channels()/xf.n_scales));
720     for (int i = 0; i < xf.n_scales; ++i){
721         cv::Mat in_roi(vars.in_all, cv::Rect(0, i*scales[0].rows, scales[0].cols, scales[0].rows));
722         cv::exp(- 1.f / (sigma * sigma) * cv::max((vars.xf_sqr_norm[i] + vars.yf_sqr_norm[0] - 2 * scales[i]) * numel_xf_inv, 0), in_roi);
723         DEBUG_PRINTM(in_roi);
724     }
725
726     DEBUG_PRINTM(vars.in_all );
727     fft.forward(vars);
728     return;
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     // clang-format off
759     // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
760     cv::Mat A = (cv::Mat_<float>(9, 6) <<
761                  p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
762                  p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
763                  p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
764                  p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
765                  p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
766                  p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
767                  p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
768                  p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
769                  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);
770     cv::Mat fval = (cv::Mat_<float>(9, 1) <<
771                     get_response_circular(p1, response),
772                     get_response_circular(p2, response),
773                     get_response_circular(p3, response),
774                     get_response_circular(p4, response),
775                     get_response_circular(p5, response),
776                     get_response_circular(p6, response),
777                     get_response_circular(p7, response),
778                     get_response_circular(p8, response),
779                     get_response_circular(max_loc, response));
780     // clang-format on
781     cv::Mat x;
782     cv::solve(A, fval, x, cv::DECOMP_SVD);
783
784     double a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2),
785            d = x.at<float>(3), e = x.at<float>(4);
786
787     cv::Point2f sub_peak(max_loc.x, max_loc.y);
788     if (b > 0 || b < 0) {
789         sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
790         sub_peak.x = (-2 * c * sub_peak.y - e) / b;
791     }
792
793     return sub_peak;
794 }
795
796 double KCF_Tracker::sub_grid_scale(int index)
797 {
798     cv::Mat A, fval;
799     if (index < 0 || index > (int)p_scales.size()-1) {
800         // interpolate from all values
801         // fit 1d quadratic function f(x) = a*x^2 + b*x + c
802         A.create(p_scales.size(), 3, CV_32FC1);
803         fval.create(p_scales.size(), 1, CV_32FC1);
804         for (size_t i = 0; i < p_scales.size(); ++i) {
805             A.at<float>(i, 0) = p_scales[i] * p_scales[i];
806             A.at<float>(i, 1) = p_scales[i];
807             A.at<float>(i, 2) = 1;
808             fval.at<float>(i) = scale_vars[i].max_response;
809         }
810     } else {
811         //only from neighbours
812         if (index == 0 || index == (int)p_scales.size()-1)
813             return p_scales[index];
814
815         A = (cv::Mat_<float>(3, 3) <<
816              p_scales[index-1] * p_scales[index-1], p_scales[index-1], 1,
817              p_scales[index] * p_scales[index], p_scales[index], 1,
818              p_scales[index+1] * p_scales[index+1], p_scales[index+1], 1);
819         fval = (cv::Mat_<float>(3, 1) << scale_vars[index-1].max_response, scale_vars[index].max_response, scale_vars[index+1].max_response);
820     }
821
822     cv::Mat x;
823     cv::solve(A, fval, x, cv::DECOMP_SVD);
824     double a = x.at<float>(0), b = x.at<float>(1);
825     double scale = p_scales[index];
826     if (a > 0 || a < 0)
827         scale = -b / (2 * a);
828     return scale;
829 }