5 #include "threadctx.hpp"
11 #include "fft_cufft.h"
14 #include "fft_opencv.h"
22 #define DEBUG_PRINT(obj) \
24 std::cout << #obj << " @" << __LINE__ << std::endl << (obj) << std::endl; \
26 #define DEBUG_PRINTM(obj) \
28 std::cout << #obj << " @" << __LINE__ << " " << (obj).size() << " CH: " << (obj).channels() << std::endl \
29 << (obj) << std::endl; \
33 T clamp(const T& n, const T& lower, const T& upper)
35 return std::max(lower, std::min(n, upper));
39 void clamp2(T& n, const T& lower, const T& upper)
41 n = std::max(lower, std::min(n, upper));
44 class Kcf_Tracker_Private {
46 std::vector<ThreadCtx> threadctxs;
49 KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor,
50 double output_sigma_factor, int cell_size)
51 : fft(*new FFT()), p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
52 p_lambda(lambda), p_interp_factor(interp_factor), p_cell_size(cell_size), d(*new Kcf_Tracker_Private)
56 KCF_Tracker::KCF_Tracker() : fft(*new FFT()), d(*new Kcf_Tracker_Private) {}
58 KCF_Tracker::~KCF_Tracker()
64 void KCF_Tracker::train(cv::Mat input_gray, cv::Mat input_rgb, double interp_factor)
66 // obtain a sub-window for training
67 int sizes[3] = {p_num_of_feats, p_windows_size.height, p_windows_size.width};
68 MatDynMem patch_feats(3, sizes, CV_32FC1);
69 MatDynMem temp(3, sizes, CV_32FC1);
70 get_features(patch_feats, input_rgb, input_gray, p_pose.cx, p_pose.cy,
71 p_windows_size.width, p_windows_size.height,
73 fft.forward_window(patch_feats, p_xf, temp);
74 p_model_xf = p_model_xf * (1. - interp_factor) + p_xf * interp_factor;
75 DEBUG_PRINTM(p_model_xf);
77 ComplexMat alphaf_num, alphaf_den;
79 if (m_use_linearkernel) {
80 ComplexMat xfconj = p_xf.conj();
81 alphaf_num = xfconj.mul(p_yf);
82 alphaf_den = (p_xf * xfconj);
84 // Kernel Ridge Regression, calculate alphas (in Fourier domain)
85 const uint num_scales = BIG_BATCH_MODE ? p_num_scales : 1;
86 cv::Size sz(Fft::freq_size(p_roi));
87 ComplexMat kf(sz.height, sz.width, num_scales);
88 (*gaussian_correlation)(*this, kf, p_model_xf, p_model_xf, p_kernel_sigma, true);
90 p_model_alphaf_num = p_yf * kf;
91 DEBUG_PRINTM(p_model_alphaf_num);
92 p_model_alphaf_den = kf * (kf + p_lambda);
93 DEBUG_PRINTM(p_model_alphaf_den);
95 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
96 DEBUG_PRINTM(p_model_alphaf);
97 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
100 void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int fit_size_y)
102 // check boundary, enforce min size
103 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
105 if (x2 > img.cols - 1) x2 = img.cols - 1;
107 if (y2 > img.rows - 1) y2 = img.rows - 1;
109 if (x2 - x1 < 2 * p_cell_size) {
110 double diff = (2 * p_cell_size - x2 + x1) / 2.;
111 if (x1 - diff >= 0 && x2 + diff < img.cols) {
114 } else if (x1 - 2 * diff >= 0) {
120 if (y2 - y1 < 2 * p_cell_size) {
121 double diff = (2 * p_cell_size - y2 + y1) / 2.;
122 if (y1 - diff >= 0 && y2 + diff < img.rows) {
125 } else if (y1 - 2 * diff >= 0) {
134 p_pose.cx = x1 + p_pose.w / 2.;
135 p_pose.cy = y1 + p_pose.h / 2.;
137 cv::Mat input_gray, input_rgb = img.clone();
138 if (img.channels() == 3) {
139 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
140 input_gray.convertTo(input_gray, CV_32FC1);
142 img.convertTo(input_gray, CV_32FC1);
144 // don't need too large image
145 if (p_pose.w * p_pose.h > 100. * 100. && (fit_size_x == -1 || fit_size_y == -1)) {
146 std::cout << "resizing image by factor of " << 1 / p_downscale_factor << std::endl;
147 p_resize_image = true;
148 p_pose.scale(p_downscale_factor);
149 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
150 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
151 } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
152 if (fit_size_x % p_cell_size != 0 || fit_size_y % p_cell_size != 0) {
153 std::cerr << "Error: Fit size is not multiple of HOG cell size (" << p_cell_size << ")" << std::endl;
154 std::exit(EXIT_FAILURE);
156 p_scale_factor_x = (double)fit_size_x / round(p_pose.w * (1. + p_padding));
157 p_scale_factor_y = (double)fit_size_y / round(p_pose.h * (1. + p_padding));
158 std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x << " and verticaly by factor of "
159 << p_scale_factor_y << std::endl;
161 p_pose.scale_x(p_scale_factor_x);
162 p_pose.scale_y(p_scale_factor_y);
163 if (fabs(p_scale_factor_x - 1) > p_floating_error || fabs(p_scale_factor_y - 1) > p_floating_error) {
164 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
165 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
166 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
168 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
169 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
174 // compute win size + fit to fhog cell size
175 p_windows_size.width = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
176 p_windows_size.height = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
177 p_roi.width = p_windows_size.width / p_cell_size;
178 p_roi.height = p_windows_size.height / p_cell_size;
182 for (int i = -int(p_num_scales) / 2; i <= int(p_num_scales) / 2; ++i)
183 p_scales.push_back(std::pow(p_scale_step, i));
185 p_scales.push_back(1.);
188 if (p_roi.height * (p_roi.width / 2 + 1) > 1024) {
189 std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
190 "the window dimensions so its size is less or equal to "
191 << 1024 * p_cell_size * p_cell_size * 2 + 1
192 << " pixels . Currently the size of the window is: " << p_windows_size.width << "x" << p_windows_size.height
193 << " which is " << p_windows_size.width * p_windows_size.height << " pixels. " << std::endl;
194 std::exit(EXIT_FAILURE);
197 if (m_use_linearkernel) {
198 std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
199 std::exit(EXIT_FAILURE);
201 CudaSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost));
203 p_xf.create(p_roi.height, p_roi.height / 2 + 1, p_num_of_feats);
206 #if defined(CUFFT) || defined(FFTW)
207 uint width = p_roi.width / 2 + 1;
209 uint width = p_roi.width;
211 p_model_xf.create(p_roi.height, width, p_num_of_feats);
212 p_yf.create(p_roi.height, width, 1);
213 p_xf.create(p_roi.height, width, p_num_of_feats);
216 for (auto scale: p_scales)
217 d.threadctxs.emplace_back(p_roi, p_num_of_feats, 1, scale);
219 d.threadctxs.emplace_back(p_roi, p_num_of_feats * p_num_scales, p_num_scales);
222 p_current_scale = 1.;
224 double min_size_ratio = std::max(5. * p_cell_size / p_windows_size.width, 5. * p_cell_size / p_windows_size.height);
225 double max_size_ratio =
226 std::min(floor((img.cols + p_windows_size.width / 3) / p_cell_size) * p_cell_size / p_windows_size.width,
227 floor((img.rows + p_windows_size.height / 3) / p_cell_size) * p_cell_size / p_windows_size.height);
228 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
229 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
231 std::cout << "init: img size " << img.cols << "x" << img.rows << std::endl;
232 std::cout << "init: win size " << p_windows_size.width << "x" << p_windows_size.height << std::endl;
233 std::cout << "init: FFT size " << p_roi.width << "x" << p_roi.height << std::endl;
234 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
236 p_output_sigma = std::sqrt(p_pose.w * p_pose.h) * p_output_sigma_factor / p_cell_size;
238 fft.init(p_roi.width, p_roi.height, p_num_of_feats, p_num_scales);
239 fft.set_window(MatDynMem(cosine_window_function(p_roi.width, p_roi.height)));
241 // window weights, i.e. labels
242 fft.forward(gaussian_shaped_labels(p_output_sigma, p_roi.width, p_roi.height), p_yf);
245 // train initial model
246 train(input_gray, input_rgb, 1.0);
249 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat &img, int fit_size_x, int fit_size_y)
251 init(img, bbox.get_rect(), fit_size_x, fit_size_y);
254 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
256 if (p_resize_image) {
258 tmp.scale(p_downscale_factor);
261 } else if (p_fit_to_pw2) {
263 tmp.scale_x(p_scale_factor_x);
264 tmp.scale_y(p_scale_factor_y);
273 BBox_c KCF_Tracker::getBBox()
276 tmp.w *= p_current_scale;
277 tmp.h *= p_current_scale;
279 if (p_resize_image) tmp.scale(1 / p_downscale_factor);
281 tmp.scale_x(1 / p_scale_factor_x);
282 tmp.scale_y(1 / p_scale_factor_y);
288 double KCF_Tracker::getFilterResponse() const
290 return this->max_response;
293 void KCF_Tracker::resizeImgs(cv::Mat &input_rgb, cv::Mat &input_gray)
295 if (p_resize_image) {
296 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
297 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
298 } else if (p_fit_to_pw2 && fabs(p_scale_factor_x - 1) > p_floating_error &&
299 fabs(p_scale_factor_y - 1) > p_floating_error) {
300 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
301 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
302 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
304 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
305 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
310 void KCF_Tracker::track(cv::Mat &img)
312 if (m_debug) std::cout << "NEW FRAME" << '\n';
313 cv::Mat input_gray, input_rgb = img.clone();
314 if (img.channels() == 3) {
315 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
316 input_gray.convertTo(input_gray, CV_32FC1);
318 img.convertTo(input_gray, CV_32FC1);
320 // don't need too large image
321 resizeImgs(input_rgb, input_gray);
324 for (auto &it : d.threadctxs)
325 it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
326 scale_track(it, input_rgb, input_gray);
328 for (auto const &it : d.threadctxs)
332 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
333 NORMAL_OMP_PARALLEL_FOR
334 for (uint i = 0; i < d.threadctxs.size(); ++i)
335 scale_track(d.threadctxs[i], input_rgb, input_gray);
339 cv::Point2i *max_response_pt = nullptr;
340 cv::Mat *max_response_map = nullptr;
344 for (uint j = 0; j < d.threadctxs.size(); ++j) {
345 ThreadCtx &it = d.threadctxs[j];
346 if (it.max_response > max_response) {
347 max_response = it.max_response;
348 max_response_pt = &it.max_loc;
349 max_response_map = &it.response;
354 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
355 for (uint j = 0; j < p_scales.size(); ++j) {
356 if (d.threadctxs[0].max_responses[j] > max_response) {
357 max_response = d.threadctxs[0].max_responses[j];
358 max_response_pt = &d.threadctxs[0].max_locs[j];
359 max_response_map = &d.threadctxs[0].response_maps[j];
365 DEBUG_PRINTM(*max_response_map);
366 DEBUG_PRINT(*max_response_pt);
368 // sub pixel quadratic interpolation from neighbours
369 if (max_response_pt->y > max_response_map->rows / 2) // wrap around to negative half-space of vertical axis
370 max_response_pt->y = max_response_pt->y - max_response_map->rows;
371 if (max_response_pt->x > max_response_map->cols / 2) // same for horizontal axis
372 max_response_pt->x = max_response_pt->x - max_response_map->cols;
374 cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
375 DEBUG_PRINT(new_location);
377 if (m_use_subpixel_localization)
378 new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
379 DEBUG_PRINT(new_location);
381 p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
382 p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
384 clamp2(p_pose.cx, 0.0, (img.cols * p_scale_factor_x) - 1);
385 clamp2(p_pose.cy, 0.0, (img.rows * p_scale_factor_y) - 1);
387 clamp2(p_pose.cx, 0.0, img.cols - 1.0);
388 clamp2(p_pose.cy, 0.0, img.rows - 1.0);
391 // sub grid scale interpolation
392 if (m_use_subgrid_scale) {
393 p_current_scale *= sub_grid_scale(max_idx);
395 p_current_scale *= p_scales[max_idx];
398 clamp2(p_current_scale, p_min_max_scale[0], p_min_max_scale[1]);
400 // train at newly estimated target position
401 train(input_rgb, input_gray, p_interp_factor);
404 void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray)
406 // TODO: Move matrices to thread ctx
407 int sizes[3] = {p_num_of_feats, p_windows_size.height, p_windows_size.width};
408 MatDynMem patch_feats(3, sizes, CV_32FC1);
409 MatDynMem temp(3, sizes, CV_32FC1);
412 BIG_BATCH_OMP_PARALLEL_FOR
413 for (uint i = 0; i < p_num_scales; ++i)
416 get_features(patch_feats, input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy,
417 this->p_windows_size.width, this->p_windows_size.height,
418 this->p_current_scale * IF_BIG_BATCH(this->p_scales[i], vars.scale));
421 fft.forward_window(patch_feats, vars.zf, temp);
422 DEBUG_PRINTM(vars.zf);
424 if (m_use_linearkernel) {
425 vars.kzf = vars.zf.mul(p_model_alphaf).sum_over_channels();
427 (*gaussian_correlation)(*this, vars.kzf, vars.zf, this->p_model_xf, this->p_kernel_sigma);
428 DEBUG_PRINTM(this->p_model_alphaf);
429 DEBUG_PRINTM(vars.kzf);
430 vars.kzf = vars.kzf.mul(this->p_model_alphaf);
432 fft.inverse(vars.kzf, vars.response);
434 DEBUG_PRINTM(vars.response);
436 /* target location is at the maximum response. we must take into
437 account the fact that, if the target doesn't move, the peak
438 will appear at the top-left corner, not at the center (this is
439 discussed in the paper). the responses wrap around cyclically. */
441 cv::split(vars.response, vars.response_maps);
443 for (size_t i = 0; i < p_scales.size(); ++i) {
444 double min_val, max_val;
445 cv::Point2i min_loc, max_loc;
446 cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
447 DEBUG_PRINT(max_loc);
448 double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
449 vars.max_responses[i] = max_val * weight;
450 vars.max_locs[i] = max_loc;
455 cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
457 DEBUG_PRINT(vars.max_loc);
459 double weight = vars.scale < 1. ? vars.scale : 1. / vars.scale;
460 vars.max_response = vars.max_val * weight;
465 // ****************************************************************************
467 void KCF_Tracker::get_features(MatDynMem &result_3d, cv::Mat & input_rgb, cv::Mat & input_gray, int cx, int cy, int size_x, int size_y, double scale)
469 assert(result_3d.size[0] == p_num_of_feats);
470 assert(result_3d.size[1] == size_x);
471 assert(result_3d.size[2] == size_y);
473 int size_x_scaled = floor(size_x * scale);
474 int size_y_scaled = floor(size_y * scale);
476 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
477 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
479 // resize to default size
481 // if we downsample use INTER_AREA interpolation
482 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
484 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
487 // get hog(Histogram of Oriented Gradients) features
488 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
490 // get color rgb features (simple r,g,b channels)
491 std::vector<cv::Mat> color_feat;
492 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
493 // resize to default size
495 // if we downsample use INTER_AREA interpolation
496 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_AREA);
498 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_LINEAR);
502 if (m_use_color && input_rgb.channels() == 3) {
503 // use rgb color space
504 cv::Mat patch_rgb_norm;
505 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
506 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
507 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
508 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
509 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
510 cv::split(patch_rgb_norm, rgb);
511 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
514 if (m_use_cnfeat && input_rgb.channels() == 3) {
515 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
516 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
519 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
521 for (uint i = 0; i < hog_feat.size(); ++i) {
522 cv::Mat result_plane(result_3d.dims - 1, result_3d.size + 1, result_3d.cv::Mat::type(), result_3d.ptr<void>(i));
523 result_plane = hog_feat[i];
527 MatDynMem KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
529 MatDynMem labels(dim2, dim1, CV_32FC1);
530 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
531 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
533 double sigma_s = sigma * sigma;
535 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
536 float *row_ptr = labels.ptr<float>(j);
538 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
539 row_ptr[i] = std::exp(-0.5 * (y_s + x * x) / sigma_s); //-1/2*e^((y^2+x^2)/sigma^2)
543 // rotate so that 1 is at top-left corner (see KCF paper for explanation)
544 MatDynMem rot_labels = circshift(labels, range_x[0], range_y[0]);
545 // sanity check, 1 at top left corner
546 assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
551 MatDynMem KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
553 MatDynMem rot_patch(patch.size(), CV_32FC1);
554 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
556 // circular rotate x-axis
558 // move part that does not rotate over the edge
559 cv::Range orig_range(-x_rot, patch.cols);
560 cv::Range rot_range(0, patch.cols - (-x_rot));
561 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
564 orig_range = cv::Range(0, -x_rot);
565 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
566 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
567 } else if (x_rot > 0) {
568 // move part that does not rotate over the edge
569 cv::Range orig_range(0, patch.cols - x_rot);
570 cv::Range rot_range(x_rot, patch.cols);
571 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
574 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
575 rot_range = cv::Range(0, x_rot);
576 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
577 } else { // zero rotation
578 // move part that does not rotate over the edge
579 cv::Range orig_range(0, patch.cols);
580 cv::Range rot_range(0, patch.cols);
581 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
584 // circular rotate y-axis
586 // move part that does not rotate over the edge
587 cv::Range orig_range(-y_rot, patch.rows);
588 cv::Range rot_range(0, patch.rows - (-y_rot));
589 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
592 orig_range = cv::Range(0, -y_rot);
593 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
594 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
595 } else if (y_rot > 0) {
596 // move part that does not rotate over the edge
597 cv::Range orig_range(0, patch.rows - y_rot);
598 cv::Range rot_range(y_rot, patch.rows);
599 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
602 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
603 rot_range = cv::Range(0, y_rot);
604 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
605 } else { // zero rotation
606 // move part that does not rotate over the edge
607 cv::Range orig_range(0, patch.rows);
608 cv::Range rot_range(0, patch.rows);
609 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
615 // hann window actually (Power-of-cosine windows)
616 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
618 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
619 double N_inv = 1. / (static_cast<double>(dim1) - 1.);
620 for (int i = 0; i < dim1; ++i)
621 m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
622 N_inv = 1. / (static_cast<double>(dim2) - 1.);
623 for (int i = 0; i < dim2; ++i)
624 m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
625 cv::Mat ret = m2 * m1;
629 // Returns sub-window of image input centered at [cx, cy] coordinates),
630 // with size [width, height]. If any pixels are outside of the image,
631 // they will replicate the values at the borders.
632 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
636 int x1 = cx - width / 2;
637 int y1 = cy - height / 2;
638 int x2 = cx + width / 2;
639 int y2 = cy + height / 2;
642 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
643 patch.create(height, width, input.type());
644 patch.setTo(double(0.f));
648 int top = 0, bottom = 0, left = 0, right = 0;
650 // fit to image coordinates, set border extensions;
659 if (x2 >= input.cols) {
660 right = x2 - input.cols + width % 2;
665 if (y2 >= input.rows) {
666 bottom = y2 - input.rows + height % 2;
671 if (x2 - x1 == 0 || y2 - y1 == 0)
672 patch = cv::Mat::zeros(height, width, CV_32FC1);
674 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
675 cv::BORDER_REPLICATE);
676 // imshow( "copyMakeBorder", patch);
681 assert(patch.cols == width && patch.rows == height);
686 void KCF_Tracker::GaussianCorrelation::operator()(const KCF_Tracker &kcf, ComplexMat &result, const ComplexMat &xf,
687 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.mul2(yf.conj());
697 kcf.fft.inverse(xyf, ifft_res);
699 cuda_gaussian_correlation(ifft_res.deviceMem(), k.deviceMem(), xf_sqr_norm.deviceMem(),
700 auto_correlation ? xf_sqr_norm.deviceMem() : yf_sqr_norm.deviceMem(), sigma,
701 xf.n_channels, xf.n_scales, kcf.p_roi.height, kcf.p_roi.width);
703 // ifft2 and sum over 3rd dimension, we dont care about individual channels
704 //DEBUG_PRINTM(vars.ifft2_res);
706 if (xf.channels() != p_num_scales * p_num_of_feats)
707 xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
709 xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
711 for (int y = 0; y < vars.ifft2_res.rows; ++y) {
712 float *row_ptr = vars.ifft2_res.ptr<float>(y);
713 float *row_ptr_sum = xy_sum.ptr<float>(y);
714 for (int x = 0; x < vars.ifft2_res.cols; ++x) {
715 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
716 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
717 row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
718 (row_ptr + x * vars.ifft2_res.channels() +
719 (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
724 DEBUG_PRINTM(xy_sum);
726 std::vector<cv::Mat> scales;
727 cv::split(xy_sum, scales);
729 float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
730 for (uint i = 0; i < xf.n_scales; ++i) {
731 cv::Mat in_roi(vars.in_all, cv::Rect(0, i * scales[0].rows, scales[0].cols, scales[0].rows));
733 -1. / (sigma * sigma) *
734 cv::max((double(vars.gc.xf_sqr_norm.hostMem()[i] + vars.gc.yf_sqr_norm.hostMem()[0]) - 2 * scales[i]) * double(numel_xf_inv), 0),
736 DEBUG_PRINTM(in_roi);
739 kcf.fft.forward(k, result);
743 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
747 if (x < 0) x = response.cols + x;
748 if (y < 0) y = response.rows + y;
749 if (x >= response.cols) x = x - response.cols;
750 if (y >= response.rows) y = y - response.rows;
752 return response.at<float>(y, x);
755 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response)
757 // find neighbourhood of max_loc (response is circular)
761 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);
762 cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
763 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);
766 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
767 cv::Mat A = (cv::Mat_<float>(9, 6) <<
768 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
769 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
770 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
771 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
772 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
773 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
774 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
775 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
776 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);
777 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
778 get_response_circular(p1, response),
779 get_response_circular(p2, response),
780 get_response_circular(p3, response),
781 get_response_circular(p4, response),
782 get_response_circular(p5, response),
783 get_response_circular(p6, response),
784 get_response_circular(p7, response),
785 get_response_circular(p8, response),
786 get_response_circular(max_loc, response));
789 cv::solve(A, fval, x, cv::DECOMP_SVD);
791 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);
793 cv::Point2f sub_peak(max_loc.x, max_loc.y);
794 if (b > 0 || b < 0) {
795 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
796 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
802 double KCF_Tracker::sub_grid_scale(uint index)
805 if (index >= p_scales.size()) {
806 // interpolate from all values
807 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
808 A.create(p_scales.size(), 3, CV_32FC1);
809 fval.create(p_scales.size(), 1, CV_32FC1);
810 for (size_t i = 0; i < p_scales.size(); ++i) {
811 A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
812 A.at<float>(i, 1) = float(p_scales[i]);
813 A.at<float>(i, 2) = 1;
815 fval.at<float>(i) = d.threadctxs.back().max_responses[i];
817 fval.at<float>(i) = d.threadctxs[i].max_response;
821 // only from neighbours
822 if (index == 0 || index == p_scales.size() - 1)
823 return p_scales[index];
825 A = (cv::Mat_<float>(3, 3) <<
826 p_scales[index - 1] * p_scales[index - 1], p_scales[index - 1], 1,
827 p_scales[index + 0] * p_scales[index + 0], p_scales[index + 0], 1,
828 p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
830 fval = (cv::Mat_<float>(3, 1) <<
831 d.threadctxs.back().max_responses[index - 1],
832 d.threadctxs.back().max_responses[index + 0],
833 d.threadctxs.back().max_responses[index + 1]);
835 fval = (cv::Mat_<float>(3, 1) <<
836 d.threadctxs[index - 1].max_response,
837 d.threadctxs[index + 0].max_response,
838 d.threadctxs[index + 1].max_response);
843 cv::solve(A, fval, x, cv::DECOMP_SVD);
844 float a = x.at<float>(0), b = x.at<float>(1);
845 double scale = p_scales[index];
847 scale = -b / (2 * a);