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