11 #include "fft_cufft.h"
14 #include "fft_opencv.h"
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;}
25 KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor, double output_sigma_factor, int cell_size) :
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) {}
30 KCF_Tracker::KCF_Tracker()
33 KCF_Tracker::~KCF_Tracker()
37 for (int i = 0;i < p_num_scales;++i) {
38 CudaSafeCall(cudaFreeHost(scale_vars[i].xf_sqr_norm));
39 CudaSafeCall(cudaFreeHost(scale_vars[i].yf_sqr_norm));
40 CudaSafeCall(cudaFree(scale_vars[i].gauss_corr_res));
43 for (int i = 0;i < p_num_scales;++i) {
44 free(scale_vars[i].xf_sqr_norm);
45 free(scale_vars[i].yf_sqr_norm);
50 void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox, int fit_size_x, int fit_size_y)
52 //check boundary, enforce min size
53 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
55 if (x2 > img.cols-1) x2 = img.cols - 1;
57 if (y2 > img.rows-1) y2 = img.rows - 1;
59 if (x2-x1 < 2*p_cell_size) {
60 double diff = (2*p_cell_size -x2+x1)/2.;
61 if (x1 - diff >= 0 && x2 + diff < img.cols){
64 } else if (x1 - 2*diff >= 0) {
70 if (y2-y1 < 2*p_cell_size) {
71 double diff = (2*p_cell_size -y2+y1)/2.;
72 if (y1 - diff >= 0 && y2 + diff < img.rows){
75 } else if (y1 - 2*diff >= 0) {
84 p_pose.cx = x1 + p_pose.w/2.;
85 p_pose.cy = y1 + p_pose.h /2.;
88 cv::Mat input_gray, input_rgb = img.clone();
89 if (img.channels() == 3){
90 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
91 input_gray.convertTo(input_gray, CV_32FC1);
93 img.convertTo(input_gray, CV_32FC1);
95 // don't need too large image
96 if (p_pose.w * p_pose.h > 100.*100. && (fit_size_x == -1 || fit_size_y == -1)) {
97 std::cout << "resizing image by factor of " << 1/p_downscale_factor << std::endl;
98 p_resize_image = true;
99 p_pose.scale(p_downscale_factor);
100 cv::resize(input_gray, input_gray, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
101 cv::resize(input_rgb, input_rgb, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
102 } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
103 if (fit_size_x%p_cell_size != 0 || fit_size_y%p_cell_size != 0) {
104 std::cerr << "Fit size does not fit to hog cell size. The dimensions have to be divisible by HOG cell size, which is: " << p_cell_size << std::endl;;
105 std::exit(EXIT_FAILURE);
108 if (( tmp = (p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_x)
109 p_scale_factor_x = fit_size_x/tmp;
110 if (( tmp = (p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_y)
111 p_scale_factor_y = fit_size_y/tmp;
112 std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x
113 << " and verticaly by factor of " << p_scale_factor_y << std::endl;
115 p_pose.scale_x(p_scale_factor_x);
116 p_pose.scale_y(p_scale_factor_y);
117 if (p_scale_factor_x != 1 && p_scale_factor_y != 1) {
118 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
119 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
120 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
122 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
123 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
128 //compute win size + fit to fhog cell size
129 p_windows_size[0] = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
130 p_windows_size[1] = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
134 for (int i = -p_num_scales/2; i <= p_num_scales/2; ++i)
135 p_scales.push_back(std::pow(p_scale_step, i));
137 p_scales.push_back(1.);
139 for (int i = 0;i<p_num_scales;++i) {
140 scale_vars.push_back(Scale_var());
145 if (p_windows_size[1]/p_cell_size*(p_windows_size[0]/p_cell_size/2+1) > 1024) {
146 std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
147 "the window dimensions so its size is less or equal to " << 1024*p_cell_size*p_cell_size*2+1 <<
148 " pixels . Currently the size of the window is: " << p_windows_size[0] << "x" << p_windows_size[1] <<
149 " which is " << p_windows_size[0]*p_windows_size[1] << " pixels. " << std::endl;
150 std::exit(EXIT_FAILURE);
153 if (m_use_linearkernel){
154 std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
155 std::exit(EXIT_FAILURE);
157 cudaSetDeviceFlags(cudaDeviceMapHost);
159 for (int i = 0;i<p_num_scales;++i) {
160 CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].xf_sqr_norm, p_num_scales*sizeof(float), cudaHostAllocMapped));
161 CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].xf_sqr_norm_d, (void*)scale_vars[i].xf_sqr_norm, 0));
163 CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].yf_sqr_norm, sizeof(float), cudaHostAllocMapped));
164 CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].yf_sqr_norm_d, (void*)scale_vars[i].yf_sqr_norm, 0));
166 CudaSafeCall(cudaMalloc((void**)&scale_vars[i].gauss_corr_res, (p_windows_size[0]/p_cell_size)*(p_windows_size[1]/p_cell_size)*p_num_scales*sizeof(float)));
169 for (int i = 0;i<p_num_scales;++i) {
170 scale_vars[i].xf_sqr_norm = (float*) malloc(p_num_scales*sizeof(float));
171 scale_vars[i].yf_sqr_norm = (float*) malloc(sizeof(float));
175 p_current_scale = 1.;
177 double min_size_ratio = std::max(5.*p_cell_size/p_windows_size[0], 5.*p_cell_size/p_windows_size[1]);
178 double max_size_ratio = std::min(floor((img.cols + p_windows_size[0]/3)/p_cell_size)*p_cell_size/p_windows_size[0], floor((img.rows + p_windows_size[1]/3)/p_cell_size)*p_cell_size/p_windows_size[1]);
179 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
180 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
182 std::cout << "init: img size " << img.cols << " " << img.rows << std::endl;
183 std::cout << "init: win size. " << p_windows_size[0] << " " << p_windows_size[1] << std::endl;
184 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
186 p_output_sigma = std::sqrt(p_pose.w*p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
188 //window weights, i.e. labels
190 if(m_use_color) p_num_of_feats += 3;
191 if(m_use_cnfeat) p_num_of_feats += 10;
192 p_roi_width = p_windows_size[0]/p_cell_size;
193 p_roi_height = p_windows_size[1]/p_cell_size;
195 fft.init(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size, p_num_of_feats, p_num_scales, m_use_big_batch);
196 p_yf = fft.forward(gaussian_shaped_labels(p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
197 fft.set_window(cosine_window_function(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
199 //obtain a sub-window for training initial model
200 std::vector<cv::Mat> path_feat = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1]);
201 p_model_xf = fft.forward_window(path_feat);
202 DEBUG_PRINTM(p_model_xf);
204 if (m_use_linearkernel) {
205 ComplexMat xfconj = p_model_xf.conj();
206 p_model_alphaf_num = xfconj.mul(p_yf);
207 p_model_alphaf_den = (p_model_xf * xfconj);
209 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
210 ComplexMat kf = gaussian_correlation(scale_vars[0], p_model_xf, p_model_xf, p_kernel_sigma, true);
212 p_model_alphaf_num = p_yf * kf;
213 DEBUG_PRINTM(p_model_alphaf_num);
214 p_model_alphaf_den = kf * (kf + p_lambda);
215 DEBUG_PRINTM(p_model_alphaf_den);
217 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
218 DEBUG_PRINTM(p_model_alphaf);
219 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
222 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img, int fit_size_x, int fit_size_y)
224 init(img, bbox.get_rect(), fit_size_x, fit_size_y);
227 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
229 if (p_resize_image) {
231 tmp.scale(p_downscale_factor);
234 } else if (p_fit_to_pw2) {
236 tmp.scale_x(p_scale_factor_x);
237 tmp.scale_y(p_scale_factor_y);
246 BBox_c KCF_Tracker::getBBox()
249 tmp.w *= p_current_scale;
250 tmp.h *= p_current_scale;
253 tmp.scale(1/p_downscale_factor);
255 tmp.scale_x(1/p_scale_factor_x);
256 tmp.scale_y(1/p_scale_factor_y);
262 void KCF_Tracker::track(cv::Mat &img)
265 std::cout << "NEW FRAME" << '\n';
266 cv::Mat input_gray, input_rgb = img.clone();
267 if (img.channels() == 3){
268 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
269 input_gray.convertTo(input_gray, CV_32FC1);
271 img.convertTo(input_gray, CV_32FC1);
273 // don't need too large image
274 if (p_resize_image) {
275 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
276 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
277 } else if (p_fit_to_pw2 && p_scale_factor_x != 1 && p_scale_factor_y != 1) {
278 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
279 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
280 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
282 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
283 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
288 std::vector<cv::Mat> patch_feat;
289 double max_response = -1.;
290 cv::Mat max_response_map;
291 cv::Point2i max_response_pt;
293 std::vector<double> scale_responses;
295 if (m_use_multithreading){
296 std::vector<std::future<cv::Mat>> async_res(p_scales.size());
297 for (size_t i = 0; i < p_scales.size(); ++i) {
298 async_res[i] = std::async(std::launch::async,
299 [this, &input_gray, &input_rgb, i]() -> cv::Mat
301 std::vector<cv::Mat> patch_feat_async = get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy, this->p_windows_size[0],
302 this->p_windows_size[1], this->p_current_scale * this->p_scales[i]);
303 ComplexMat zf = fft.forward_window(patch_feat_async);
304 if (m_use_linearkernel)
305 return fft.inverse((p_model_alphaf * zf).sum_over_channels());
307 ComplexMat kzf = gaussian_correlation(this->scale_vars[i], zf, this->p_model_xf, this->p_kernel_sigma);
308 return fft.inverse(this->p_model_alphaf * kzf);
313 for (size_t i = 0; i < p_scales.size(); ++i) {
316 cv::Mat response = async_res[i].get();
318 double min_val, max_val;
319 cv::Point2i min_loc, max_loc;
320 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
322 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
323 if (max_val*weight > max_response) {
324 max_response = max_val*weight;
325 max_response_map = response;
326 max_response_pt = max_loc;
329 scale_responses.push_back(max_val*weight);
331 } else if (m_use_big_batch){
332 #pragma omp parallel for ordered
333 for (size_t i = 0; i < p_scales.size(); ++i) {
334 std::vector<cv::Mat> tmp = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], p_current_scale * p_scales[i]);
336 patch_feat.insert(std::end(patch_feat), std::begin(tmp), std::end(tmp));
338 ComplexMat zf = fft.forward_window(patch_feat);
342 if (m_use_linearkernel)
343 response = fft.inverse((zf.mul2(p_model_alphaf)).sum_over_channels());
345 ComplexMat kzf = gaussian_correlation(scale_vars[0], zf, p_model_xf, p_kernel_sigma);
346 DEBUG_PRINTM(p_model_alphaf);
348 response = fft.inverse(kzf.mul(p_model_alphaf));
350 DEBUG_PRINTM(response);
351 std::vector<cv::Mat> scales;
352 cv::split(response,scales);
354 /* target location is at the maximum response. we must take into
355 account the fact that, if the target doesn't move, the peak
356 will appear at the top-left corner, not at the center (this is
357 discussed in the paper). the responses wrap around cyclically. */
358 for (size_t i = 0; i < p_scales.size(); ++i) {
359 double min_val, max_val;
360 cv::Point2i min_loc, max_loc;
361 cv::minMaxLoc(scales[i], &min_val, &max_val, &min_loc, &max_loc);
362 DEBUG_PRINT(max_loc);
364 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
366 if (max_val*weight > max_response) {
367 max_response = max_val*weight;
368 max_response_map = scales[i];
369 max_response_pt = max_loc;
372 scale_responses.push_back(max_val*weight);
375 #pragma omp parallel for ordered private(patch_feat) schedule(dynamic)
376 for (size_t i = 0; i < p_scales.size(); ++i) {
377 patch_feat = get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy, this->p_windows_size[0], this->p_windows_size[1], this->p_current_scale * this->p_scales[i]);
378 ComplexMat zf = fft.forward_window(patch_feat);
381 if (m_use_linearkernel)
382 response = fft.inverse((p_model_alphaf * zf).sum_over_channels());
384 ComplexMat kzf = gaussian_correlation(this->scale_vars[i], zf, this->p_model_xf, this->p_kernel_sigma);
385 DEBUG_PRINTM(p_model_alphaf);
387 DEBUG_PRINTM(p_model_alphaf * kzf);
388 response = fft.inverse(this->p_model_alphaf * kzf);
390 DEBUG_PRINTM(response);
392 /* target location is at the maximum response. we must take into
393 account the fact that, if the target doesn't move, the peak
394 will appear at the top-left corner, not at the center (this is
395 discussed in the paper). the responses wrap around cyclically. */
396 double min_val, max_val;
397 cv::Point2i min_loc, max_loc;
398 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
399 DEBUG_PRINT(max_loc);
401 double weight = this->p_scales[i] < 1. ? this->p_scales[i] : 1./this->p_scales[i];
404 if (max_val*weight > max_response) {
405 max_response = max_val*weight;
406 max_response_map = response;
407 max_response_pt = max_loc;
412 scale_responses.push_back(max_val*weight);
415 DEBUG_PRINTM(max_response_map);
416 DEBUG_PRINT(max_response_pt);
417 //sub pixel quadratic interpolation from neighbours
418 if (max_response_pt.y > max_response_map.rows / 2) //wrap around to negative half-space of vertical axis
419 max_response_pt.y = max_response_pt.y - max_response_map.rows;
420 if (max_response_pt.x > max_response_map.cols / 2) //same for horizontal axis
421 max_response_pt.x = max_response_pt.x - max_response_map.cols;
423 cv::Point2f new_location(max_response_pt.x, max_response_pt.y);
424 DEBUG_PRINT(new_location);
426 if (m_use_subpixel_localization)
427 new_location = sub_pixel_peak(max_response_pt, max_response_map);
428 DEBUG_PRINT(new_location);
430 p_pose.cx += p_current_scale*p_cell_size*new_location.x;
431 p_pose.cy += p_current_scale*p_cell_size*new_location.y;
433 if (p_pose.cx < 0) p_pose.cx = 0;
434 if (p_pose.cx > (img.cols*p_scale_factor_x)-1) p_pose.cx = (img.cols*p_scale_factor_x)-1;
435 if (p_pose.cy < 0) p_pose.cy = 0;
436 if (p_pose.cy > (img.rows*p_scale_factor_y)-1) p_pose.cy = (img.rows*p_scale_factor_y)-1;
438 if (p_pose.cx < 0) p_pose.cx = 0;
439 if (p_pose.cx > img.cols-1) p_pose.cx = img.cols-1;
440 if (p_pose.cy < 0) p_pose.cy = 0;
441 if (p_pose.cy > img.rows-1) p_pose.cy = img.rows-1;
444 //sub grid scale interpolation
445 double new_scale = p_scales[scale_index];
446 if (m_use_subgrid_scale)
447 new_scale = sub_grid_scale(scale_responses, scale_index);
449 p_current_scale *= new_scale;
451 if (p_current_scale < p_min_max_scale[0])
452 p_current_scale = p_min_max_scale[0];
453 if (p_current_scale > p_min_max_scale[1])
454 p_current_scale = p_min_max_scale[1];
455 //obtain a subwindow for training at newly estimated target position
456 patch_feat = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], p_current_scale);
457 ComplexMat xf = fft.forward_window(patch_feat);
459 //subsequent frames, interpolate model
460 p_model_xf = p_model_xf * (1. - p_interp_factor) + xf * p_interp_factor;
462 ComplexMat alphaf_num, alphaf_den;
464 if (m_use_linearkernel) {
465 ComplexMat xfconj = xf.conj();
466 alphaf_num = xfconj.mul(p_yf);
467 alphaf_den = (xf * xfconj);
469 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
470 ComplexMat kf = gaussian_correlation(scale_vars[0], xf, xf, p_kernel_sigma, true);
471 // ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
472 // p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
473 alphaf_num = p_yf * kf;
474 alphaf_den = kf * (kf + p_lambda);
477 p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
478 p_model_alphaf_den = p_model_alphaf_den * (1. - p_interp_factor) + alphaf_den * p_interp_factor;
479 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
482 // ****************************************************************************
484 std::vector<cv::Mat> KCF_Tracker::get_features(cv::Mat & input_rgb, cv::Mat & input_gray, int cx, int cy, int size_x, int size_y, double scale)
486 int size_x_scaled = floor(size_x*scale);
487 int size_y_scaled = floor(size_y*scale);
489 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
490 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
492 //resize to default size
494 //if we downsample use INTER_AREA interpolation
495 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
497 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
500 // get hog(Histogram of Oriented Gradients) features
501 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
503 //get color rgb features (simple r,g,b channels)
504 std::vector<cv::Mat> color_feat;
505 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
506 //resize to default size
508 //if we downsample use INTER_AREA interpolation
509 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_AREA);
511 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_LINEAR);
515 if (m_use_color && input_rgb.channels() == 3) {
516 //use rgb color space
517 cv::Mat patch_rgb_norm;
518 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
519 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
520 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
521 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
522 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
523 cv::split(patch_rgb_norm, rgb);
524 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
527 if (m_use_cnfeat && input_rgb.channels() == 3) {
528 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
529 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
532 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
536 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
538 cv::Mat labels(dim2, dim1, CV_32FC1);
539 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
540 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
542 double sigma_s = sigma*sigma;
544 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j){
545 float * row_ptr = labels.ptr<float>(j);
547 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i){
548 row_ptr[i] = std::exp(-0.5 * (y_s + x*x) / sigma_s);//-1/2*e^((y^2+x^2)/sigma^2)
552 //rotate so that 1 is at top-left corner (see KCF paper for explanation)
553 cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
554 //sanity check, 1 at top left corner
555 assert(rot_labels.at<float>(0,0) >= 1.f - 1e-10f);
560 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
562 cv::Mat rot_patch(patch.size(), CV_32FC1);
563 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
565 //circular rotate x-axis
567 //move part that does not rotate over the edge
568 cv::Range orig_range(-x_rot, patch.cols);
569 cv::Range rot_range(0, patch.cols - (-x_rot));
570 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
573 orig_range = cv::Range(0, -x_rot);
574 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
575 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
576 }else if (x_rot > 0){
577 //move part that does not rotate over the edge
578 cv::Range orig_range(0, patch.cols - x_rot);
579 cv::Range rot_range(x_rot, patch.cols);
580 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
583 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
584 rot_range = cv::Range(0, x_rot);
585 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
586 }else { //zero rotation
587 //move part that does not rotate over the edge
588 cv::Range orig_range(0, patch.cols);
589 cv::Range rot_range(0, patch.cols);
590 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
593 //circular rotate y-axis
595 //move part that does not rotate over the edge
596 cv::Range orig_range(-y_rot, patch.rows);
597 cv::Range rot_range(0, patch.rows - (-y_rot));
598 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
601 orig_range = cv::Range(0, -y_rot);
602 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
603 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
604 }else if (y_rot > 0){
605 //move part that does not rotate over the edge
606 cv::Range orig_range(0, patch.rows - y_rot);
607 cv::Range rot_range(y_rot, patch.rows);
608 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
611 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
612 rot_range = cv::Range(0, y_rot);
613 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
614 }else { //zero rotation
615 //move part that does not rotate over the edge
616 cv::Range orig_range(0, patch.rows);
617 cv::Range rot_range(0, patch.rows);
618 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
624 //hann window actually (Power-of-cosine windows)
625 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
627 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
628 double N_inv = 1./(static_cast<double>(dim1)-1.);
629 for (int i = 0; i < dim1; ++i)
630 m1.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
631 N_inv = 1./(static_cast<double>(dim2)-1.);
632 for (int i = 0; i < dim2; ++i)
633 m2.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
638 // Returns sub-window of image input centered at [cx, cy] coordinates),
639 // with size [width, height]. If any pixels are outside of the image,
640 // they will replicate the values at the borders.
641 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
645 int x1 = cx - width/2;
646 int y1 = cy - height/2;
647 int x2 = cx + width/2;
648 int y2 = cy + height/2;
651 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
652 patch.create(height, width, input.type());
657 int top = 0, bottom = 0, left = 0, right = 0;
659 //fit to image coordinates, set border extensions;
668 if (x2 >= input.cols) {
669 right = x2 - input.cols + width % 2;
674 if (y2 >= input.rows) {
675 bottom = y2 - input.rows + height % 2;
680 if (x2 - x1 == 0 || y2 - y1 == 0)
681 patch = cv::Mat::zeros(height, width, CV_32FC1);
684 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right, cv::BORDER_REPLICATE);
685 // imshow( "copyMakeBorder", patch);
690 assert(patch.cols == width && patch.rows == height);
695 ComplexMat KCF_Tracker::gaussian_correlation(struct Scale_var &vars, const ComplexMat &xf, const ComplexMat &yf, double sigma, bool auto_correlation)
698 xf.sqr_norm(vars.xf_sqr_norm_d);
699 if (!auto_correlation)
700 yf.sqr_norm(vars.yf_sqr_norm_d);
702 xf.sqr_norm(vars.xf_sqr_norm);
703 if (auto_correlation){
704 vars.yf_sqr_norm[0] = vars.xf_sqr_norm[0];
706 yf.sqr_norm(vars.yf_sqr_norm);
710 xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
714 cuda_gaussian_correlation(fft.inverse_raw(xyf), vars.gauss_corr_res, vars.xf_sqr_norm_d, vars.xf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
716 cuda_gaussian_correlation(fft.inverse_raw(xyf), vars.gauss_corr_res, vars.xf_sqr_norm_d, vars.yf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
718 return fft.forward_raw(vars.gauss_corr_res, xf.n_scales==p_num_scales);
720 //ifft2 and sum over 3rd dimension, we dont care about individual channels
721 cv::Mat ifft2_res = fft.inverse(xyf);
722 DEBUG_PRINTM(ifft2_res);
724 if (xf.channels() != p_num_scales*p_num_of_feats)
725 xy_sum.create(ifft2_res.size(), CV_32FC1);
727 xy_sum.create(ifft2_res.size(), CV_32FC(p_scales.size()));
729 for (int y = 0; y < ifft2_res.rows; ++y) {
730 float * row_ptr = ifft2_res.ptr<float>(y);
731 float * row_ptr_sum = xy_sum.ptr<float>(y);
732 for (int x = 0; x < ifft2_res.cols; ++x) {
733 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
734 row_ptr_sum[(x*xy_sum.channels())+sum_ch] += std::accumulate(row_ptr + x*ifft2_res.channels() + sum_ch*(ifft2_res.channels()/xy_sum.channels()), (row_ptr + x*ifft2_res.channels() + (sum_ch+1)*(ifft2_res.channels()/xy_sum.channels())), 0.f);
738 DEBUG_PRINTM(xy_sum);
740 std::vector<cv::Mat> scales;
741 cv::split(xy_sum,scales);
742 cv::Mat in_all(scales[0].rows * xf.n_scales, scales[0].cols, CV_32F);
744 float numel_xf_inv = 1.f/(xf.cols * xf.rows * (xf.channels()/xf.n_scales));
745 for (int i = 0; i < xf.n_scales; ++i){
746 cv::Mat in_roi(in_all, cv::Rect(0, i*scales[0].rows, scales[0].cols, scales[0].rows));
747 cv::exp(- 1.f / (sigma * sigma) * cv::max((vars.xf_sqr_norm[i] + vars.yf_sqr_norm[0] - 2 * scales[i]) * numel_xf_inv, 0), in_roi);
748 DEBUG_PRINTM(in_roi);
751 DEBUG_PRINTM(in_all);
752 return fft.forward(in_all);
756 float get_response_circular(cv::Point2i & pt, cv::Mat & response)
761 x = response.cols + x;
763 y = response.rows + y;
764 if (x >= response.cols)
765 x = x - response.cols;
766 if (y >= response.rows)
767 y = y - response.rows;
769 return response.at<float>(y,x);
772 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
774 //find neighbourhood of max_loc (response is circular)
778 cv::Point2i p1(max_loc.x-1, max_loc.y-1), p2(max_loc.x, max_loc.y-1), p3(max_loc.x+1, max_loc.y-1);
779 cv::Point2i p4(max_loc.x-1, max_loc.y), p5(max_loc.x+1, max_loc.y);
780 cv::Point2i p6(max_loc.x-1, max_loc.y+1), p7(max_loc.x, max_loc.y+1), p8(max_loc.x+1, max_loc.y+1);
783 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
784 cv::Mat A = (cv::Mat_<float>(9, 6) <<
785 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
786 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
787 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
788 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
789 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
790 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
791 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
792 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
793 max_loc.x*max_loc.x, max_loc.x*max_loc.y, max_loc.y*max_loc.y, max_loc.x, max_loc.y, 1.f);
794 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
795 get_response_circular(p1, response),
796 get_response_circular(p2, response),
797 get_response_circular(p3, response),
798 get_response_circular(p4, response),
799 get_response_circular(p5, response),
800 get_response_circular(p6, response),
801 get_response_circular(p7, response),
802 get_response_circular(p8, response),
803 get_response_circular(max_loc, response));
806 cv::solve(A, fval, x, cv::DECOMP_SVD);
808 double a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2),
809 d = x.at<float>(3), e = x.at<float>(4);
811 cv::Point2f sub_peak(max_loc.x, max_loc.y);
812 if (b > 0 || b < 0) {
813 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
814 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
820 double KCF_Tracker::sub_grid_scale(std::vector<double> & responses, int index)
823 if (index < 0 || index > (int)p_scales.size()-1) {
824 // interpolate from all values
825 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
826 A.create(p_scales.size(), 3, CV_32FC1);
827 fval.create(p_scales.size(), 1, CV_32FC1);
828 for (size_t i = 0; i < p_scales.size(); ++i) {
829 A.at<float>(i, 0) = p_scales[i] * p_scales[i];
830 A.at<float>(i, 1) = p_scales[i];
831 A.at<float>(i, 2) = 1;
832 fval.at<float>(i) = responses[i];
835 //only from neighbours
836 if (index == 0 || index == (int)p_scales.size()-1)
837 return p_scales[index];
839 A = (cv::Mat_<float>(3, 3) <<
840 p_scales[index-1] * p_scales[index-1], p_scales[index-1], 1,
841 p_scales[index] * p_scales[index], p_scales[index], 1,
842 p_scales[index+1] * p_scales[index+1], p_scales[index+1], 1);
843 fval = (cv::Mat_<float>(3, 1) << responses[index-1], responses[index], responses[index+1]);
847 cv::solve(A, fval, x, cv::DECOMP_SVD);
848 double a = x.at<float>(0), b = x.at<float>(1);
849 double scale = p_scales[index];
851 scale = -b / (2 * a);