11 #include "fft_cufft.h"
14 #include "fft_opencv.h"
22 #define DEBUG_PRINT(obj) if (m_debug || m_visual_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 CudaSafeCall(cudaFreeHost(xf_sqr_norm));
38 CudaSafeCall(cudaFreeHost(yf_sqr_norm));
39 CudaSafeCall(cudaFree(gauss_corr_res));
46 void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox, int fit_size_x, int fit_size_y)
48 //check boundary, enforce min size
49 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
51 if (x2 > img.cols-1) x2 = img.cols - 1;
53 if (y2 > img.rows-1) y2 = img.rows - 1;
55 if (x2-x1 < 2*p_cell_size) {
56 double diff = (2*p_cell_size -x2+x1)/2.;
57 if (x1 - diff >= 0 && x2 + diff < img.cols){
60 } else if (x1 - 2*diff >= 0) {
66 if (y2-y1 < 2*p_cell_size) {
67 double diff = (2*p_cell_size -y2+y1)/2.;
68 if (y1 - diff >= 0 && y2 + diff < img.rows){
71 } else if (y1 - 2*diff >= 0) {
80 p_pose.cx = x1 + p_pose.w/2.;
81 p_pose.cy = y1 + p_pose.h /2.;
84 cv::Mat input_gray, input_rgb = img.clone();
85 if (img.channels() == 3){
86 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
87 input_gray.convertTo(input_gray, CV_32FC1);
89 img.convertTo(input_gray, CV_32FC1);
91 // don't need too large image
92 if (p_pose.w * p_pose.h > 100.*100. && (fit_size_x == -1 || fit_size_y == -1)) {
93 std::cout << "resizing image by factor of " << 1/p_downscale_factor << std::endl;
94 p_resize_image = true;
95 p_pose.scale(p_downscale_factor);
96 cv::resize(input_gray, input_gray, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
97 cv::resize(input_rgb, input_rgb, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
98 } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
99 if (fit_size_x%p_cell_size != 0 || fit_size_y%p_cell_size != 0) {
100 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;;
101 std::exit(EXIT_FAILURE);
104 if (( tmp = (p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_x)
105 p_scale_factor_x = fit_size_x/tmp;
106 if (( tmp = (p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_y)
107 p_scale_factor_y = fit_size_y/tmp;
108 std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x
109 << " and verticaly by factor of " << p_scale_factor_y << std::endl;
111 p_pose.scale_x(p_scale_factor_x);
112 p_pose.scale_y(p_scale_factor_y);
113 if (p_scale_factor_x != 1 && p_scale_factor_y != 1) {
114 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
115 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
116 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
118 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
119 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
124 //compute win size + fit to fhog cell size
125 p_windows_size[0] = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
126 p_windows_size[1] = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
130 for (int i = -p_num_scales/2; i <= p_num_scales/2; ++i)
131 p_scales.push_back(std::pow(p_scale_step, i));
133 p_scales.push_back(1.);
136 for (int i = p_angle_min; i <=p_angle_max ; i += p_angle_step)
137 p_angles.push_back(i);
139 p_angles.push_back(0);
143 if (p_windows_size[1]/p_cell_size*(p_windows_size[0]/p_cell_size/2+1) > 1024) {
144 std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
145 "the window dimensions so its size is less or equal to " << 1024*p_cell_size*p_cell_size*2+1 <<
146 " pixels . Currently the size of the window is: " << p_windows_size[0] << "x" << p_windows_size[1] <<
147 " which is " << p_windows_size[0]*p_windows_size[1] << " pixels. " << std::endl;
148 std::exit(EXIT_FAILURE);
151 if (m_use_linearkernel){
152 std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
153 std::exit(EXIT_FAILURE);
155 cudaSetDeviceFlags(cudaDeviceMapHost);
156 CudaSafeCall(cudaHostAlloc((void**)&xf_sqr_norm, p_num_scales*sizeof(float), cudaHostAllocMapped));
157 CudaSafeCall(cudaHostGetDevicePointer((void**)&xf_sqr_norm_d, (void*)xf_sqr_norm, 0));
159 CudaSafeCall(cudaHostAlloc((void**)&yf_sqr_norm, sizeof(float), cudaHostAllocMapped));
160 CudaSafeCall(cudaHostGetDevicePointer((void**)&yf_sqr_norm_d, (void*)yf_sqr_norm, 0));
162 xf_sqr_norm = (float*) malloc(p_num_scales*sizeof(float));
163 yf_sqr_norm = (float*) malloc(sizeof(float));
166 p_current_scale = 1.;
168 double min_size_ratio = std::max(5.*p_cell_size/p_windows_size[0], 5.*p_cell_size/p_windows_size[1]);
169 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]);
170 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
171 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
173 std::cout << "init: img size " << img.cols << " " << img.rows << std::endl;
174 std::cout << "init: win size. " << p_windows_size[0] << " " << p_windows_size[1] << std::endl;
175 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
177 p_output_sigma = std::sqrt(p_pose.w*p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
179 //window weights, i.e. labels
181 if(m_use_color) p_num_of_feats += 3;
182 if(m_use_cnfeat) p_num_of_feats += 10;
183 p_roi_width = p_windows_size[0]/p_cell_size;
184 p_roi_height = p_windows_size[1]/p_cell_size;
186 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);
187 p_yf = fft.forward(gaussian_shaped_labels(p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
188 fft.set_window(cosine_window_function(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
191 CudaSafeCall(cudaMalloc((void**)&gauss_corr_res, (p_windows_size[0]/p_cell_size)*(p_windows_size[1]/p_cell_size)*p_num_scales*sizeof(float)));
193 //obtain a sub-window for training initial model
194 int size_x_scaled = floor(p_windows_size[0]);
195 int size_y_scaled = floor(p_windows_size[1]);
197 cv::Mat patch_gray = get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
198 geometric_transformations(patch_gray, p_windows_size[0], p_windows_size[1], 1, 0, false);
200 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
201 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
202 patch_rgb = get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
203 geometric_transformations(patch_rgb, p_windows_size[0], p_windows_size[1], 1, 0, false);
205 std::vector<cv::Mat> path_feat = get_features(patch_rgb, patch_gray);
206 p_model_xf = fft.forward_window(path_feat);
207 DEBUG_PRINTM(p_model_xf);
209 if (m_use_linearkernel) {
210 ComplexMat xfconj = p_model_xf.conj();
211 p_model_alphaf_num = xfconj.mul(p_yf);
212 p_model_alphaf_den = (p_model_xf * xfconj);
214 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
215 ComplexMat kf = gaussian_correlation(p_model_xf, p_model_xf, p_kernel_sigma, true);
217 p_model_alphaf_num = p_yf * kf;
218 DEBUG_PRINTM(p_model_alphaf_num);
219 p_model_alphaf_den = kf * (kf + p_lambda);
220 DEBUG_PRINTM(p_model_alphaf_den);
222 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
223 DEBUG_PRINTM(p_model_alphaf);
224 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
227 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img, int fit_size_x, int fit_size_y)
229 init(img, bbox.get_rect(), fit_size_x, fit_size_y);
232 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
234 if (p_resize_image) {
236 tmp.scale(p_downscale_factor);
239 } else if (p_fit_to_pw2) {
241 tmp.scale_x(p_scale_factor_x);
242 tmp.scale_y(p_scale_factor_y);
251 BBox_c KCF_Tracker::getBBox()
254 tmp.w *= p_current_scale;
255 tmp.h *= p_current_scale;
256 tmp.a = p_current_angle;
259 tmp.scale(1/p_downscale_factor);
261 tmp.scale_x(1/p_scale_factor_x);
262 tmp.scale_y(1/p_scale_factor_y);
268 void KCF_Tracker::track(cv::Mat &img)
270 if (m_debug || m_visual_debug)
271 std::cout << "\nNEW FRAME" << std::endl;
272 cv::Mat input_gray, input_rgb = img.clone();
273 if (img.channels() == 3){
274 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
275 input_gray.convertTo(input_gray, CV_32FC1);
277 img.convertTo(input_gray, CV_32FC1);
279 // don't need too large image
280 if (p_resize_image) {
281 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
282 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
283 } else if (p_fit_to_pw2 && p_scale_factor_x != 1 && p_scale_factor_y != 1) {
284 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
285 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
286 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
288 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
289 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
294 std::vector<cv::Mat> patch_feat;
295 double max_response = -1.;
296 cv::Mat max_response_map;
297 cv::Point2i max_response_pt;
300 std::vector<double> scale_responses;
302 if (m_use_multithreading){
303 std::vector<std::future<cv::Mat>> async_res(p_scales.size());
304 for (size_t i = 0; i < p_scales.size(); ++i) {
305 async_res[i] = std::async(std::launch::async,
306 [this, &input_gray, &input_rgb, i]() -> cv::Mat
308 int size_x_scaled = floor(p_windows_size[0]*p_current_scale * this->p_scales[i]);
309 int size_y_scaled = floor(p_windows_size[1]*p_current_scale * this->p_scales[i]);
311 cv::Mat patch_gray = get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
312 geometric_transformations(patch_gray, p_windows_size[0], p_windows_size[1], p_current_scale * this->p_scales[i]);
314 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
315 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
316 patch_rgb = get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
317 geometric_transformations(patch_rgb, p_windows_size[0], p_windows_size[1], p_current_scale * this->p_scales[i]);
320 std::vector<cv::Mat> patch_feat_async = get_features(patch_rgb, patch_gray);
321 ComplexMat zf = fft.forward_window(patch_feat_async);
322 if (m_use_linearkernel)
323 return fft.inverse((p_model_alphaf * zf).sum_over_channels());
325 ComplexMat kzf = gaussian_correlation(zf, this->p_model_xf, this->p_kernel_sigma);
326 return fft.inverse(this->p_model_alphaf * kzf);
331 for (size_t i = 0; i < p_scales.size(); ++i) {
334 cv::Mat response = async_res[i].get();
336 double min_val, max_val;
337 cv::Point2i min_loc, max_loc;
338 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
340 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
341 if (max_val*weight > max_response) {
342 max_response = max_val*weight;
343 max_response_map = response;
344 max_response_pt = max_loc;
347 scale_responses.push_back(max_val*weight);
349 } else if (m_use_big_batch){
350 #pragma omp parallel for ordered
351 for (size_t i = 0; i < p_scales.size(); ++i) {
352 int size_x_scaled = floor(p_windows_size[0]*p_current_scale * this->p_scales[i]);
353 int size_y_scaled = floor(p_windows_size[1]*p_current_scale * this->p_scales[i]);
355 cv::Mat patch_gray = get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
356 geometric_transformations(patch_gray, p_windows_size[0], p_windows_size[1], p_current_scale * this->p_scales[i]);
358 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
359 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
360 patch_rgb = get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
361 geometric_transformations(patch_rgb, p_windows_size[0], p_windows_size[1], p_current_scale * this->p_scales[i]);
363 std::vector<cv::Mat> tmp = get_features(input_rgb, input_gray);
365 patch_feat.insert(std::end(patch_feat), std::begin(tmp), std::end(tmp));
367 ComplexMat zf = fft.forward_window(patch_feat);
371 if (m_use_linearkernel)
372 response = fft.inverse((zf.mul2(p_model_alphaf)).sum_over_channels());
374 ComplexMat kzf = gaussian_correlation(zf, p_model_xf, p_kernel_sigma);
375 DEBUG_PRINTM(p_model_alphaf);
377 response = fft.inverse(kzf.mul(p_model_alphaf));
379 DEBUG_PRINTM(response);
380 std::vector<cv::Mat> scales;
381 cv::split(response,scales);
383 /* target location is at the maximum response. we must take into
384 account the fact that, if the target doesn't move, the peak
385 will appear at the top-left corner, not at the center (this is
386 discussed in the paper). the responses wrap around cyclically. */
387 for (size_t i = 0; i < p_scales.size(); ++i) {
388 double min_val, max_val;
389 cv::Point2i min_loc, max_loc;
390 cv::minMaxLoc(scales[i], &min_val, &max_val, &min_loc, &max_loc);
391 DEBUG_PRINT(max_loc);
393 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
395 if (max_val*weight > max_response) {
396 max_response = max_val*weight;
397 max_response_map = scales[i];
398 max_response_pt = max_loc;
401 scale_responses.push_back(max_val*weight);
404 #pragma omp parallel for ordered private(patch_feat) schedule(dynamic)
405 for (size_t i = 0; i < p_scales.size(); ++i) {
406 for (size_t j = 0; j < p_angles.size(); ++j) {
407 int size_x_scaled = floor(p_windows_size[0]*p_current_scale * p_scales[i]);
408 int size_y_scaled = floor(p_windows_size[1]*p_current_scale * p_scales[i]);
410 cv::Mat patch_gray = get_subwindow(input_gray, p_pose.cx, p_pose.cy, size_x_scaled, size_y_scaled);
411 geometric_transformations(patch_gray, p_windows_size[0], p_windows_size[1], p_current_scale * p_scales[i], p_current_angle + p_angles[j]);
413 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
414 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
415 patch_rgb = get_subwindow(input_rgb, p_pose.cx, p_pose.cy, size_x_scaled, size_y_scaled);
416 geometric_transformations(patch_rgb, p_windows_size[0], p_windows_size[1], p_current_scale * p_scales[i], p_current_angle + p_angles[j]);
419 patch_feat = get_features(patch_rgb, patch_gray);
420 ComplexMat zf = fft.forward_window(patch_feat);
423 if (m_use_linearkernel)
424 response = fft.inverse((p_model_alphaf * zf).sum_over_channels());
426 ComplexMat kzf = gaussian_correlation(zf, p_model_xf, p_kernel_sigma);
427 DEBUG_PRINTM(p_model_alphaf);
429 DEBUG_PRINTM(p_model_alphaf * kzf);
430 response = fft.inverse(p_model_alphaf * kzf);
432 DEBUG_PRINTM(response);
434 /* target location is at the maximum response. we must take into
435 account the fact that, if the target doesn't move, the peak
436 will appear at the top-left corner, not at the center (this is
437 discussed in the paper). the responses wrap around cyclically. */
438 double min_val, max_val;
439 cv::Point2i min_loc, max_loc;
440 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
441 DEBUG_PRINT(max_loc);
443 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
445 std::string scale = std::to_string(p_scales[i]);
446 scale.erase ( scale.find_last_not_of('0') + 1, std::string::npos );
447 scale.erase ( scale.find_last_not_of('.') + 1, std::string::npos );
449 std::string angle = std::to_string(p_current_angle + p_angles[j]);
450 angle.erase ( angle.find_last_not_of('0') + 1, std::string::npos );
451 angle.erase ( angle.find_last_not_of('.') + 1, std::string::npos );
452 std::cout << "Max value for scale: " << scale << " and angle:" << angle << " is: " << std::to_string(max_val*weight) << std::endl;
453 cv::Mat copy_response = response.clone();
455 // crop the spectrum, if it has an odd number of rows or columns
456 copy_response = copy_response(cv::Rect(0, 0, copy_response.cols & -2, copy_response.rows & -2));
458 // rearrange the quadrants of Fourier image so that the origin is at the image center
459 int cx = copy_response.cols/2;
460 int cy = copy_response.rows/2;
462 cv::Mat q0(copy_response, cv::Rect(0, 0, cx, cy)); // Top-Left - Create a ROI per quadrant
463 cv::Mat q1(copy_response, cv::Rect(cx, 0, cx, cy)); // Top-Right
464 cv::Mat q2(copy_response, cv::Rect(0, cy, cx, cy)); // Bottom-Left
465 cv::Mat q3(copy_response, cv::Rect(cx, cy, cx, cy)); // Bottom-Right
467 cv::Mat tmp; // swap quadrants (Top-Left with Bottom-Right)
472 q1.copyTo(tmp); // swap quadrant (Top-Right with Bottom-Left)
476 cv::resize(copy_response, copy_response, cv::Size(p_debug_image_size, p_debug_image_size), 0., 0., cv::INTER_LINEAR);
477 cv::putText(copy_response, angle, cv::Point(0, copy_response.rows-1), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.5, cv::Scalar(255,255,255),1,cv::LINE_AA);
478 if ((p_count-1)%5 == 0)
479 cv::putText(copy_response, scale, cv::Point(0, 10), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.5, cv::Scalar(255,255,255),1,cv::LINE_AA);
481 p_debug_scale_responses.push_back(copy_response);
485 if (max_val*weight > max_response) {
486 max_response = max_val*weight;
487 max_response_map = response;
488 max_response_pt = max_loc;
494 scale_responses.push_back(max_val*weight);
498 cv::Mat all_responses(cv::Size(p_angles.size()*p_debug_image_size, p_scales.size()*p_debug_image_size), p_debug_scale_responses[0].type(), cv::Scalar::all(0));
499 cv::Mat all_subwindows(cv::Size(p_angles.size()*p_debug_image_size, p_scales.size()*p_debug_image_size), p_debug_subwindows[0].type(), cv::Scalar::all(0));
500 for (size_t i = 0; i < p_scales.size(); ++i) {
501 for (size_t j = 0; j < p_angles.size(); ++j) {
502 cv::Mat in_roi(all_responses, cv::Rect(j*p_debug_image_size, i*p_debug_image_size, p_debug_image_size, p_debug_image_size));
503 p_debug_scale_responses[5*i+j].copyTo(in_roi);
504 in_roi = all_subwindows(cv::Rect(j*p_debug_image_size, i*p_debug_image_size, p_debug_image_size, p_debug_image_size));
505 p_debug_subwindows[5*i+j].copyTo(in_roi);
508 cv::namedWindow("All subwindows", CV_WINDOW_AUTOSIZE);
509 cv::imshow("All subwindows", all_subwindows);
510 cv::namedWindow("All responses", CV_WINDOW_AUTOSIZE);
511 cv::imshow("All responses", all_responses);
513 p_debug_scale_responses.clear();
514 p_debug_subwindows.clear();
517 DEBUG_PRINTM(max_response_map);
518 DEBUG_PRINT(max_response_pt);
520 //sub pixel quadratic interpolation from neighbours
521 if (max_response_pt.y > max_response_map.rows / 2) //wrap around to negative half-space of vertical axis
522 max_response_pt.y = max_response_pt.y - max_response_map.rows;
523 if (max_response_pt.x > max_response_map.cols / 2) //same for horizontal axis
524 max_response_pt.x = max_response_pt.x - max_response_map.cols;
526 cv::Point2f new_location(max_response_pt.x, max_response_pt.y);
527 DEBUG_PRINT(new_location);
529 if (m_use_subpixel_localization)
530 new_location = sub_pixel_peak(max_response_pt, max_response_map);
531 DEBUG_PRINT(new_location);
534 std::cout << "Old p_pose, cx: " << p_pose.cx << " cy: " << p_pose.cy << std::endl;
536 p_pose.cx += p_current_scale*p_cell_size*new_location.x;
537 p_pose.cy += p_current_scale*p_cell_size*new_location.y;
540 std::cout << "New p_pose, cx: " << p_pose.cx << " cy: " << p_pose.cy << std::endl;
543 if (p_pose.cx < 0) p_pose.cx = 0;
544 if (p_pose.cx > (img.cols*p_scale_factor_x)-1) p_pose.cx = (img.cols*p_scale_factor_x)-1;
545 if (p_pose.cy < 0) p_pose.cy = 0;
546 if (p_pose.cy > (img.rows*p_scale_factor_y)-1) p_pose.cy = (img.rows*p_scale_factor_y)-1;
548 if (p_pose.cx < 0) p_pose.cx = 0;
549 if (p_pose.cx > img.cols-1) p_pose.cx = img.cols-1;
550 if (p_pose.cy < 0) p_pose.cy = 0;
551 if (p_pose.cy > img.rows-1) p_pose.cy = img.rows-1;
554 //sub grid scale interpolation
555 double new_scale = p_scales[scale_index];
556 if (m_use_subgrid_scale)
557 new_scale = sub_grid_scale(scale_responses, scale_index);
559 p_current_scale *= new_scale;
561 if (p_current_scale < p_min_max_scale[0])
562 p_current_scale = p_min_max_scale[0];
563 if (p_current_scale > p_min_max_scale[1])
564 p_current_scale = p_min_max_scale[1];
566 int tmp_angle = p_current_angle + p_angles[angle_index];
567 p_current_angle = tmp_angle < 0 ? -std::abs(tmp_angle)%360 : tmp_angle%360;
569 //obtain a subwindow for training at newly estimated target position
570 int size_x_scaled = floor(p_windows_size[0]*p_current_scale);
571 int size_y_scaled = floor(p_windows_size[1]*p_current_scale);
573 cv::Mat patch_gray = get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
574 geometric_transformations(patch_gray, p_windows_size[0], p_windows_size[1], p_current_scale, p_current_angle, false);
576 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
577 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
578 patch_rgb = get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
579 geometric_transformations(patch_rgb, p_windows_size[0], p_windows_size[1], p_current_scale, p_current_angle, false);
581 patch_feat = get_features(patch_rgb, patch_gray);
582 ComplexMat xf = fft.forward_window(patch_feat);
584 //subsequent frames, interpolate model
585 p_model_xf = p_model_xf * (1. - p_interp_factor) + xf * p_interp_factor;
587 ComplexMat alphaf_num, alphaf_den;
589 if (m_use_linearkernel) {
590 ComplexMat xfconj = xf.conj();
591 alphaf_num = xfconj.mul(p_yf);
592 alphaf_den = (xf * xfconj);
594 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
595 ComplexMat kf = gaussian_correlation(xf, xf, p_kernel_sigma, true);
596 // ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
597 // p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
598 alphaf_num = p_yf * kf;
599 alphaf_den = kf * (kf + p_lambda);
602 p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
603 p_model_alphaf_den = p_model_alphaf_den * (1. - p_interp_factor) + alphaf_den * p_interp_factor;
604 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
607 // ****************************************************************************
609 std::vector<cv::Mat> KCF_Tracker::get_features(cv::Mat & patch_rgb, cv::Mat & patch_gray)
612 // get hog(Histogram of Oriented Gradients) features
613 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
615 //get color rgb features (simple r,g,b channels)
616 std::vector<cv::Mat> color_feat;
618 if (m_use_color && patch_rgb.channels() == 3) {
619 //use rgb color space
620 cv::Mat patch_rgb_norm;
621 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
622 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
623 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
624 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
625 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
626 cv::split(patch_rgb_norm, rgb);
627 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
630 if (m_use_cnfeat && patch_rgb.channels() == 3) {
631 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
632 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
635 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
639 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
641 cv::Mat labels(dim2, dim1, CV_32FC1);
642 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
643 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
645 double sigma_s = sigma*sigma;
647 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j){
648 float * row_ptr = labels.ptr<float>(j);
650 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i){
651 row_ptr[i] = std::exp(-0.5 * (y_s + x*x) / sigma_s);//-1/2*e^((y^2+x^2)/sigma^2)
655 //rotate so that 1 is at top-left corner (see KCF paper for explanation)
656 cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
657 //sanity check, 1 at top left corner
658 assert(rot_labels.at<float>(0,0) >= 1.f - 1e-10f);
663 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
665 cv::Mat rot_patch(patch.size(), CV_32FC1);
666 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
668 //circular rotate x-axis
670 //move part that does not rotate over the edge
671 cv::Range orig_range(-x_rot, patch.cols);
672 cv::Range rot_range(0, patch.cols - (-x_rot));
673 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
676 orig_range = cv::Range(0, -x_rot);
677 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
678 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
679 }else if (x_rot > 0){
680 //move part that does not rotate over the edge
681 cv::Range orig_range(0, patch.cols - x_rot);
682 cv::Range rot_range(x_rot, patch.cols);
683 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
686 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
687 rot_range = cv::Range(0, x_rot);
688 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
689 }else { //zero rotation
690 //move part that does not rotate over the edge
691 cv::Range orig_range(0, patch.cols);
692 cv::Range rot_range(0, patch.cols);
693 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
696 //circular rotate y-axis
698 //move part that does not rotate over the edge
699 cv::Range orig_range(-y_rot, patch.rows);
700 cv::Range rot_range(0, patch.rows - (-y_rot));
701 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
704 orig_range = cv::Range(0, -y_rot);
705 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
706 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
707 }else if (y_rot > 0){
708 //move part that does not rotate over the edge
709 cv::Range orig_range(0, patch.rows - y_rot);
710 cv::Range rot_range(y_rot, patch.rows);
711 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
714 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
715 rot_range = cv::Range(0, y_rot);
716 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
717 }else { //zero rotation
718 //move part that does not rotate over the edge
719 cv::Range orig_range(0, patch.rows);
720 cv::Range rot_range(0, patch.rows);
721 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
727 //hann window actually (Power-of-cosine windows)
728 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
730 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
731 double N_inv = 1./(static_cast<double>(dim1)-1.);
732 for (int i = 0; i < dim1; ++i)
733 m1.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
734 N_inv = 1./(static_cast<double>(dim2)-1.);
735 for (int i = 0; i < dim2; ++i)
736 m2.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
741 // Returns sub-window of image input centered at [cx, cy] coordinates),
742 // with size [width, height]. If any pixels are outside of the image,
743 // they will replicate the values at the borders.
744 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
748 int x1 = cx - width/2;
749 int y1 = cy - height/2;
750 int x2 = cx + width/2;
751 int y2 = cy + height/2;
754 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
755 patch.create(height, width, input.type());
760 int top = 0, bottom = 0, left = 0, right = 0;
762 //fit to image coordinates, set border extensions;
771 if (x2 >= input.cols) {
772 right = x2 - input.cols + width % 2;
777 if (y2 >= input.rows) {
778 bottom = y2 - input.rows + height % 2;
783 if (x2 - x1 == 0 || y2 - y1 == 0)
784 patch = cv::Mat::zeros(height, width, CV_32FC1);
786 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right, cv::BORDER_REPLICATE);
789 assert(patch.cols == width && patch.rows == height);
794 void KCF_Tracker::geometric_transformations(cv::Mat& patch, int size_x, int size_y, double scale,int angle, bool allow_debug)
797 cv::Point2f center((patch.cols-1)/2., (patch.rows-1)/2.);
798 cv::Mat r = cv::getRotationMatrix2D(center, angle, 1.0);
800 cv::warpAffine(patch, patch, r, cv::Size(patch.cols, patch.rows), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
803 //resize to default size
804 if (patch.channels() != 3){
806 //if we downsample use INTER_AREA interpolation
807 cv::resize(patch, patch, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
809 cv::resize(patch, patch, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
813 //if we downsample use INTER_AREA interpolation
814 cv::resize(patch, patch, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_AREA);
816 cv::resize(patch, patch, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_LINEAR);
818 if (m_visual_debug && allow_debug) {
819 cv::Mat input_clone = patch.clone();
820 cv::resize(input_clone, input_clone, cv::Size(p_debug_image_size, p_debug_image_size), 0., 0., cv::INTER_LINEAR);
822 std::string angle_string = std::to_string(p_current_angle + angle);
823 if (p_count%5 == 0) {
824 std::string scale_string = std::to_string(scale);
825 scale_string.erase ( scale_string.find_last_not_of('0') + 1, std::string::npos );
826 scale_string.erase ( scale_string.find_last_not_of('.') + 1, std::string::npos );
827 cv::putText(input_clone, scale_string, cv::Point(0, 10), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.5, cv::Scalar(0,255,0),1,cv::LINE_AA);
830 cv::putText(input_clone, angle_string, cv::Point(1, input_clone.rows-5), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.5, cv::Scalar(0,255,0),1,cv::LINE_AA);
832 p_debug_subwindows.push_back(input_clone);
838 ComplexMat KCF_Tracker::gaussian_correlation(const ComplexMat &xf, const ComplexMat &yf, double sigma, bool auto_correlation)
841 xf.sqr_norm(xf_sqr_norm_d);
842 if (!auto_correlation)
843 yf.sqr_norm(yf_sqr_norm_d);
845 xf.sqr_norm(xf_sqr_norm);
846 if (auto_correlation){
847 yf_sqr_norm[0] = xf_sqr_norm[0];
849 yf.sqr_norm(yf_sqr_norm);
853 xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
857 cuda_gaussian_correlation(fft.inverse_raw(xyf), gauss_corr_res, xf_sqr_norm_d, xf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
859 cuda_gaussian_correlation(fft.inverse_raw(xyf), gauss_corr_res, xf_sqr_norm_d, yf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
861 return fft.forward_raw(gauss_corr_res, xf.n_scales==p_num_scales);
863 //ifft2 and sum over 3rd dimension, we dont care about individual channels
864 cv::Mat ifft2_res = fft.inverse(xyf);
865 DEBUG_PRINTM(ifft2_res);
867 if (xf.channels() != p_num_scales*p_num_of_feats)
868 xy_sum.create(ifft2_res.size(), CV_32FC1);
870 xy_sum.create(ifft2_res.size(), CV_32FC(p_scales.size()));
872 for (int y = 0; y < ifft2_res.rows; ++y) {
873 float * row_ptr = ifft2_res.ptr<float>(y);
874 float * row_ptr_sum = xy_sum.ptr<float>(y);
875 for (int x = 0; x < ifft2_res.cols; ++x) {
876 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
877 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);
881 DEBUG_PRINTM(xy_sum);
883 std::vector<cv::Mat> scales;
884 cv::split(xy_sum,scales);
885 cv::Mat in_all(scales[0].rows * xf.n_scales, scales[0].cols, CV_32F);
887 float numel_xf_inv = 1.f/(xf.cols * xf.rows * (xf.channels()/xf.n_scales));
888 for (int i = 0; i < xf.n_scales; ++i){
889 cv::Mat in_roi(in_all, cv::Rect(0, i*scales[0].rows, scales[0].cols, scales[0].rows));
890 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);
891 DEBUG_PRINTM(in_roi);
894 DEBUG_PRINTM(in_all);
895 return fft.forward(in_all);
899 float get_response_circular(cv::Point2i & pt, cv::Mat & response)
904 x = response.cols + x;
906 y = response.rows + y;
907 if (x >= response.cols)
908 x = x - response.cols;
909 if (y >= response.rows)
910 y = y - response.rows;
912 return response.at<float>(y,x);
915 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
917 //find neighbourhood of max_loc (response is circular)
921 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);
922 cv::Point2i p4(max_loc.x-1, max_loc.y), p5(max_loc.x+1, max_loc.y);
923 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);
926 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
927 cv::Mat A = (cv::Mat_<float>(9, 6) <<
928 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
929 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
930 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
931 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
932 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
933 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
934 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
935 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
936 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);
937 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
938 get_response_circular(p1, response),
939 get_response_circular(p2, response),
940 get_response_circular(p3, response),
941 get_response_circular(p4, response),
942 get_response_circular(p5, response),
943 get_response_circular(p6, response),
944 get_response_circular(p7, response),
945 get_response_circular(p8, response),
946 get_response_circular(max_loc, response));
949 cv::solve(A, fval, x, cv::DECOMP_SVD);
951 double a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2),
952 d = x.at<float>(3), e = x.at<float>(4);
954 cv::Point2f sub_peak(max_loc.x, max_loc.y);
955 if (b > 0 || b < 0) {
956 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
957 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
963 double KCF_Tracker::sub_grid_scale(std::vector<double> & responses, int index)
966 if (index < 0 || index > (int)p_scales.size()-1) {
967 // interpolate from all values
968 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
969 A.create(p_scales.size(), 3, CV_32FC1);
970 fval.create(p_scales.size(), 1, CV_32FC1);
971 for (size_t i = 0; i < p_scales.size(); ++i) {
972 A.at<float>(i, 0) = p_scales[i] * p_scales[i];
973 A.at<float>(i, 1) = p_scales[i];
974 A.at<float>(i, 2) = 1;
975 fval.at<float>(i) = responses[i];
978 //only from neighbours
979 if (index == 0 || index == (int)p_scales.size()-1)
980 return p_scales[index];
982 A = (cv::Mat_<float>(3, 3) <<
983 p_scales[index-1] * p_scales[index-1], p_scales[index-1], 1,
984 p_scales[index] * p_scales[index], p_scales[index], 1,
985 p_scales[index+1] * p_scales[index+1], p_scales[index+1], 1);
986 fval = (cv::Mat_<float>(3, 1) << responses[index-1], responses[index], responses[index+1]);
990 cv::solve(A, fval, x, cv::DECOMP_SVD);
991 double a = x.at<float>(0), b = x.at<float>(1);
992 double scale = p_scales[index];
994 scale = -b / (2 * a);