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