11 #include "fft_opencv.h"
19 #define DEBUG_PRINT(obj) if (m_debug) {std::cout << #obj << " @" << __LINE__ << std::endl << (obj) << std::endl;}
20 #define DEBUG_PRINTM(obj) if (m_debug) {std::cout << #obj << " @" << __LINE__ << " " << (obj).size() << " CH: " << (obj).channels() << std::endl << (obj) << std::endl;}
22 KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor, double output_sigma_factor, int cell_size) :
24 p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
25 p_lambda(lambda), p_interp_factor(interp_factor), p_cell_size(cell_size) {}
27 KCF_Tracker::KCF_Tracker()
30 KCF_Tracker::~KCF_Tracker()
35 void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
37 //check boundary, enforce min size
38 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
40 if (x2 > img.cols-1) x2 = img.cols - 1;
42 if (y2 > img.rows-1) y2 = img.rows - 1;
44 if (x2-x1 < 2*p_cell_size) {
45 double diff = (2*p_cell_size -x2+x1)/2.;
46 if (x1 - diff >= 0 && x2 + diff < img.cols){
49 } else if (x1 - 2*diff >= 0) {
55 if (y2-y1 < 2*p_cell_size) {
56 double diff = (2*p_cell_size -y2+y1)/2.;
57 if (y1 - diff >= 0 && y2 + diff < img.rows){
60 } else if (y1 - 2*diff >= 0) {
69 p_pose.cx = x1 + p_pose.w/2.;
70 p_pose.cy = y1 + p_pose.h/2.;
73 cv::Mat input_gray, input_rgb = img.clone();
74 if (img.channels() == 3){
75 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
76 input_gray.convertTo(input_gray, CV_32FC1);
78 img.convertTo(input_gray, CV_32FC1);
80 // don't need too large image
81 if (p_pose.w * p_pose.h > 100.*100.) {
82 std::cout << "resizing image by factor of " << 1/p_downscale_factor << std::endl;
83 p_resize_image = true;
84 p_pose.scale(p_downscale_factor);
85 cv::resize(input_gray, input_gray, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
86 cv::resize(input_rgb, input_rgb, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
89 //compute win size + fit to fhog cell size
90 p_windows_size[0] = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
91 p_windows_size[1] = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
95 for (int i = -p_num_scales/2; i <= p_num_scales/2; ++i)
96 p_scales.push_back(std::pow(p_scale_step, i));
98 p_scales.push_back(1.);
100 p_current_scale = 1.;
102 double min_size_ratio = std::max(5.*p_cell_size/p_windows_size[0], 5.*p_cell_size/p_windows_size[1]);
103 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]);
104 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
105 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
107 std::cout << "init: img size " << img.cols << " " << img.rows << std::endl;
108 std::cout << "init: win size. " << p_windows_size[0] << " " << p_windows_size[1] << std::endl;
109 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
111 p_output_sigma = std::sqrt(p_pose.w*p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
113 //window weights, i.e. labels
115 if(m_use_color) num_of_feats += 3;
116 if(m_use_cnfeat) num_of_feats += 10;
117 fft.init(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size, num_of_feats, p_scales.size());
118 p_yf = fft.forward(gaussian_shaped_labels(p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
119 fft.set_window(cosine_window_function(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
121 //obtain a sub-window for training initial model
122 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]);
123 p_model_xf = fft.forward_window(path_feat);
124 DEBUG_PRINTM(p_model_xf);
126 if (m_use_linearkernel) {
127 ComplexMat xfconj = p_model_xf.conj();
128 p_model_alphaf_num = xfconj.mul(p_yf);
129 p_model_alphaf_den = (p_model_xf * xfconj);
131 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
132 ComplexMat kf = gaussian_correlation(p_model_xf, p_model_xf, p_kernel_sigma, true);
134 p_model_alphaf_num = p_yf * kf;
135 DEBUG_PRINTM(p_model_alphaf_num);
136 p_model_alphaf_den = kf * (kf + p_lambda);
137 DEBUG_PRINTM(p_model_alphaf_den);
139 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
140 DEBUG_PRINTM(p_model_alphaf);
141 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
144 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img)
146 init(img, bbox.get_rect());
149 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
151 if (p_resize_image) {
153 tmp.scale(p_downscale_factor);
162 BBox_c KCF_Tracker::getBBox()
165 tmp.w *= p_current_scale;
166 tmp.h *= p_current_scale;
169 tmp.scale(1/p_downscale_factor);
174 void KCF_Tracker::track(cv::Mat &img)
177 std::cout << "NEW FRAME" << '\n';
178 cv::Mat input_gray, input_rgb = img.clone();
179 if (img.channels() == 3){
180 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
181 input_gray.convertTo(input_gray, CV_32FC1);
183 img.convertTo(input_gray, CV_32FC1);
185 // don't need too large image
186 if (p_resize_image) {
187 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
188 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
192 std::vector<cv::Mat> patch_feat;
193 double max_response = -1.;
194 cv::Mat max_response_map;
195 cv::Point2i max_response_pt;
197 std::vector<double> scale_responses;
199 if (m_use_multithreading){
200 std::vector<std::future<cv::Mat>> async_res(p_scales.size());
201 for (size_t i = 0; i < p_scales.size(); ++i) {
202 async_res[i] = std::async(std::launch::async,
203 [this, &input_gray, &input_rgb, i]() -> cv::Mat
205 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],
206 this->p_windows_size[1], this->p_current_scale * this->p_scales[i]);
207 ComplexMat zf = fft.forward_window(patch_feat_async);
208 if (m_use_linearkernel)
209 return fft.inverse((p_model_alphaf * zf).sum_over_channels());
211 ComplexMat kzf = gaussian_correlation(zf, this->p_model_xf, this->p_kernel_sigma);
212 return fft.inverse(this->p_model_alphaf * kzf);
217 for (size_t i = 0; i < p_scales.size(); ++i) {
220 cv::Mat response = async_res[i].get();
222 double min_val, max_val;
223 cv::Point2i min_loc, max_loc;
224 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
226 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
227 if (max_val*weight > max_response) {
228 max_response = max_val*weight;
229 max_response_map = response;
230 max_response_pt = max_loc;
233 scale_responses.push_back(max_val*weight);
235 } else if(m_use_big_batch){
236 for (size_t i = 0; i < p_scales.size(); ++i) {
237 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]);
238 patch_feat.insert(std::end(patch_feat), std::begin(tmp), std::end(tmp));
240 ComplexMat zf = fft.forward_window(patch_feat);
244 if (m_use_linearkernel)
245 response = fft.inverse((zf.mul2(p_model_alphaf)).sum_over_channels());
247 ComplexMat kzf = gaussian_correlation(zf, p_model_xf, p_kernel_sigma);
248 DEBUG_PRINTM(p_model_alphaf);
250 response = fft.inverse(kzf.mul(p_model_alphaf));
252 DEBUG_PRINTM(response);
253 std::vector<cv::Mat> scales;
254 cv::split(response,scales);
256 /* target location is at the maximum response. we must take into
257 account the fact that, if the target doesn't move, the peak
258 will appear at the top-left corner, not at the center (this is
259 discussed in the paper). the responses wrap around cyclically. */
260 for (size_t i = 0; i < p_scales.size(); ++i) {
261 double min_val, max_val;
262 cv::Point2i min_loc, max_loc;
263 cv::minMaxLoc(scales[i], &min_val, &max_val, &min_loc, &max_loc);
264 DEBUG_PRINT(max_loc);
266 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
267 if (max_val*weight > max_response) {
268 max_response = max_val*weight;
269 max_response_map = scales[i];
270 max_response_pt = max_loc;
273 scale_responses.push_back(max_val*weight);
276 #pragma omp parallel for ordered private(patch_feat) schedule(dynamic)
277 for (size_t i = 0; i < p_scales.size(); ++i) {
278 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]);
279 ComplexMat zf = fft.forward_window(patch_feat);
282 if (m_use_linearkernel)
283 response = fft.inverse((p_model_alphaf * zf).sum_over_channels());
285 ComplexMat kzf = gaussian_correlation(zf, p_model_xf, p_kernel_sigma);
286 DEBUG_PRINTM(p_model_alphaf);
288 DEBUG_PRINTM(p_model_alphaf * kzf);
289 response = fft.inverse(p_model_alphaf * kzf);
291 DEBUG_PRINTM(response);
293 /* target location is at the maximum response. we must take into
294 account the fact that, if the target doesn't move, the peak
295 will appear at the top-left corner, not at the center (this is
296 discussed in the paper). the responses wrap around cyclically. */
297 double min_val, max_val;
298 cv::Point2i min_loc, max_loc;
299 cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
300 DEBUG_PRINT(max_loc);
302 double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
305 if (max_val*weight > max_response) {
306 max_response = max_val*weight;
307 max_response_map = response;
308 max_response_pt = max_loc;
313 scale_responses.push_back(max_val*weight);
316 DEBUG_PRINTM(max_response_map);
317 DEBUG_PRINT(max_response_pt);
318 //sub pixel quadratic interpolation from neighbours
319 if (max_response_pt.y > max_response_map.rows / 2) //wrap around to negative half-space of vertical axis
320 max_response_pt.y = max_response_pt.y - max_response_map.rows;
321 if (max_response_pt.x > max_response_map.cols / 2) //same for horizontal axis
322 max_response_pt.x = max_response_pt.x - max_response_map.cols;
324 cv::Point2f new_location(max_response_pt.x, max_response_pt.y);
325 DEBUG_PRINT(new_location);
327 if (m_use_subpixel_localization)
328 new_location = sub_pixel_peak(max_response_pt, max_response_map);
329 DEBUG_PRINT(new_location);
331 p_pose.cx += p_current_scale*p_cell_size*new_location.x;
332 p_pose.cy += p_current_scale*p_cell_size*new_location.y;
333 if (p_pose.cx < 0) p_pose.cx = 0;
334 if (p_pose.cx > img.cols-1) p_pose.cx = img.cols-1;
335 if (p_pose.cy < 0) p_pose.cy = 0;
336 if (p_pose.cy > img.rows-1) p_pose.cy = img.rows-1;
338 //sub grid scale interpolation
339 double new_scale = p_scales[scale_index];
340 if (m_use_subgrid_scale)
341 new_scale = sub_grid_scale(scale_responses, scale_index);
343 p_current_scale *= new_scale;
345 if (p_current_scale < p_min_max_scale[0])
346 p_current_scale = p_min_max_scale[0];
347 if (p_current_scale > p_min_max_scale[1])
348 p_current_scale = p_min_max_scale[1];
349 //obtain a subwindow for training at newly estimated target position
350 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);
351 ComplexMat xf = fft.forward_window(patch_feat);
353 //subsequent frames, interpolate model
354 p_model_xf = p_model_xf * (1. - p_interp_factor) + xf * p_interp_factor;
356 ComplexMat alphaf_num, alphaf_den;
358 if (m_use_linearkernel) {
359 ComplexMat xfconj = xf.conj();
360 alphaf_num = xfconj.mul(p_yf);
361 alphaf_den = (xf * xfconj);
363 //Kernel Ridge Regression, calculate alphas (in Fourier domain)
364 ComplexMat kf = gaussian_correlation(xf, xf, p_kernel_sigma, true);
365 // ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
366 // p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
367 alphaf_num = p_yf * kf;
368 alphaf_den = kf * (kf + p_lambda);
371 p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
372 p_model_alphaf_den = p_model_alphaf_den * (1. - p_interp_factor) + alphaf_den * p_interp_factor;
373 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
376 // ****************************************************************************
378 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)
380 int size_x_scaled = floor(size_x*scale);
381 int size_y_scaled = floor(size_y*scale);
383 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
384 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
386 //resize to default size
388 //if we downsample use INTER_AREA interpolation
389 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
391 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
394 // get hog(Histogram of Oriented Gradients) features
395 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
397 //get color rgb features (simple r,g,b channels)
398 std::vector<cv::Mat> color_feat;
399 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
400 //resize to default size
402 //if we downsample use INTER_AREA interpolation
403 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_AREA);
405 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x/p_cell_size, size_y/p_cell_size), 0., 0., cv::INTER_LINEAR);
409 if (m_use_color && input_rgb.channels() == 3) {
410 //use rgb color space
411 cv::Mat patch_rgb_norm;
412 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
413 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
414 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
415 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
416 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
417 cv::split(patch_rgb_norm, rgb);
418 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
421 if (m_use_cnfeat && input_rgb.channels() == 3) {
422 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
423 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
426 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
430 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
432 cv::Mat labels(dim2, dim1, CV_32FC1);
433 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
434 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
436 double sigma_s = sigma*sigma;
438 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j){
439 float * row_ptr = labels.ptr<float>(j);
441 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i){
442 row_ptr[i] = std::exp(-0.5 * (y_s + x*x) / sigma_s);//-1/2*e^((y^2+x^2)/sigma^2)
446 //rotate so that 1 is at top-left corner (see KCF paper for explanation)
447 cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
448 //sanity check, 1 at top left corner
449 assert(rot_labels.at<float>(0,0) >= 1.f - 1e-10f);
454 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
456 cv::Mat rot_patch(patch.size(), CV_32FC1);
457 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
459 //circular rotate x-axis
461 //move part that does not rotate over the edge
462 cv::Range orig_range(-x_rot, patch.cols);
463 cv::Range rot_range(0, patch.cols - (-x_rot));
464 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
467 orig_range = cv::Range(0, -x_rot);
468 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
469 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
470 }else if (x_rot > 0){
471 //move part that does not rotate over the edge
472 cv::Range orig_range(0, patch.cols - x_rot);
473 cv::Range rot_range(x_rot, patch.cols);
474 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
477 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
478 rot_range = cv::Range(0, x_rot);
479 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
480 }else { //zero rotation
481 //move part that does not rotate over the edge
482 cv::Range orig_range(0, patch.cols);
483 cv::Range rot_range(0, patch.cols);
484 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
487 //circular rotate y-axis
489 //move part that does not rotate over the edge
490 cv::Range orig_range(-y_rot, patch.rows);
491 cv::Range rot_range(0, patch.rows - (-y_rot));
492 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
495 orig_range = cv::Range(0, -y_rot);
496 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
497 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
498 }else if (y_rot > 0){
499 //move part that does not rotate over the edge
500 cv::Range orig_range(0, patch.rows - y_rot);
501 cv::Range rot_range(y_rot, patch.rows);
502 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
505 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
506 rot_range = cv::Range(0, y_rot);
507 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
508 }else { //zero rotation
509 //move part that does not rotate over the edge
510 cv::Range orig_range(0, patch.rows);
511 cv::Range rot_range(0, patch.rows);
512 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
518 //hann window actually (Power-of-cosine windows)
519 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
521 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
522 double N_inv = 1./(static_cast<double>(dim1)-1.);
523 for (int i = 0; i < dim1; ++i)
524 m1.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
525 N_inv = 1./(static_cast<double>(dim2)-1.);
526 for (int i = 0; i < dim2; ++i)
527 m2.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
532 // Returns sub-window of image input centered at [cx, cy] coordinates),
533 // with size [width, height]. If any pixels are outside of the image,
534 // they will replicate the values at the borders.
535 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
539 int x1 = cx - width/2;
540 int y1 = cy - height/2;
541 int x2 = cx + width/2;
542 int y2 = cy + height/2;
545 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
546 patch.create(height, width, input.type());
551 int top = 0, bottom = 0, left = 0, right = 0;
553 //fit to image coordinates, set border extensions;
562 if (x2 >= input.cols) {
563 right = x2 - input.cols + width % 2;
568 if (y2 >= input.rows) {
569 bottom = y2 - input.rows + height % 2;
574 if (x2 - x1 == 0 || y2 - y1 == 0)
575 patch = cv::Mat::zeros(height, width, CV_32FC1);
578 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right, cv::BORDER_REPLICATE);
579 // imshow( "copyMakeBorder", patch);
584 assert(patch.cols == width && patch.rows == height);
589 ComplexMat KCF_Tracker::gaussian_correlation(const ComplexMat &xf, const ComplexMat &yf, double sigma, bool auto_correlation)
591 std::vector<float> xf_sqr_norm = xf.sqr_norm();
592 std::vector<float> yf_sqr_norm = auto_correlation ? xf_sqr_norm : yf.sqr_norm();
595 xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
598 //ifft2 and sum over 3rd dimension, we dont care about individual channels
599 cv::Mat ifft2_res = fft.inverse(xyf);
601 if(xf.channels() != 308)
602 xy_sum.create(ifft2_res.size(), CV_32FC1);
604 xy_sum.create(ifft2_res.size(), CV_32FC(p_scales.size()));
606 for (int y = 0; y < ifft2_res.rows; ++y) {
607 float * row_ptr = ifft2_res.ptr<float>(y);
608 float * row_ptr_sum = xy_sum.ptr<float>(y);
609 for (int x = 0; x < ifft2_res.cols; ++x) {
610 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
611 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()),
612 (row_ptr + x*ifft2_res.channels() + (sum_ch+1)*(ifft2_res.channels()/xy_sum.channels())), 0.f);
616 DEBUG_PRINTM(ifft2_res);
617 DEBUG_PRINTM(xy_sum);
619 std::vector<cv::Mat> scales;
620 cv::split(xy_sum,scales);
621 cv::Mat in_all(scales[0].rows * xf.n_scales, scales[0].cols, CV_32F);
623 float numel_xf_inv = 1.f/(xf.cols * xf.rows * (xf.channels()/xf.n_scales));
624 for(int i = 0; i < xf.n_scales; ++i){
625 cv::Mat in_roi(in_all, cv::Rect(0, i*scales[0].rows, scales[0].cols, scales[0].rows));
626 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);
627 DEBUG_PRINTM(in_roi);
630 DEBUG_PRINTM(in_all);
631 return fft.forward(in_all);
634 float get_response_circular(cv::Point2i & pt, cv::Mat & response)
639 x = response.cols + x;
641 y = response.rows + y;
642 if (x >= response.cols)
643 x = x - response.cols;
644 if (y >= response.rows)
645 y = y - response.rows;
647 return response.at<float>(y,x);
650 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
652 //find neighbourhood of max_loc (response is circular)
656 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);
657 cv::Point2i p4(max_loc.x-1, max_loc.y), p5(max_loc.x+1, max_loc.y);
658 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);
660 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
661 cv::Mat A = (cv::Mat_<float>(9, 6) <<
662 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
663 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
664 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
665 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
666 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
667 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
668 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
669 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
670 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);
671 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
672 get_response_circular(p1, response),
673 get_response_circular(p2, response),
674 get_response_circular(p3, response),
675 get_response_circular(p4, response),
676 get_response_circular(p5, response),
677 get_response_circular(p6, response),
678 get_response_circular(p7, response),
679 get_response_circular(p8, response),
680 get_response_circular(max_loc, response));
682 cv::solve(A, fval, x, cv::DECOMP_SVD);
684 double a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2),
685 d = x.at<float>(3), e = x.at<float>(4);
687 cv::Point2f sub_peak(max_loc.x, max_loc.y);
688 if (b > 0 || b < 0) {
689 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
690 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
696 double KCF_Tracker::sub_grid_scale(std::vector<double> & responses, int index)
699 if (index < 0 || index > (int)p_scales.size()-1) {
700 // interpolate from all values
701 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
702 A.create(p_scales.size(), 3, CV_32FC1);
703 fval.create(p_scales.size(), 1, CV_32FC1);
704 for (size_t i = 0; i < p_scales.size(); ++i) {
705 A.at<float>(i, 0) = p_scales[i] * p_scales[i];
706 A.at<float>(i, 1) = p_scales[i];
707 A.at<float>(i, 2) = 1;
708 fval.at<float>(i) = responses[i];
711 //only from neighbours
712 if (index == 0 || index == (int)p_scales.size()-1)
713 return p_scales[index];
715 A = (cv::Mat_<float>(3, 3) <<
716 p_scales[index-1] * p_scales[index-1], p_scales[index-1], 1,
717 p_scales[index] * p_scales[index], p_scales[index], 1,
718 p_scales[index+1] * p_scales[index+1], p_scales[index+1], 1);
719 fval = (cv::Mat_<float>(3, 1) << responses[index-1], responses[index], responses[index+1]);
723 cv::solve(A, fval, x, cv::DECOMP_SVD);
724 double a = x.at<float>(0), b = x.at<float>(1);
725 double scale = p_scales[index];
727 scale = -b / (2 * a);