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