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