5 #include "threadctx.hpp"
12 #include "fft_cufft.h"
15 #include "fft_opencv.h"
23 DbgTracer __dbgTracer;
26 T clamp(const T& n, const T& lower, const T& upper)
28 return std::max(lower, std::min(n, upper));
32 void clamp2(T& n, const T& lower, const T& upper)
34 n = std::max(lower, std::min(n, upper));
37 class Kcf_Tracker_Private {
39 std::vector<ThreadCtx> threadctxs;
42 KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor,
43 double output_sigma_factor, int cell_size)
44 : fft(*new FFT()), p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
45 p_lambda(lambda), p_interp_factor(interp_factor), p_cell_size(cell_size), d(*new Kcf_Tracker_Private)
49 KCF_Tracker::KCF_Tracker() : fft(*new FFT()), d(*new Kcf_Tracker_Private) {}
51 KCF_Tracker::~KCF_Tracker()
57 void KCF_Tracker::train(cv::Mat input_rgb, cv::Mat input_gray, double interp_factor)
61 // obtain a sub-window for training
62 // TODO: Move Mats outside from here
63 MatScaleFeats patch_feats(1, p_num_of_feats, p_roi);
64 DEBUG_PRINT(patch_feats);
65 MatScaleFeats temp(1, p_num_of_feats, p_roi);
66 get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy,
67 p_windows_size.width, p_windows_size.height,
68 p_current_scale).copyTo(patch_feats.scale(0));
69 DEBUG_PRINT(patch_feats);
70 fft.forward_window(patch_feats, p_xf, temp);
72 p_model_xf = p_model_xf * (1. - interp_factor) + p_xf * interp_factor;
73 DEBUG_PRINTM(p_model_xf);
75 ComplexMat alphaf_num, alphaf_den;
77 if (m_use_linearkernel) {
78 ComplexMat xfconj = p_xf.conj();
79 alphaf_num = xfconj.mul(p_yf);
80 alphaf_den = (p_xf * xfconj);
82 // Kernel Ridge Regression, calculate alphas (in Fourier domain)
83 const uint num_scales = BIG_BATCH_MODE ? p_num_scales : 1;
84 cv::Size sz(Fft::freq_size(p_roi));
85 ComplexMat kf(sz.height, sz.width, num_scales);
86 (*gaussian_correlation)(*this, kf, p_model_xf, p_model_xf, p_kernel_sigma, true);
88 p_model_alphaf_num = p_yf * kf;
89 p_model_alphaf_den = kf * (kf + p_lambda);
91 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
92 DEBUG_PRINTM(p_model_alphaf);
93 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
96 void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int fit_size_y)
98 __dbgTracer.debug = m_debug;
101 // check boundary, enforce min size
102 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
104 if (x2 > img.cols - 1) x2 = img.cols - 1;
106 if (y2 > img.rows - 1) y2 = img.rows - 1;
108 if (x2 - x1 < 2 * p_cell_size) {
109 double diff = (2 * p_cell_size - x2 + x1) / 2.;
110 if (x1 - diff >= 0 && x2 + diff < img.cols) {
113 } else if (x1 - 2 * diff >= 0) {
119 if (y2 - y1 < 2 * p_cell_size) {
120 double diff = (2 * p_cell_size - y2 + y1) / 2.;
121 if (y1 - diff >= 0 && y2 + diff < img.rows) {
124 } else if (y1 - 2 * diff >= 0) {
133 p_pose.cx = x1 + p_pose.w / 2.;
134 p_pose.cy = y1 + p_pose.h / 2.;
136 cv::Mat input_gray, input_rgb = img.clone();
137 if (img.channels() == 3) {
138 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
139 input_gray.convertTo(input_gray, CV_32FC1);
141 img.convertTo(input_gray, CV_32FC1);
143 // don't need too large image
144 if (p_pose.w * p_pose.h > 100. * 100. && (fit_size_x == -1 || fit_size_y == -1)) {
145 std::cout << "resizing image by factor of " << 1 / p_downscale_factor << std::endl;
146 p_resize_image = true;
147 p_pose.scale(p_downscale_factor);
148 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
149 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
150 } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
151 if (fit_size_x % p_cell_size != 0 || fit_size_y % p_cell_size != 0) {
152 std::cerr << "Error: Fit size is not multiple of HOG cell size (" << p_cell_size << ")" << std::endl;
153 std::exit(EXIT_FAILURE);
155 p_scale_factor_x = (double)fit_size_x / round(p_pose.w * (1. + p_padding));
156 p_scale_factor_y = (double)fit_size_y / round(p_pose.h * (1. + p_padding));
157 std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x << " and verticaly by factor of "
158 << p_scale_factor_y << std::endl;
160 p_pose.scale_x(p_scale_factor_x);
161 p_pose.scale_y(p_scale_factor_y);
162 if (fabs(p_scale_factor_x - 1) > p_floating_error || fabs(p_scale_factor_y - 1) > p_floating_error) {
163 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
164 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
165 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
167 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
168 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
173 // compute win size + fit to fhog cell size
174 p_windows_size.width = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
175 p_windows_size.height = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
176 p_roi.width = p_windows_size.width / p_cell_size;
177 p_roi.height = p_windows_size.height / p_cell_size;
181 for (int i = -int(p_num_scales) / 2; i <= int(p_num_scales) / 2; ++i)
182 p_scales.push_back(std::pow(p_scale_step, i));
184 p_scales.push_back(1.);
187 if (p_roi.height * (p_roi.width / 2 + 1) > 1024) {
188 std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
189 "the window dimensions so its size is less or equal to "
190 << 1024 * p_cell_size * p_cell_size * 2 + 1
191 << " pixels . Currently the size of the window is: " << p_windows_size.width << "x" << p_windows_size.height
192 << " which is " << p_windows_size.width * p_windows_size.height << " pixels. " << std::endl;
193 std::exit(EXIT_FAILURE);
196 if (m_use_linearkernel) {
197 std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
198 std::exit(EXIT_FAILURE);
200 CudaSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost));
202 p_xf.create(p_roi.height, p_roi.height / 2 + 1, p_num_of_feats);
205 #if defined(CUFFT) || defined(FFTW)
206 uint width = p_roi.width / 2 + 1;
208 uint width = p_roi.width;
210 p_model_xf.create(p_roi.height, width, p_num_of_feats);
211 p_yf.create(p_roi.height, width, 1);
212 p_xf.create(p_roi.height, width, p_num_of_feats);
215 for (auto scale: p_scales)
216 d.threadctxs.emplace_back(p_roi, p_num_of_feats, scale);
218 d.threadctxs.emplace_back(p_roi, p_num_of_feats, p_num_scales);
221 gaussian_correlation.reset(
222 new GaussianCorrelation(IF_BIG_BATCH(p_num_scales, 1), p_roi));
224 p_current_scale = 1.;
226 double min_size_ratio = std::max(5. * p_cell_size / p_windows_size.width, 5. * p_cell_size / p_windows_size.height);
227 double max_size_ratio =
228 std::min(floor((img.cols + p_windows_size.width / 3) / p_cell_size) * p_cell_size / p_windows_size.width,
229 floor((img.rows + p_windows_size.height / 3) / p_cell_size) * p_cell_size / p_windows_size.height);
230 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
231 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
233 std::cout << "init: img size " << img.cols << "x" << img.rows << std::endl;
234 std::cout << "init: win size " << p_windows_size.width << "x" << p_windows_size.height << std::endl;
235 std::cout << "init: FFT size " << p_roi.width << "x" << p_roi.height << std::endl;
236 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
238 p_output_sigma = std::sqrt(p_pose.w * p_pose.h) * p_output_sigma_factor / p_cell_size;
240 fft.init(p_roi.width, p_roi.height, p_num_of_feats, p_num_scales);
241 fft.set_window(MatDynMem(cosine_window_function(p_roi.width, p_roi.height)));
243 // window weights, i.e. labels
244 MatScales gsl(1, p_roi);
245 gaussian_shaped_labels(p_output_sigma, p_roi.width, p_roi.height).copyTo(gsl.plane(0));
246 fft.forward(gsl, p_yf);
249 // train initial model
250 train(input_rgb, input_gray, 1.0);
253 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat &img, int fit_size_x, int fit_size_y)
255 init(img, bbox.get_rect(), fit_size_x, fit_size_y);
258 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
260 if (p_resize_image) {
262 tmp.scale(p_downscale_factor);
265 } else if (p_fit_to_pw2) {
267 tmp.scale_x(p_scale_factor_x);
268 tmp.scale_y(p_scale_factor_y);
277 BBox_c KCF_Tracker::getBBox()
280 tmp.w *= p_current_scale;
281 tmp.h *= p_current_scale;
283 if (p_resize_image) tmp.scale(1 / p_downscale_factor);
285 tmp.scale_x(1 / p_scale_factor_x);
286 tmp.scale_y(1 / p_scale_factor_y);
292 double KCF_Tracker::getFilterResponse() const
294 return this->max_response;
297 void KCF_Tracker::resizeImgs(cv::Mat &input_rgb, cv::Mat &input_gray)
299 if (p_resize_image) {
300 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
301 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
302 } else if (p_fit_to_pw2 && fabs(p_scale_factor_x - 1) > p_floating_error &&
303 fabs(p_scale_factor_y - 1) > p_floating_error) {
304 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
305 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
306 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
308 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
309 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
314 void KCF_Tracker::findMaxReponse(uint &max_idx, cv::Point2f &new_location) const
318 for (uint j = 0; j < d.threadctxs.size(); ++j) {
319 if (d.threadctxs[j].max.response > max) {
320 max = d.threadctxs[j].max.response;
325 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
326 for (uint j = 0; j < p_scales.size(); ++j) {
327 if (d.threadctxs[0].max[j].response > max) {
328 max = d.threadctxs[0].max[j].response;
333 cv::Point2i &max_response_pt = IF_BIG_BATCH(d.threadctxs[0].max[max_idx].loc, d.threadctxs[max_idx].max.loc);
334 cv::Mat max_response_map = IF_BIG_BATCH(d.threadctxs[0].response.plane(max_idx), d.threadctxs[max_idx].response.plane(0));
336 DEBUG_PRINTM(max_response_map);
337 DEBUG_PRINT(max_response_pt);
339 // sub pixel quadratic interpolation from neighbours
340 if (max_response_pt.y > max_response_map.rows / 2) // wrap around to negative half-space of vertical axis
341 max_response_pt.y = max_response_pt.y - max_response_map.rows;
342 if (max_response_pt.x > max_response_map.cols / 2) // same for horizontal axis
343 max_response_pt.x = max_response_pt.x - max_response_map.cols;
346 if (m_use_subpixel_localization) {
347 new_location = sub_pixel_peak(max_response_pt, max_response_map);
349 new_location = max_response_pt;
351 DEBUG_PRINT(new_location);
354 void KCF_Tracker::track(cv::Mat &img)
356 __dbgTracer.debug = m_debug;
359 cv::Mat input_gray, input_rgb = img.clone();
360 if (img.channels() == 3) {
361 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
362 input_gray.convertTo(input_gray, CV_32FC1);
364 img.convertTo(input_gray, CV_32FC1);
366 // don't need too large image
367 resizeImgs(input_rgb, input_gray);
370 for (auto &it : d.threadctxs)
371 it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
372 it.track(*this, input_rgb, input_gray);
374 for (auto const &it : d.threadctxs)
378 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
379 NORMAL_OMP_PARALLEL_FOR
380 for (uint i = 0; i < d.threadctxs.size(); ++i)
381 d.threadctxs[i].track(*this, input_rgb, input_gray);
384 cv::Point2f new_location;
386 findMaxReponse(max_idx, new_location);
388 p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
389 p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
391 clamp2(p_pose.cx, 0.0, (img.cols * p_scale_factor_x) - 1);
392 clamp2(p_pose.cy, 0.0, (img.rows * p_scale_factor_y) - 1);
394 clamp2(p_pose.cx, 0.0, img.cols - 1.0);
395 clamp2(p_pose.cy, 0.0, img.rows - 1.0);
398 // sub grid scale interpolation
399 if (m_use_subgrid_scale) {
400 p_current_scale *= sub_grid_scale(max_idx);
402 p_current_scale *= p_scales[max_idx];
405 clamp2(p_current_scale, p_min_max_scale[0], p_min_max_scale[1]);
407 // train at newly estimated target position
408 train(input_rgb, input_gray, p_interp_factor);
411 void ThreadCtx::track(const KCF_Tracker &kcf, cv::Mat &input_rgb, cv::Mat &input_gray)
415 BIG_BATCH_OMP_PARALLEL_FOR
416 for (uint i = 0; i < IF_BIG_BATCH(kcf.p_num_scales, 1); ++i)
418 kcf.get_features(input_rgb, input_gray, kcf.p_pose.cx, kcf.p_pose.cy,
419 kcf.p_windows_size.width, kcf.p_windows_size.height,
420 kcf.p_current_scale * IF_BIG_BATCH(kcf.p_scales[i], scale))
421 .copyTo(patch_feats.scale(i));
422 DEBUG_PRINT(patch_feats.scale(i));
425 kcf.fft.forward_window(patch_feats, zf, temp);
428 if (kcf.m_use_linearkernel) {
429 kzf = zf.mul(kcf.p_model_alphaf).sum_over_channels();
431 gaussian_correlation(kcf, kzf, zf, kcf.p_model_xf, kcf.p_kernel_sigma);
433 kzf = kzf.mul(kcf.p_model_alphaf);
435 kcf.fft.inverse(kzf, response);
437 DEBUG_PRINTM(response);
439 /* target location is at the maximum response. we must take into
440 account the fact that, if the target doesn't move, the peak
441 will appear at the top-left corner, not at the center (this is
442 discussed in the paper). the responses wrap around cyclically. */
443 double min_val, max_val;
444 cv::Point2i min_loc, max_loc;
446 for (size_t i = 0; i < kcf.p_scales.size(); ++i) {
447 cv::minMaxLoc(response.plane(i), &min_val, &max_val, &min_loc, &max_loc);
448 DEBUG_PRINT(max_loc);
449 double weight = kcf.p_scales[i] < 1. ? kcf.p_scales[i] : 1. / kcf.p_scales[i];
450 max[i].response = max_val * weight;
451 max[i].loc = max_loc;
454 cv::minMaxLoc(response.plane(0), &min_val, &max_val, &min_loc, &max_loc);
456 DEBUG_PRINT(max_loc);
457 DEBUG_PRINT(max_val);
459 double weight = scale < 1. ? scale : 1. / scale;
460 max.response = max_val * weight;
465 // ****************************************************************************
467 cv::Mat KCF_Tracker::get_features(cv::Mat &input_rgb, cv::Mat &input_gray, int cx, int cy,
468 int size_x, int size_y, double scale) const
470 int size_x_scaled = floor(size_x * scale);
471 int size_y_scaled = floor(size_y * scale);
473 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
474 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
476 // resize to default size
478 // if we downsample use INTER_AREA interpolation
479 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
481 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
484 // get hog(Histogram of Oriented Gradients) features
485 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
487 // get color rgb features (simple r,g,b channels)
488 std::vector<cv::Mat> color_feat;
489 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
490 // resize to default size
492 // if we downsample use INTER_AREA interpolation
493 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_AREA);
495 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_LINEAR);
499 if (m_use_color && input_rgb.channels() == 3) {
500 // use rgb color space
501 cv::Mat patch_rgb_norm;
502 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
503 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
504 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
505 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
506 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
507 cv::split(patch_rgb_norm, rgb);
508 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
511 if (m_use_cnfeat && input_rgb.channels() == 3) {
512 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
513 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
516 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
518 int size[] = {p_num_of_feats, p_roi.height, p_roi.width};
519 cv::Mat result(3, size, CV_32F);
520 for (uint i = 0; i < hog_feat.size(); ++i)
521 hog_feat[i].copyTo(cv::Mat(size[1], size[2], CV_32FC1, result.ptr(i)));
526 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
528 cv::Mat labels(dim2, dim1, CV_32FC1);
529 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
530 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
532 double sigma_s = sigma * sigma;
534 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
535 float *row_ptr = labels.ptr<float>(j);
537 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
538 row_ptr[i] = std::exp(-0.5 * (y_s + x * x) / sigma_s); //-1/2*e^((y^2+x^2)/sigma^2)
542 // rotate so that 1 is at top-left corner (see KCF paper for explanation)
543 MatDynMem rot_labels = circshift(labels, range_x[0], range_y[0]);
544 // sanity check, 1 at top left corner
545 assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
550 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
552 cv::Mat rot_patch(patch.size(), CV_32FC1);
553 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
555 // circular rotate x-axis
557 // move part that does not rotate over the edge
558 cv::Range orig_range(-x_rot, patch.cols);
559 cv::Range rot_range(0, patch.cols - (-x_rot));
560 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
563 orig_range = cv::Range(0, -x_rot);
564 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
565 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
566 } else if (x_rot > 0) {
567 // move part that does not rotate over the edge
568 cv::Range orig_range(0, patch.cols - x_rot);
569 cv::Range rot_range(x_rot, patch.cols);
570 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
573 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
574 rot_range = cv::Range(0, x_rot);
575 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
576 } else { // zero rotation
577 // move part that does not rotate over the edge
578 cv::Range orig_range(0, patch.cols);
579 cv::Range rot_range(0, patch.cols);
580 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
583 // circular rotate y-axis
585 // move part that does not rotate over the edge
586 cv::Range orig_range(-y_rot, patch.rows);
587 cv::Range rot_range(0, patch.rows - (-y_rot));
588 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
591 orig_range = cv::Range(0, -y_rot);
592 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
593 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
594 } else if (y_rot > 0) {
595 // move part that does not rotate over the edge
596 cv::Range orig_range(0, patch.rows - y_rot);
597 cv::Range rot_range(y_rot, patch.rows);
598 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
601 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
602 rot_range = cv::Range(0, y_rot);
603 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
604 } else { // zero rotation
605 // move part that does not rotate over the edge
606 cv::Range orig_range(0, patch.rows);
607 cv::Range rot_range(0, patch.rows);
608 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
614 // hann window actually (Power-of-cosine windows)
615 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
617 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
618 double N_inv = 1. / (static_cast<double>(dim1) - 1.);
619 for (int i = 0; i < dim1; ++i)
620 m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
621 N_inv = 1. / (static_cast<double>(dim2) - 1.);
622 for (int i = 0; i < dim2; ++i)
623 m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
624 cv::Mat ret = m2 * m1;
628 // Returns sub-window of image input centered at [cx, cy] coordinates),
629 // with size [width, height]. If any pixels are outside of the image,
630 // they will replicate the values at the borders.
631 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height) const
635 int x1 = cx - width / 2;
636 int y1 = cy - height / 2;
637 int x2 = cx + width / 2;
638 int y2 = cy + height / 2;
641 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
642 patch.create(height, width, input.type());
643 patch.setTo(double(0.f));
647 int top = 0, bottom = 0, left = 0, right = 0;
649 // fit to image coordinates, set border extensions;
658 if (x2 >= input.cols) {
659 right = x2 - input.cols + width % 2;
664 if (y2 >= input.rows) {
665 bottom = y2 - input.rows + height % 2;
670 if (x2 - x1 == 0 || y2 - y1 == 0)
671 patch = cv::Mat::zeros(height, width, CV_32FC1);
673 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
674 cv::BORDER_REPLICATE);
675 // imshow( "copyMakeBorder", patch);
680 assert(patch.cols == width && patch.rows == height);
685 void KCF_Tracker::GaussianCorrelation::operator()(const KCF_Tracker &kcf, ComplexMat &result, const ComplexMat &xf,
686 const ComplexMat &yf, double sigma, bool auto_correlation)
689 xf.sqr_norm(xf_sqr_norm);
690 if (auto_correlation) {
691 yf_sqr_norm = xf_sqr_norm;
693 yf.sqr_norm(yf_sqr_norm);
695 xyf = auto_correlation ? xf.sqr_mag() : xf * yf.conj(); // xf.muln(yf.conj());
698 // ifft2 and sum over 3rd dimension, we dont care about individual channels
699 ComplexMat xyf_sum = xyf.sum_over_channels();
700 DEBUG_PRINTM(xyf_sum);
701 kcf.fft.inverse(xyf_sum, ifft_res);
702 DEBUG_PRINTM(ifft_res);
705 cuda_gaussian_correlation(ifft_res.deviceMem(), k.deviceMem(), xf_sqr_norm.deviceMem(),
706 auto_correlation ? xf_sqr_norm.deviceMem() : yf_sqr_norm.deviceMem(), sigma,
707 xf.n_channels, xf.n_scales, kcf.p_roi.height, kcf.p_roi.width);
710 float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
711 for (uint i = 0; i < xf.n_scales; ++i) {
712 cv::Mat plane = ifft_res.plane(i);
713 cv::exp(-1. / (sigma * sigma) * cv::max((xf_sqr_norm[i] + yf_sqr_norm[0] - 2 * ifft_res.plane(i))
714 * numel_xf_inv, 0), plane);
718 kcf.fft.forward(ifft_res, result);
721 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
725 assert(response.dims == 2); // ensure .cols and .rows are valid
726 if (x < 0) x = response.cols + x;
727 if (y < 0) y = response.rows + y;
728 if (x >= response.cols) x = x - response.cols;
729 if (y >= response.rows) y = y - response.rows;
731 return response.at<float>(y, x);
734 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response) const
736 // find neighbourhood of max_loc (response is circular)
740 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);
741 cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
742 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);
745 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
746 cv::Mat A = (cv::Mat_<float>(9, 6) <<
747 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
748 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
749 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
750 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
751 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
752 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
753 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
754 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
755 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);
756 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
757 get_response_circular(p1, response),
758 get_response_circular(p2, response),
759 get_response_circular(p3, response),
760 get_response_circular(p4, response),
761 get_response_circular(p5, response),
762 get_response_circular(p6, response),
763 get_response_circular(p7, response),
764 get_response_circular(p8, response),
765 get_response_circular(max_loc, response));
768 cv::solve(A, fval, x, cv::DECOMP_SVD);
770 float a = x.at<float>(0), b = x.at<float>(1), c = x.at<float>(2), d = x.at<float>(3), e = x.at<float>(4);
772 cv::Point2f sub_peak(max_loc.x, max_loc.y);
773 if (b > 0 || b < 0) {
774 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
775 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
781 double KCF_Tracker::sub_grid_scale(uint index)
784 if (index >= p_scales.size()) {
785 // interpolate from all values
786 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
787 A.create(p_scales.size(), 3, CV_32FC1);
788 fval.create(p_scales.size(), 1, CV_32FC1);
789 for (size_t i = 0; i < p_scales.size(); ++i) {
790 A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
791 A.at<float>(i, 1) = float(p_scales[i]);
792 A.at<float>(i, 2) = 1;
793 fval.at<float>(i) = d.threadctxs.back().IF_BIG_BATCH(max[i].response, max.response);
796 // only from neighbours
797 if (index == 0 || index == p_scales.size() - 1)
798 return p_scales[index];
800 A = (cv::Mat_<float>(3, 3) <<
801 p_scales[index - 1] * p_scales[index - 1], p_scales[index - 1], 1,
802 p_scales[index + 0] * p_scales[index + 0], p_scales[index + 0], 1,
803 p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
805 fval = (cv::Mat_<float>(3, 1) <<
806 d.threadctxs.back().max[index - 1].response,
807 d.threadctxs.back().max[index + 0].response,
808 d.threadctxs.back().max[index + 1].response);
810 fval = (cv::Mat_<float>(3, 1) <<
811 d.threadctxs[index - 1].max.response,
812 d.threadctxs[index + 0].max.response,
813 d.threadctxs[index + 1].max.response);
818 cv::solve(A, fval, x, cv::DECOMP_SVD);
819 float a = x.at<float>(0), b = x.at<float>(1);
820 double scale = p_scales[index];
822 scale = -b / (2 * a);