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