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