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_vars());
144 if(m_use_color) p_num_of_feats += 3;
145 if(m_use_cnfeat) p_num_of_feats += 10;
146 p_roi_width = p_windows_size[0]/p_cell_size;
147 p_roi_height = p_windows_size[1]/p_cell_size;
150 int alloc_size = p_num_scales;
156 if (p_windows_size[1]/p_cell_size*(p_windows_size[0]/p_cell_size/2+1) > 1024) {
157 std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
158 "the window dimensions so its size is less or equal to " << 1024*p_cell_size*p_cell_size*2+1 <<
159 " pixels . Currently the size of the window is: " << p_windows_size[0] << "x" << p_windows_size[1] <<
160 " which is " << p_windows_size[0]*p_windows_size[1] << " pixels. " << std::endl;
161 std::exit(EXIT_FAILURE);
164 if (m_use_linearkernel){
165 std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
166 std::exit(EXIT_FAILURE);
168 cudaSetDeviceFlags(cudaDeviceMapHost);
170 for (int i = 0;i<p_num_scales;++i) {
171 CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].xf_sqr_norm, alloc_size*sizeof(float), cudaHostAllocMapped));
172 CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].xf_sqr_norm_d, (void*)scale_vars[i].xf_sqr_norm, 0));
174 CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].yf_sqr_norm, sizeof(float), cudaHostAllocMapped));
175 CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].yf_sqr_norm_d, (void*)scale_vars[i].yf_sqr_norm, 0));
177 CudaSafeCall(cudaMalloc((void**)&scale_vars[i].gauss_corr_res, (p_windows_size[0]/p_cell_size)*(p_windows_size[1]/p_cell_size)*alloc_size*sizeof(float)));
180 for (int i = 0;i<p_num_scales;++i) {
181 scale_vars[i].xf_sqr_norm = (float*) malloc(alloc_size*sizeof(float));
182 scale_vars[i].yf_sqr_norm = (float*) malloc(sizeof(float));
184 scale_vars[i].patch_feats.reserve(p_num_of_feats);
186 scale_vars[i].zf = ComplexMat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, p_num_of_feats);
187 //We use scale_vars[0] for updating the tracker, so we only allocate memory for its xf only.
189 scale_vars[i].xf = ComplexMat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, p_num_of_feats);
193 p_current_scale = 1.;
195 double min_size_ratio = std::max(5.*p_cell_size/p_windows_size[0], 5.*p_cell_size/p_windows_size[1]);
196 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]);
197 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
198 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
200 std::cout << "init: img size " << img.cols << " " << img.rows << std::endl;
201 std::cout << "init: win size. " << p_windows_size[0] << " " << p_windows_size[1] << std::endl;
202 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
204 p_output_sigma = std::sqrt(p_pose.w*p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
206 //window weights, i.e. labels
207 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);
208 p_yf = fft.forward(gaussian_shaped_labels(p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
209 fft.set_window(cosine_window_function(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
211 //obtain a sub-window for training initial model
212 get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], scale_vars[0]);
213 p_model_xf = fft.forward_window(scale_vars[0].patch_feats);
214 DEBUG_PRINTM(p_model_xf);
215 scale_vars[0].flag = Track_flags::AUTO_CORRELATION;
217 if (m_use_linearkernel) {
218 ComplexMat xfconj = p_model_xf.conj();
219 p_model_alphaf_num = xfconj.mul(p_yf);
220 p_model_alphaf_den = (p_model_xf * xfconj);
222 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
223 gaussian_correlation(scale_vars[0], p_model_xf, p_model_xf, p_kernel_sigma, true);
224 DEBUG_PRINTM(scale_vars[0].kf);
225 p_model_alphaf_num = p_yf * scale_vars[0].kf;
226 DEBUG_PRINTM(p_model_alphaf_num);
227 p_model_alphaf_den = scale_vars[0].kf * (scale_vars[0].kf + p_lambda);
228 DEBUG_PRINTM(p_model_alphaf_den);
230 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
231 DEBUG_PRINTM(p_model_alphaf);
232 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
235 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img, int fit_size_x, int fit_size_y)
237 init(img, bbox.get_rect(), fit_size_x, fit_size_y);
240 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
242 if (p_resize_image) {
244 tmp.scale(p_downscale_factor);
247 } else if (p_fit_to_pw2) {
249 tmp.scale_x(p_scale_factor_x);
250 tmp.scale_y(p_scale_factor_y);
259 BBox_c KCF_Tracker::getBBox()
262 tmp.w *= p_current_scale;
263 tmp.h *= p_current_scale;
266 tmp.scale(1/p_downscale_factor);
268 tmp.scale_x(1/p_scale_factor_x);
269 tmp.scale_y(1/p_scale_factor_y);
275 void KCF_Tracker::track(cv::Mat &img)
278 std::cout << "NEW FRAME" << '\n';
279 cv::Mat input_gray, input_rgb = img.clone();
280 if (img.channels() == 3){
281 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
282 input_gray.convertTo(input_gray, CV_32FC1);
284 img.convertTo(input_gray, CV_32FC1);
286 // don't need too large image
287 if (p_resize_image) {
288 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
289 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
290 } else if (p_fit_to_pw2 && p_scale_factor_x != 1 && p_scale_factor_y != 1) {
291 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
292 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
293 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
295 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
296 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
300 double max_response = -1.;
302 cv::Point2i *max_response_pt = nullptr;
303 cv::Mat *max_response_map = nullptr;
305 if(m_use_multithreading) {
306 std::vector<std::future<void>> async_res(p_scales.size());
307 for (size_t i = 0; i < scale_vars.size(); ++i) {
308 async_res[i] = std::async(std::launch::async,
309 [this, &input_gray, &input_rgb, i]() -> void
310 {return scale_track(this->scale_vars[i], input_rgb, input_gray, this->p_scales[i]);});
312 for (size_t i = 0; i < p_scales.size(); ++i) {
314 if (this->scale_vars[i].max_response > max_response) {
315 max_response = this->scale_vars[i].max_response;
316 max_response_pt = & this->scale_vars[i].max_loc;
317 max_response_map = & this->scale_vars[i].response;
322 #pragma omp parallel for schedule(dynamic)
323 for (size_t i = 0; i < scale_vars.size(); ++i) {
324 scale_track(this->scale_vars[i], input_rgb, input_gray, this->p_scales[i]);
327 if (this->scale_vars[i].max_response > max_response) {
328 max_response = this->scale_vars[i].max_response;
329 max_response_pt = & this->scale_vars[i].max_loc;
330 max_response_map = & this->scale_vars[i].response;
337 DEBUG_PRINTM(*max_response_map);
338 DEBUG_PRINT(*max_response_pt);
340 //sub pixel quadratic interpolation from neighbours
341 if (max_response_pt->y > max_response_map->rows / 2) //wrap around to negative half-space of vertical axis
342 max_response_pt->y = max_response_pt->y - max_response_map->rows;
343 if (max_response_pt->x > max_response_map->cols / 2) //same for horizontal axis
344 max_response_pt->x = max_response_pt->x - max_response_map->cols;
346 cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
347 DEBUG_PRINT(new_location);
349 if (m_use_subpixel_localization)
350 new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
351 DEBUG_PRINT(new_location);
353 p_pose.cx += p_current_scale*p_cell_size*new_location.x;
354 p_pose.cy += p_current_scale*p_cell_size*new_location.y;
356 if (p_pose.cx < 0) p_pose.cx = 0;
357 if (p_pose.cx > (img.cols*p_scale_factor_x)-1) p_pose.cx = (img.cols*p_scale_factor_x)-1;
358 if (p_pose.cy < 0) p_pose.cy = 0;
359 if (p_pose.cy > (img.rows*p_scale_factor_y)-1) p_pose.cy = (img.rows*p_scale_factor_y)-1;
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;
367 //sub grid scale interpolation
368 double new_scale = p_scales[scale_index];
369 if (m_use_subgrid_scale)
370 new_scale = sub_grid_scale(scale_index);
372 p_current_scale *= new_scale;
374 if (p_current_scale < p_min_max_scale[0])
375 p_current_scale = p_min_max_scale[0];
376 if (p_current_scale > p_min_max_scale[1])
377 p_current_scale = p_min_max_scale[1];
378 //obtain a subwindow for training at newly estimated target position
379 get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], scale_vars[0], p_current_scale);
380 scale_vars[0].flag = Track_flags::TRACKER_UPDATE;
381 fft.forward_window(scale_vars[0]);
383 //subsequent frames, interpolate model
384 p_model_xf = p_model_xf * (1. - p_interp_factor) + scale_vars[0].xf * p_interp_factor;
386 ComplexMat alphaf_num, alphaf_den;
388 if (m_use_linearkernel) {
389 ComplexMat xfconj = scale_vars[0].xf.conj();
390 alphaf_num = xfconj.mul(p_yf);
391 alphaf_den = (scale_vars[0].xf * xfconj);
393 scale_vars[0].flag = Track_flags::AUTO_CORRELATION;
394 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
395 gaussian_correlation(scale_vars[0], scale_vars[0].xf, scale_vars[0].xf, p_kernel_sigma, true);
396 // ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
397 // p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
398 alphaf_num = p_yf * scale_vars[0].kf;
399 alphaf_den = scale_vars[0].kf * (scale_vars[0].kf + p_lambda);
402 p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
403 p_model_alphaf_den = p_model_alphaf_den * (1. - p_interp_factor) + alphaf_den * p_interp_factor;
404 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
407 // ****************************************************************************
409 void KCF_Tracker::scale_track(Scale_vars & vars, cv::Mat & input_rgb, cv::Mat & input_gray, double scale)
411 get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy, this->p_windows_size[0], this->p_windows_size[1],
412 vars, this->p_current_scale * scale);
414 vars.flag = Track_flags::SCALE_RESPONSE;
415 fft.forward_window(vars);
416 DEBUG_PRINTM(vars.zf);
418 if (m_use_linearkernel) {
419 vars.kzf = (vars.zf.mul2(this->p_model_alphaf)).sum_over_channels();
420 vars.flag = Track_flags::RESPONSE;
423 vars.flag = Track_flags::CROSS_CORRELATION;
424 gaussian_correlation(vars, vars.zf, this->p_model_xf, this->p_kernel_sigma);
425 DEBUG_PRINTM(this->p_model_alphaf);
426 DEBUG_PRINTM(vars.kzf);
427 DEBUG_PRINTM(this->p_model_alphaf * vars.kzf);
428 vars.flag = Track_flags::RESPONSE;
429 vars.kzf = this->p_model_alphaf * vars.kzf;
433 DEBUG_PRINTM(vars.response);
435 /* target location is at the maximum response. we must take into
436 account the fact that, if the target doesn't move, the peak
437 will appear at the top-left corner, not at the center (this is
438 discussed in the paper). the responses wrap around cyclically. */
441 cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
443 DEBUG_PRINT(vars.max_loc);
445 double weight = scale < 1. ? scale : 1./scale;
446 vars.max_response = vars.max_val*weight;
449 void KCF_Tracker::get_features(cv::Mat & input_rgb, cv::Mat & input_gray, int cx, int cy, int size_x, int size_y, Scale_vars &vars, double scale)
451 int size_x_scaled = floor(size_x*scale);
452 int size_y_scaled = floor(size_y*scale);
454 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
455 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
457 //resize to default size
459 //if we downsample use INTER_AREA interpolation
460 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
462 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
465 // get hog(Histogram of Oriented Gradients) features
466 FHoG::extract(patch_gray, vars, 2, p_cell_size, 9);
468 //get color rgb features (simple r,g,b channels)
469 std::vector<cv::Mat> color_feat;
470 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
471 //resize to default size
473 //if we downsample use INTER_AREA interpolation
474 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_AREA);
476 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_LINEAR);
480 if (m_use_color && input_rgb.channels() == 3) {
481 //use rgb color space
482 cv::Mat patch_rgb_norm;
483 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
484 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
485 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
486 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
487 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
488 cv::split(patch_rgb_norm, rgb);
489 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
492 if (m_use_cnfeat && input_rgb.channels() == 3) {
493 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
494 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
497 vars.patch_feats.insert(vars.patch_feats.end(), color_feat.begin(), color_feat.end());
501 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
503 cv::Mat labels(dim2, dim1, CV_32FC1);
504 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
505 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
507 double sigma_s = sigma*sigma;
509 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j){
510 float * row_ptr = labels.ptr<float>(j);
512 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i){
513 row_ptr[i] = std::exp(-0.5 * (y_s + x*x) / sigma_s);//-1/2*e^((y^2+x^2)/sigma^2)
517 //rotate so that 1 is at top-left corner (see KCF paper for explanation)
518 cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
519 //sanity check, 1 at top left corner
520 assert(rot_labels.at<float>(0,0) >= 1.f - 1e-10f);
525 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
527 cv::Mat rot_patch(patch.size(), CV_32FC1);
528 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
530 //circular rotate x-axis
532 //move part that does not rotate over the edge
533 cv::Range orig_range(-x_rot, patch.cols);
534 cv::Range rot_range(0, patch.cols - (-x_rot));
535 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
538 orig_range = cv::Range(0, -x_rot);
539 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
540 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
541 }else if (x_rot > 0){
542 //move part that does not rotate over the edge
543 cv::Range orig_range(0, patch.cols - x_rot);
544 cv::Range rot_range(x_rot, patch.cols);
545 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
548 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
549 rot_range = cv::Range(0, x_rot);
550 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
551 }else { //zero rotation
552 //move part that does not rotate over the edge
553 cv::Range orig_range(0, patch.cols);
554 cv::Range rot_range(0, patch.cols);
555 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
558 //circular rotate y-axis
560 //move part that does not rotate over the edge
561 cv::Range orig_range(-y_rot, patch.rows);
562 cv::Range rot_range(0, patch.rows - (-y_rot));
563 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
566 orig_range = cv::Range(0, -y_rot);
567 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
568 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
569 }else if (y_rot > 0){
570 //move part that does not rotate over the edge
571 cv::Range orig_range(0, patch.rows - y_rot);
572 cv::Range rot_range(y_rot, patch.rows);
573 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
576 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
577 rot_range = cv::Range(0, y_rot);
578 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
579 }else { //zero rotation
580 //move part that does not rotate over the edge
581 cv::Range orig_range(0, patch.rows);
582 cv::Range rot_range(0, patch.rows);
583 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
589 //hann window actually (Power-of-cosine windows)
590 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
592 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
593 double N_inv = 1./(static_cast<double>(dim1)-1.);
594 for (int i = 0; i < dim1; ++i)
595 m1.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
596 N_inv = 1./(static_cast<double>(dim2)-1.);
597 for (int i = 0; i < dim2; ++i)
598 m2.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
603 // Returns sub-window of image input centered at [cx, cy] coordinates),
604 // with size [width, height]. If any pixels are outside of the image,
605 // they will replicate the values at the borders.
606 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat & input, int cx, int cy, int width, int height)
610 int x1 = cx - width/2;
611 int y1 = cy - height/2;
612 int x2 = cx + width/2;
613 int y2 = cy + height/2;
616 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
617 patch.create(height, width, input.type());
622 int top = 0, bottom = 0, left = 0, right = 0;
624 //fit to image coordinates, set border extensions;
633 if (x2 >= input.cols) {
634 right = x2 - input.cols + width % 2;
639 if (y2 >= input.rows) {
640 bottom = y2 - input.rows + height % 2;
645 if (x2 - x1 == 0 || y2 - y1 == 0)
646 patch = cv::Mat::zeros(height, width, CV_32FC1);
649 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right, cv::BORDER_REPLICATE);
650 // imshow( "copyMakeBorder", patch);
655 assert(patch.cols == width && patch.rows == height);
660 void KCF_Tracker::gaussian_correlation(struct Scale_vars & vars, const ComplexMat & xf, const ComplexMat & yf, double sigma, bool auto_correlation)
663 xf.sqr_norm(vars.xf_sqr_norm_d);
664 if (!auto_correlation)
665 yf.sqr_norm(vars.yf_sqr_norm_d);
667 xf.sqr_norm(vars.xf_sqr_norm);
668 if (auto_correlation){
669 vars.yf_sqr_norm[0] = vars.xf_sqr_norm[0];
671 yf.sqr_norm(vars.yf_sqr_norm);
674 vars.xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
675 DEBUG_PRINTM(vars.xyf);
678 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);
680 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);
682 return fft.forward_raw(vars.gauss_corr_res, xf.n_scales==p_num_scales);
684 //ifft2 and sum over 3rd dimension, we dont care about individual channels
686 DEBUG_PRINTM(vars.ifft2_res);
688 if (xf.channels() != p_num_scales*p_num_of_feats)
689 xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
691 xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
693 for (int y = 0; y < vars.ifft2_res.rows; ++y) {
694 float * row_ptr = vars.ifft2_res.ptr<float>(y);
695 float * row_ptr_sum = xy_sum.ptr<float>(y);
696 for (int x = 0; x < vars.ifft2_res.cols; ++x) {
697 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
698 row_ptr_sum[(x*xy_sum.channels())+sum_ch] += std::accumulate(row_ptr + x*vars.ifft2_res.channels() + sum_ch*(vars.ifft2_res.channels()/xy_sum.channels()),
699 (row_ptr + x*vars.ifft2_res.channels() + (sum_ch+1)*(vars.ifft2_res.channels()/xy_sum.channels())), 0.f);
703 DEBUG_PRINTM(xy_sum);
705 std::vector<cv::Mat> scales;
706 cv::split(xy_sum,scales);
707 vars.in_all = cv::Mat(scales[0].rows * xf.n_scales, scales[0].cols, CV_32F);
709 float numel_xf_inv = 1.f/(xf.cols * xf.rows * (xf.channels()/xf.n_scales));
710 for (int i = 0; i < xf.n_scales; ++i){
711 cv::Mat in_roi(vars.in_all, cv::Rect(0, i*scales[0].rows, scales[0].cols, scales[0].rows));
712 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);
713 DEBUG_PRINTM(in_roi);
716 DEBUG_PRINTM(vars.in_all );
722 float get_response_circular(cv::Point2i & pt, cv::Mat & response)
727 x = response.cols + x;
729 y = response.rows + y;
730 if (x >= response.cols)
731 x = x - response.cols;
732 if (y >= response.rows)
733 y = y - response.rows;
735 return response.at<float>(y,x);
738 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
740 //find neighbourhood of max_loc (response is circular)
744 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);
745 cv::Point2i p4(max_loc.x-1, max_loc.y), p5(max_loc.x+1, max_loc.y);
746 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);
749 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
750 cv::Mat A = (cv::Mat_<float>(9, 6) <<
751 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
752 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
753 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
754 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
755 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
756 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
757 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
758 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
759 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);
760 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
761 get_response_circular(p1, response),
762 get_response_circular(p2, response),
763 get_response_circular(p3, response),
764 get_response_circular(p4, response),
765 get_response_circular(p5, response),
766 get_response_circular(p6, response),
767 get_response_circular(p7, response),
768 get_response_circular(p8, response),
769 get_response_circular(max_loc, response));
772 cv::solve(A, fval, x, cv::DECOMP_SVD);
774 double a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2),
775 d = x.at<float>(3), e = x.at<float>(4);
777 cv::Point2f sub_peak(max_loc.x, max_loc.y);
778 if (b > 0 || b < 0) {
779 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
780 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
786 double KCF_Tracker::sub_grid_scale(int index)
789 if (index < 0 || index > (int)p_scales.size()-1) {
790 // interpolate from all values
791 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
792 A.create(p_scales.size(), 3, CV_32FC1);
793 fval.create(p_scales.size(), 1, CV_32FC1);
794 for (size_t i = 0; i < p_scales.size(); ++i) {
795 A.at<float>(i, 0) = p_scales[i] * p_scales[i];
796 A.at<float>(i, 1) = p_scales[i];
797 A.at<float>(i, 2) = 1;
798 fval.at<float>(i) = scale_vars[i].max_response;
801 //only from neighbours
802 if (index == 0 || index == (int)p_scales.size()-1)
803 return p_scales[index];
805 A = (cv::Mat_<float>(3, 3) <<
806 p_scales[index-1] * p_scales[index-1], p_scales[index-1], 1,
807 p_scales[index] * p_scales[index], p_scales[index], 1,
808 p_scales[index+1] * p_scales[index+1], p_scales[index+1], 1);
809 fval = (cv::Mat_<float>(3, 1) << scale_vars[index-1].max_response, scale_vars[index].max_response, scale_vars[index+1].max_response);
813 cv::solve(A, fval, x, cv::DECOMP_SVD);
814 double a = x.at<float>(0), b = x.at<float>(1);
815 double scale = p_scales[index];
817 scale = -b / (2 * a);