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()
38 void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
40 //check boundary, enforce min size
41 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
43 if (x2 > img.cols-1) x2 = img.cols - 1;
45 if (y2 > img.rows-1) y2 = img.rows - 1;
47 if (x2-x1 < 2*p_cell_size) {
48 double diff = (2*p_cell_size -x2+x1)/2.;
49 if (x1 - diff >= 0 && x2 + diff < img.cols){
52 } else if (x1 - 2*diff >= 0) {
58 if (y2-y1 < 2*p_cell_size) {
59 double diff = (2*p_cell_size -y2+y1)/2.;
60 if (y1 - diff >= 0 && y2 + diff < img.rows){
63 } else if (y1 - 2*diff >= 0) {
72 p_pose.cx = x1 + p_pose.w/2.;
73 p_pose.cy = y1 + p_pose.h/2.;
76 cv::Mat input_gray, input_rgb = img.clone();
77 if (img.channels() == 3){
78 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
79 input_gray.convertTo(input_gray, CV_32FC1);
81 img.convertTo(input_gray, CV_32FC1);
83 // don't need too large image
84 if (p_pose.w * p_pose.h > 100.*100.) {
85 std::cout << "resizing image by factor of " << 1/p_downscale_factor << std::endl;
86 p_resize_image = true;
87 p_pose.scale(p_downscale_factor);
88 cv::resize(input_gray, input_gray, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
89 cv::resize(input_rgb, input_rgb, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
92 //compute win size + fit to fhog cell size
93 p_windows_size[0] = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
94 p_windows_size[1] = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
98 for (int i = -p_num_scales/2; i <= p_num_scales/2; ++i)
99 p_scales.push_back(std::pow(p_scale_step, i));
101 p_scales.push_back(1.);
103 p_current_scale = 1.;
105 double min_size_ratio = std::max(5.*p_cell_size/p_windows_size[0], 5.*p_cell_size/p_windows_size[1]);
106 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]);
107 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
108 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
110 std::cout << "init: img size " << img.cols << " " << img.rows << std::endl;
111 std::cout << "init: win size. " << p_windows_size[0] << " " << p_windows_size[1] << std::endl;
112 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
114 p_output_sigma = std::sqrt(p_pose.w*p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
116 //window weights, i.e. labels
118 if(m_use_color) num_of_feats += 3;
119 if(m_use_cnfeat) num_of_feats += 10;
120 fft.init(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size, num_of_feats, p_scales.size(), m_use_big_batch);
121 p_yf = fft.forward(gaussian_shaped_labels(p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
122 fft.set_window(cosine_window_function(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
124 //obtain a sub-window for training initial model
125 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]);
126 p_model_xf = fft.forward_window(path_feat);
127 DEBUG_PRINTM(p_model_xf);
129 if (m_use_linearkernel) {
130 ComplexMat xfconj = p_model_xf.conj();
131 p_model_alphaf_num = xfconj.mul(p_yf);
132 p_model_alphaf_den = (p_model_xf * xfconj);
134 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
135 ComplexMat kf = gaussian_correlation(p_model_xf, p_model_xf, p_kernel_sigma, true);
137 p_model_alphaf_num = p_yf * kf;
138 DEBUG_PRINTM(p_model_alphaf_num);
139 p_model_alphaf_den = kf * (kf + p_lambda);
140 DEBUG_PRINTM(p_model_alphaf_den);
142 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
143 DEBUG_PRINTM(p_model_alphaf);
144 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
147 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img)
149 init(img, bbox.get_rect());
152 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
154 if (p_resize_image) {
156 tmp.scale(p_downscale_factor);
165 BBox_c KCF_Tracker::getBBox()
168 tmp.w *= p_current_scale;
169 tmp.h *= p_current_scale;
172 tmp.scale(1/p_downscale_factor);
177 void KCF_Tracker::track(cv::Mat &img)
180 std::cout << "NEW FRAME" << '\n';
181 cv::Mat input_gray, input_rgb = img.clone();
182 if (img.channels() == 3){
183 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
184 input_gray.convertTo(input_gray, CV_32FC1);
186 img.convertTo(input_gray, CV_32FC1);
188 // don't need too large image
189 if (p_resize_image) {
190 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
191 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
195 std::vector<cv::Mat> patch_feat;
196 double max_response = -1.;
197 cv::Mat max_response_map;
198 cv::Point2i max_response_pt;
200 std::vector<double> scale_responses;
202 if (m_use_multithreading){
203 std::vector<std::future<cv::Mat>> async_res(p_scales.size());
204 for (size_t i = 0; i < p_scales.size(); ++i) {
205 async_res[i] = std::async(std::launch::async,
206 [this, &input_gray, &input_rgb, i]() -> cv::Mat
208 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],
209 this->p_windows_size[1], this->p_current_scale * this->p_scales[i]);
210 ComplexMat zf = fft.forward_window(patch_feat_async);
211 if (m_use_linearkernel)
212 return fft.inverse((p_model_alphaf * zf).sum_over_channels());
214 ComplexMat kzf = gaussian_correlation(zf, this->p_model_xf, this->p_kernel_sigma);
215 return fft.inverse(this->p_model_alphaf * kzf);
220 for (size_t i = 0; i < p_scales.size(); ++i) {
223 cv::Mat response = async_res[i].get();
225 double min_val, max_val;
226 cv::Point2i min_loc, max_loc;
227 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
229 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
230 if (max_val*weight > max_response) {
231 max_response = max_val*weight;
232 max_response_map = response;
233 max_response_pt = max_loc;
236 scale_responses.push_back(max_val*weight);
238 } else if(m_use_big_batch){
239 #pragma omp parallel for ordered
240 for (size_t i = 0; i < p_scales.size(); ++i) {
241 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]);
243 patch_feat.insert(std::end(patch_feat), std::begin(tmp), std::end(tmp));
245 ComplexMat zf = fft.forward_window(patch_feat);
249 if (m_use_linearkernel)
250 response = fft.inverse((zf.mul2(p_model_alphaf)).sum_over_channels());
252 ComplexMat kzf = gaussian_correlation(zf, p_model_xf, p_kernel_sigma);
253 DEBUG_PRINTM(p_model_alphaf);
255 response = fft.inverse(kzf.mul(p_model_alphaf));
257 DEBUG_PRINTM(response);
258 std::vector<cv::Mat> scales;
259 cv::split(response,scales);
261 /* target location is at the maximum response. we must take into
262 account the fact that, if the target doesn't move, the peak
263 will appear at the top-left corner, not at the center (this is
264 discussed in the paper). the responses wrap around cyclically. */
265 for (size_t i = 0; i < p_scales.size(); ++i) {
266 double min_val, max_val;
267 cv::Point2i min_loc, max_loc;
268 cv::minMaxLoc(scales[i], &min_val, &max_val, &min_loc, &max_loc);
269 DEBUG_PRINT(max_loc);
271 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
273 if (max_val*weight > max_response) {
274 max_response = max_val*weight;
275 max_response_map = scales[i];
276 max_response_pt = max_loc;
279 scale_responses.push_back(max_val*weight);
282 #pragma omp parallel for ordered private(patch_feat) schedule(dynamic)
283 for (size_t i = 0; i < p_scales.size(); ++i) {
284 patch_feat = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], p_current_scale * p_scales[i]);
285 ComplexMat zf = fft.forward_window(patch_feat);
288 if (m_use_linearkernel)
289 response = fft.inverse((p_model_alphaf * zf).sum_over_channels());
291 ComplexMat kzf = gaussian_correlation(zf, p_model_xf, p_kernel_sigma);
292 DEBUG_PRINTM(p_model_alphaf);
294 DEBUG_PRINTM(p_model_alphaf * kzf);
295 response = fft.inverse(p_model_alphaf * kzf);
297 DEBUG_PRINTM(response);
299 /* target location is at the maximum response. we must take into
300 account the fact that, if the target doesn't move, the peak
301 will appear at the top-left corner, not at the center (this is
302 discussed in the paper). the responses wrap around cyclically. */
303 double min_val, max_val;
304 cv::Point2i min_loc, max_loc;
305 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
306 DEBUG_PRINT(max_loc);
308 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
311 if (max_val*weight > max_response) {
312 max_response = max_val*weight;
313 max_response_map = response;
314 max_response_pt = max_loc;
319 scale_responses.push_back(max_val*weight);
322 DEBUG_PRINTM(max_response_map);
323 DEBUG_PRINT(max_response_pt);
324 //sub pixel quadratic interpolation from neighbours
325 if (max_response_pt.y > max_response_map.rows / 2) //wrap around to negative half-space of vertical axis
326 max_response_pt.y = max_response_pt.y - max_response_map.rows;
327 if (max_response_pt.x > max_response_map.cols / 2) //same for horizontal axis
328 max_response_pt.x = max_response_pt.x - max_response_map.cols;
330 cv::Point2f new_location(max_response_pt.x, max_response_pt.y);
331 DEBUG_PRINT(new_location);
333 if (m_use_subpixel_localization)
334 new_location = sub_pixel_peak(max_response_pt, max_response_map);
335 DEBUG_PRINT(new_location);
337 p_pose.cx += p_current_scale*p_cell_size*new_location.x;
338 p_pose.cy += p_current_scale*p_cell_size*new_location.y;
339 if (p_pose.cx < 0) p_pose.cx = 0;
340 if (p_pose.cx > img.cols-1) p_pose.cx = img.cols-1;
341 if (p_pose.cy < 0) p_pose.cy = 0;
342 if (p_pose.cy > img.rows-1) p_pose.cy = img.rows-1;
344 //sub grid scale interpolation
345 double new_scale = p_scales[scale_index];
346 if (m_use_subgrid_scale)
347 new_scale = sub_grid_scale(scale_responses, scale_index);
349 p_current_scale *= new_scale;
351 if (p_current_scale < p_min_max_scale[0])
352 p_current_scale = p_min_max_scale[0];
353 if (p_current_scale > p_min_max_scale[1])
354 p_current_scale = p_min_max_scale[1];
355 //obtain a subwindow for training at newly estimated target position
356 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);
357 ComplexMat xf = fft.forward_window(patch_feat);
359 //subsequent frames, interpolate model
360 p_model_xf = p_model_xf * (1. - p_interp_factor) + xf * p_interp_factor;
362 ComplexMat alphaf_num, alphaf_den;
364 if (m_use_linearkernel) {
365 ComplexMat xfconj = xf.conj();
366 alphaf_num = xfconj.mul(p_yf);
367 alphaf_den = (xf * xfconj);
369 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
370 ComplexMat kf = gaussian_correlation(xf, xf, p_kernel_sigma, true);
371 // ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
372 // p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
373 alphaf_num = p_yf * kf;
374 alphaf_den = kf * (kf + p_lambda);
377 p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
378 p_model_alphaf_den = p_model_alphaf_den * (1. - p_interp_factor) + alphaf_den * p_interp_factor;
379 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
382 // ****************************************************************************
384 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)
386 int size_x_scaled = floor(size_x*scale);
387 int size_y_scaled = floor(size_y*scale);
389 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
390 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
392 //resize to default size
394 //if we downsample use INTER_AREA interpolation
395 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
397 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
400 // get hog(Histogram of Oriented Gradients) features
401 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
403 //get color rgb features (simple r,g,b channels)
404 std::vector<cv::Mat> color_feat;
405 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
406 //resize to default size
408 //if we downsample use INTER_AREA interpolation
409 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_AREA);
411 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_LINEAR);
415 if (m_use_color && input_rgb.channels() == 3) {
416 //use rgb color space
417 cv::Mat patch_rgb_norm;
418 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
419 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
420 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
421 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
422 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
423 cv::split(patch_rgb_norm, rgb);
424 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
427 if (m_use_cnfeat && input_rgb.channels() == 3) {
428 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
429 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
432 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
436 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
438 cv::Mat labels(dim2, dim1, CV_32FC1);
439 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
440 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
442 double sigma_s = sigma*sigma;
444 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j){
445 float * row_ptr = labels.ptr<float>(j);
447 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i){
448 row_ptr[i] = std::exp(-0.5 * (y_s + x*x) / sigma_s);//-1/2*e^((y^2+x^2)/sigma^2)
452 //rotate so that 1 is at top-left corner (see KCF paper for explanation)
453 cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
454 //sanity check, 1 at top left corner
455 assert(rot_labels.at<float>(0,0) >= 1.f - 1e-10f);
460 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
462 cv::Mat rot_patch(patch.size(), CV_32FC1);
463 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
465 //circular rotate x-axis
467 //move part that does not rotate over the edge
468 cv::Range orig_range(-x_rot, patch.cols);
469 cv::Range rot_range(0, patch.cols - (-x_rot));
470 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
473 orig_range = cv::Range(0, -x_rot);
474 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
475 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
476 }else if (x_rot > 0){
477 //move part that does not rotate over the edge
478 cv::Range orig_range(0, patch.cols - x_rot);
479 cv::Range rot_range(x_rot, patch.cols);
480 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
483 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
484 rot_range = cv::Range(0, x_rot);
485 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
486 }else { //zero rotation
487 //move part that does not rotate over the edge
488 cv::Range orig_range(0, patch.cols);
489 cv::Range rot_range(0, patch.cols);
490 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
493 //circular rotate y-axis
495 //move part that does not rotate over the edge
496 cv::Range orig_range(-y_rot, patch.rows);
497 cv::Range rot_range(0, patch.rows - (-y_rot));
498 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
501 orig_range = cv::Range(0, -y_rot);
502 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
503 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
504 }else if (y_rot > 0){
505 //move part that does not rotate over the edge
506 cv::Range orig_range(0, patch.rows - y_rot);
507 cv::Range rot_range(y_rot, patch.rows);
508 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
511 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
512 rot_range = cv::Range(0, y_rot);
513 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
514 }else { //zero rotation
515 //move part that does not rotate over the edge
516 cv::Range orig_range(0, patch.rows);
517 cv::Range rot_range(0, patch.rows);
518 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
524 //hann window actually (Power-of-cosine windows)
525 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
527 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
528 double N_inv = 1./(static_cast<double>(dim1)-1.);
529 for (int i = 0; i < dim1; ++i)
530 m1.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
531 N_inv = 1./(static_cast<double>(dim2)-1.);
532 for (int i = 0; i < dim2; ++i)
533 m2.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
538 // Returns sub-window of image input centered at [cx, cy] coordinates),
539 // with size [width, height]. If any pixels are outside of the image,
540 // they will replicate the values at the borders.
541 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
545 int x1 = cx - width/2;
546 int y1 = cy - height/2;
547 int x2 = cx + width/2;
548 int y2 = cy + height/2;
551 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
552 patch.create(height, width, input.type());
557 int top = 0, bottom = 0, left = 0, right = 0;
559 //fit to image coordinates, set border extensions;
568 if (x2 >= input.cols) {
569 right = x2 - input.cols + width % 2;
574 if (y2 >= input.rows) {
575 bottom = y2 - input.rows + height % 2;
580 if (x2 - x1 == 0 || y2 - y1 == 0)
581 patch = cv::Mat::zeros(height, width, CV_32FC1);
584 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right, cv::BORDER_REPLICATE);
585 // imshow( "copyMakeBorder", patch);
590 assert(patch.cols == width && patch.rows == height);
595 ComplexMat KCF_Tracker::gaussian_correlation(const ComplexMat &xf, const ComplexMat &yf, double sigma, bool auto_correlation)
597 float* xf_sqr_norm = xf.sqr_norm();
598 float* yf_sqr_norm = auto_correlation ? xf_sqr_norm : yf.sqr_norm();
601 xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
604 //ifft2 and sum over 3rd dimension, we dont care about individual channels
605 cv::Mat ifft2_res = fft.inverse(xyf);
607 if(xf.channels() != 308)
608 xy_sum.create(ifft2_res.size(), CV_32FC1);
610 xy_sum.create(ifft2_res.size(), CV_32FC(p_scales.size()));
612 for (int y = 0; y < ifft2_res.rows; ++y) {
613 float * row_ptr = ifft2_res.ptr<float>(y);
614 float * row_ptr_sum = xy_sum.ptr<float>(y);
615 for (int x = 0; x < ifft2_res.cols; ++x) {
616 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
617 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()),
618 (row_ptr + x*ifft2_res.channels() + (sum_ch+1)*(ifft2_res.channels()/xy_sum.channels())), 0.f);
622 DEBUG_PRINTM(ifft2_res);
623 DEBUG_PRINTM(xy_sum);
625 std::vector<cv::Mat> scales;
626 cv::split(xy_sum,scales);
627 cv::Mat in_all(scales[0].rows * xf.n_scales, scales[0].cols, CV_32F);
629 float numel_xf_inv = 1.f/(xf.cols * xf.rows * (xf.channels()/xf.n_scales));
630 for(int i = 0; i < xf.n_scales; ++i){
631 cv::Mat in_roi(in_all, cv::Rect(0, i*scales[0].rows, scales[0].cols, scales[0].rows));
632 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);
633 DEBUG_PRINTM(in_roi);
637 if(!auto_correlation)free(yf_sqr_norm);
639 DEBUG_PRINTM(in_all);
640 return fft.forward(in_all);
643 float get_response_circular(cv::Point2i & pt, cv::Mat & response)
648 x = response.cols + x;
650 y = response.rows + y;
651 if (x >= response.cols)
652 x = x - response.cols;
653 if (y >= response.rows)
654 y = y - response.rows;
656 return response.at<float>(y,x);
659 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
661 //find neighbourhood of max_loc (response is circular)
665 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);
666 cv::Point2i p4(max_loc.x-1, max_loc.y), p5(max_loc.x+1, max_loc.y);
667 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);
669 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
670 cv::Mat A = (cv::Mat_<float>(9, 6) <<
671 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
672 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
673 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
674 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
675 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
676 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
677 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
678 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
679 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);
680 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
681 get_response_circular(p1, response),
682 get_response_circular(p2, response),
683 get_response_circular(p3, response),
684 get_response_circular(p4, response),
685 get_response_circular(p5, response),
686 get_response_circular(p6, response),
687 get_response_circular(p7, response),
688 get_response_circular(p8, response),
689 get_response_circular(max_loc, response));
691 cv::solve(A, fval, x, cv::DECOMP_SVD);
693 double a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2),
694 d = x.at<float>(3), e = x.at<float>(4);
696 cv::Point2f sub_peak(max_loc.x, max_loc.y);
697 if (b > 0 || b < 0) {
698 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
699 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
705 double KCF_Tracker::sub_grid_scale(std::vector<double> & responses, int index)
708 if (index < 0 || index > (int)p_scales.size()-1) {
709 // interpolate from all values
710 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
711 A.create(p_scales.size(), 3, CV_32FC1);
712 fval.create(p_scales.size(), 1, CV_32FC1);
713 for (size_t i = 0; i < p_scales.size(); ++i) {
714 A.at<float>(i, 0) = p_scales[i] * p_scales[i];
715 A.at<float>(i, 1) = p_scales[i];
716 A.at<float>(i, 2) = 1;
717 fval.at<float>(i) = responses[i];
720 //only from neighbours
721 if (index == 0 || index == (int)p_scales.size()-1)
722 return p_scales[index];
724 A = (cv::Mat_<float>(3, 3) <<
725 p_scales[index-1] * p_scales[index-1], p_scales[index-1], 1,
726 p_scales[index] * p_scales[index], p_scales[index], 1,
727 p_scales[index+1] * p_scales[index+1], p_scales[index+1], 1);
728 fval = (cv::Mat_<float>(3, 1) << responses[index-1], responses[index], responses[index+1]);
732 cv::solve(A, fval, x, cv::DECOMP_SVD);
733 double a = x.at<float>(0), b = x.at<float>(1);
734 double scale = p_scales[index];
736 scale = -b / (2 * a);