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::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int fit_size_y)
66 // check boundary, enforce min size
67 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
69 if (x2 > img.cols - 1) x2 = img.cols - 1;
71 if (y2 > img.rows - 1) y2 = img.rows - 1;
73 if (x2 - x1 < 2 * p_cell_size) {
74 double diff = (2 * p_cell_size - x2 + x1) / 2.;
75 if (x1 - diff >= 0 && x2 + diff < img.cols) {
78 } else if (x1 - 2 * diff >= 0) {
84 if (y2 - y1 < 2 * p_cell_size) {
85 double diff = (2 * p_cell_size - y2 + y1) / 2.;
86 if (y1 - diff >= 0 && y2 + diff < img.rows) {
89 } else if (y1 - 2 * diff >= 0) {
98 p_pose.cx = x1 + p_pose.w / 2.;
99 p_pose.cy = y1 + p_pose.h / 2.;
101 cv::Mat input_gray, input_rgb = img.clone();
102 if (img.channels() == 3) {
103 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
104 input_gray.convertTo(input_gray, CV_32FC1);
106 img.convertTo(input_gray, CV_32FC1);
108 // don't need too large image
109 if (p_pose.w * p_pose.h > 100. * 100. && (fit_size_x == -1 || fit_size_y == -1)) {
110 std::cout << "resizing image by factor of " << 1 / p_downscale_factor << std::endl;
111 p_resize_image = true;
112 p_pose.scale(p_downscale_factor);
113 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
114 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
115 } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
116 if (fit_size_x % p_cell_size != 0 || fit_size_y % p_cell_size != 0) {
117 std::cerr << "Error: Fit size is not multiple of HOG cell size (" << p_cell_size << ")" << std::endl;
118 std::exit(EXIT_FAILURE);
120 p_scale_factor_x = (double)fit_size_x / round(p_pose.w * (1. + p_padding));
121 p_scale_factor_y = (double)fit_size_y / round(p_pose.h * (1. + p_padding));
122 std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x << " and verticaly by factor of "
123 << p_scale_factor_y << std::endl;
125 p_pose.scale_x(p_scale_factor_x);
126 p_pose.scale_y(p_scale_factor_y);
127 if (fabs(p_scale_factor_x - 1) > p_floating_error || fabs(p_scale_factor_y - 1) > p_floating_error) {
128 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
129 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
130 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
132 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
133 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
138 // compute win size + fit to fhog cell size
139 p_windows_size.width = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
140 p_windows_size.height = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
141 p_roi.width = p_windows_size.width / p_cell_size;
142 p_roi.height = p_windows_size.height / p_cell_size;
146 for (int i = -int(p_num_scales) / 2; i <= int(p_num_scales) / 2; ++i)
147 p_scales.push_back(std::pow(p_scale_step, i));
149 p_scales.push_back(1.);
152 if (p_roi.height * (p_roi.width / 2 + 1) > 1024) {
153 std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
154 "the window dimensions so its size is less or equal to "
155 << 1024 * p_cell_size * p_cell_size * 2 + 1
156 << " pixels . Currently the size of the window is: " << p_windows_size.width << "x" << p_windows_size.height
157 << " which is " << p_windows_size.width * p_windows_size.height << " pixels. " << std::endl;
158 std::exit(EXIT_FAILURE);
161 if (m_use_linearkernel) {
162 std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
163 std::exit(EXIT_FAILURE);
165 CudaSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost));
166 p_rot_labels_data = DynMem(p_roi.width * p_roi.height * sizeof(float));
167 p_rot_labels = cv::Mat(p_roi, CV_32FC1, p_rot_labels_data.hostMem());
169 p_xf.create(p_roi.height, p_roi.height / 2 + 1, p_num_of_feats);
172 #if defined(CUFFT) || defined(FFTW)
173 uint width = p_roi.width / 2 + 1;
175 uint width = p_roi.width;
177 p_model_xf.create(p_roi.height, width, p_num_of_feats);
178 p_yf.create(p_roi.height, width, 1);
179 p_xf.create(p_roi.height, width, p_num_of_feats);
182 for (auto scale: p_scales)
183 d.threadctxs.emplace_back(p_roi, p_num_of_feats, 1, scale);
185 d.threadctxs.emplace_back(p_roi, p_num_of_feats * p_num_scales, p_num_scales);
188 p_current_scale = 1.;
190 double min_size_ratio = std::max(5. * p_cell_size / p_windows_size.width, 5. * p_cell_size / p_windows_size.height);
191 double max_size_ratio =
192 std::min(floor((img.cols + p_windows_size.width / 3) / p_cell_size) * p_cell_size / p_windows_size.width,
193 floor((img.rows + p_windows_size.height / 3) / p_cell_size) * p_cell_size / p_windows_size.height);
194 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
195 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
197 std::cout << "init: img size " << img.cols << "x" << img.rows << std::endl;
198 std::cout << "init: win size " << p_windows_size.width << "x" << p_windows_size.height << std::endl;
199 std::cout << "init: FFT size " << p_roi.width << "x" << p_roi.height << std::endl;
200 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
202 p_output_sigma = std::sqrt(p_pose.w * p_pose.h) * p_output_sigma_factor / p_cell_size;
204 fft.init(p_roi.width, p_roi.height, p_num_of_feats, p_num_scales);
205 fft.set_window(cosine_window_function(p_roi.width, p_roi.height));
207 // window weights, i.e. labels
208 fft.forward(gaussian_shaped_labels(p_output_sigma, p_roi.width, p_roi.height), p_yf);
211 // obtain a sub-window for training initial model
212 int sizes[3] = {p_num_of_feats, p_windows_size.height, p_windows_size.width};
213 MatDynMem patch_feats(3, sizes, CV_32FC1);
214 MatDynMem temp(3, tmp, CV_32FC1);
215 get_features(features, input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size.width, p_windows_size.height);
216 fft.forward_window(patch_feats, p_model_xf);
217 DEBUG_PRINTM(p_model_xf);
219 if (m_use_linearkernel) {
220 ComplexMat xfconj = p_model_xf.conj();
221 p_model_alphaf_num = xfconj.mul(p_yf);
222 p_model_alphaf_den = (p_model_xf * xfconj);
224 // Kernel Ridge Regression, calculate alphas (in Fourier domain)
225 uint num_scales = BIG_BATCH_MODE ? p_num_scales : 1;
226 cv::Size sz(Fft::freq_size(p_roi));
227 GaussianCorrelation gaussian_correlation(sz, num_scales);
228 ComplexMat kf(sz.height, sz.width, num_scales);
229 gaussian_correlation(*this, kf, p_model_xf, p_model_xf, p_kernel_sigma, true);
231 p_model_alphaf_num = p_yf * kf;
232 DEBUG_PRINTM(p_model_alphaf_num);
233 p_model_alphaf_den = kf * (kf + p_lambda);
234 DEBUG_PRINTM(p_model_alphaf_den);
236 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
237 DEBUG_PRINTM(p_model_alphaf);
238 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
241 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat &img, int fit_size_x, int fit_size_y)
243 init(img, bbox.get_rect(), fit_size_x, fit_size_y);
246 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
248 if (p_resize_image) {
250 tmp.scale(p_downscale_factor);
253 } else if (p_fit_to_pw2) {
255 tmp.scale_x(p_scale_factor_x);
256 tmp.scale_y(p_scale_factor_y);
265 BBox_c KCF_Tracker::getBBox()
268 tmp.w *= p_current_scale;
269 tmp.h *= p_current_scale;
271 if (p_resize_image) tmp.scale(1 / p_downscale_factor);
273 tmp.scale_x(1 / p_scale_factor_x);
274 tmp.scale_y(1 / p_scale_factor_y);
280 double KCF_Tracker::getFilterResponse() const
282 return this->max_response;
285 void KCF_Tracker::track(cv::Mat &img)
287 if (m_debug) std::cout << "NEW FRAME" << '\n';
288 cv::Mat input_gray, input_rgb = img.clone();
289 if (img.channels() == 3) {
290 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
291 input_gray.convertTo(input_gray, CV_32FC1);
293 img.convertTo(input_gray, CV_32FC1);
295 // don't need too large image
296 if (p_resize_image) {
297 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
298 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
299 } else if (p_fit_to_pw2 && fabs(p_scale_factor_x - 1) > p_floating_error &&
300 fabs(p_scale_factor_y - 1) > p_floating_error) {
301 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
302 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
303 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
305 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
306 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
311 ThreadCtx *max = nullptr;
312 cv::Point2i *max_response_pt = nullptr;
313 cv::Mat *max_response_map = nullptr;
316 for (auto &it : d.threadctxs)
317 it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
318 scale_track(it, input_rgb, input_gray);
320 for (auto const &it : d.threadctxs)
324 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
325 NORMAL_OMP_PARALLEL_FOR
326 for (uint i = 0; i < d.threadctxs.size(); ++i)
327 scale_track(d.threadctxs[i], input_rgb, input_gray);
331 for (auto &it : d.threadctxs) {
332 if (it.max_response > max_response) {
333 max_response = it.max_response;
334 max_response_pt = &it.max_loc;
335 max_response_map = &it.response;
340 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
341 for (uint j = 0; j < p_scales.size(); ++j) {
342 if (d.threadctxs[0].max_responses[j] > max_response) {
343 max_response = d.threadctxs[0].max_responses[j];
344 max_response_pt = &d.threadctxs[0].max_locs[j];
345 max_response_map = &d.threadctxs[0].response_maps[j];
346 max = &d.threadctxs[0];
351 DEBUG_PRINTM(*max_response_map);
352 DEBUG_PRINT(*max_response_pt);
354 // sub pixel quadratic interpolation from neighbours
355 if (max_response_pt->y > max_response_map->rows / 2) // wrap around to negative half-space of vertical axis
356 max_response_pt->y = max_response_pt->y - max_response_map->rows;
357 if (max_response_pt->x > max_response_map->cols / 2) // same for horizontal axis
358 max_response_pt->x = max_response_pt->x - max_response_map->cols;
360 cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
361 DEBUG_PRINT(new_location);
363 if (m_use_subpixel_localization)
364 new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
365 DEBUG_PRINT(new_location);
367 p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
368 p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
370 clamp2(p_pose.cx, 0.0, (img.cols * p_scale_factor_x) - 1);
371 clamp2(p_pose.cy, 0.0, (img.rows * p_scale_factor_y) - 1);
373 clamp2(p_pose.cx, 0.0, img.cols - 1.0);
374 clamp2(p_pose.cy, 0.0, img.rows - 1.0);
377 // sub grid scale interpolation
378 if (m_use_subgrid_scale) {
379 auto it = std::find_if(d.threadctxs.begin(), d.threadctxs.end(), [max](ThreadCtx &ctx) { return &ctx == max; });
380 p_current_scale *= sub_grid_scale(std::distance(d.threadctxs.begin(), it));
382 p_current_scale *= max->scale;
385 clamp2(p_current_scale, p_min_max_scale[0], p_min_max_scale[1]);
387 ThreadCtx &ctx = d.threadctxs.front();
388 // obtain a subwindow for training at newly estimated target position
389 std::vector<cv::Mat> patch_feats = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy,
390 p_windows_size.width, p_windows_size.height,
392 fft.forward_window(patch_feats, p_xf, ctx.fw_all,
393 m_use_cuda ? ctx.data_features.deviceMem() : nullptr);
395 // subsequent frames, interpolate model
396 p_model_xf = p_model_xf * (1. - p_interp_factor) + p_xf * p_interp_factor;
398 ComplexMat alphaf_num, alphaf_den;
400 if (m_use_linearkernel) {
401 ComplexMat xfconj = p_xf.conj();
402 alphaf_num = xfconj.mul(p_yf);
403 alphaf_den = (p_xf * xfconj);
405 // Kernel Ridge Regression, calculate alphas (in Fourier domain)
406 const uint num_scales = BIG_BATCH_MODE ? p_num_scales : 1;
407 cv::Size sz(Fft::freq_size(p_roi));
408 ComplexMat kf(sz.height, sz.width, num_scales);
409 (*gaussian_correlation)(*this, kf, p_xf, p_xf, p_kernel_sigma, true);
410 // ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
411 // p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
412 alphaf_num = p_yf * kf;
413 alphaf_den = kf * (kf + p_lambda);
416 p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
417 p_model_alphaf_den = p_model_alphaf_den * (1. - p_interp_factor) + alphaf_den * p_interp_factor;
418 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
421 void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray)
423 std::vector<cv::Mat> patch_feats;
424 if (BIG_BATCH_MODE) {
425 BIG_BATCH_OMP_PARALLEL_FOR
426 for (uint i = 0; i < p_num_scales; ++i) {
427 patch_feats = get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy,
428 this->p_windows_size.width, this->p_windows_size.height,
429 this->p_current_scale * this->p_scales[i]);
432 patch_feats = get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy,
433 this->p_windows_size.width, this->p_windows_size.height,
434 this->p_current_scale * vars.scale);
437 fft.forward_window(patch_feats, vars.zf, vars.fw_all, m_use_cuda ? vars.data_features.deviceMem() : nullptr);
438 DEBUG_PRINTM(vars.zf);
440 if (m_use_linearkernel) {
441 vars.kzf = BIG_BATCH_MODE ? (vars.zf.mul2(this->p_model_alphaf)).sum_over_channels()
442 : (p_model_alphaf * vars.zf).sum_over_channels();
443 fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr);
445 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
446 gaussian_correlation(vars, vars.zf, this->p_model_xf, this->p_kernel_sigma);
447 vars.kzf = vars.model_alphaf * vars.kzf;
449 vars.gaussian_correlation(*this, vars.kzf, vars.zf, this->p_model_xf, this->p_kernel_sigma);
450 DEBUG_PRINTM(this->p_model_alphaf);
451 DEBUG_PRINTM(vars.kzf);
452 vars.kzf = BIG_BATCH_MODE ? vars.kzf.mul(this->p_model_alphaf) : this->p_model_alphaf * vars.kzf;
454 fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr);
457 DEBUG_PRINTM(vars.response);
459 /* target location is at the maximum response. we must take into
460 account the fact that, if the target doesn't move, the peak
461 will appear at the top-left corner, not at the center (this is
462 discussed in the paper). the responses wrap around cyclically. */
464 cv::split(vars.response, vars.response_maps);
466 for (size_t i = 0; i < p_scales.size(); ++i) {
467 double min_val, max_val;
468 cv::Point2i min_loc, max_loc;
469 cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
470 DEBUG_PRINT(max_loc);
471 double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
472 vars.max_responses[i] = max_val * weight;
473 vars.max_locs[i] = max_loc;
478 cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
480 DEBUG_PRINT(vars.max_loc);
482 double weight = vars.scale < 1. ? vars.scale : 1. / vars.scale;
483 vars.max_response = vars.max_val * weight;
488 // ****************************************************************************
490 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)
492 assert(result_3d.size[0] == num_of_feats());
493 assert(result_3d.size[1] == size_x);
494 assert(result_3d.size[2] == size_y);
496 int size_x_scaled = floor(size_x * scale);
497 int size_y_scaled = floor(size_y * scale);
499 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
500 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
502 // resize to default size
504 // if we downsample use INTER_AREA interpolation
505 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
507 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
510 // get hog(Histogram of Oriented Gradients) features
511 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
513 // get color rgb features (simple r,g,b channels)
514 std::vector<cv::Mat> color_feat;
515 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
516 // resize to default size
518 // if we downsample use INTER_AREA interpolation
519 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_AREA);
521 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_LINEAR);
525 if (m_use_color && input_rgb.channels() == 3) {
526 // use rgb color space
527 cv::Mat patch_rgb_norm;
528 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
529 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
530 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
531 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
532 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
533 cv::split(patch_rgb_norm, rgb);
534 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
537 if (m_use_cnfeat && input_rgb.channels() == 3) {
538 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
539 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
542 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
546 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
548 cv::Mat labels(dim2, dim1, CV_32FC1);
549 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
550 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
552 double sigma_s = sigma * sigma;
554 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
555 float *row_ptr = labels.ptr<float>(j);
557 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
558 row_ptr[i] = std::exp(-0.5 * (y_s + x * x) / sigma_s); //-1/2*e^((y^2+x^2)/sigma^2)
562 // rotate so that 1 is at top-left corner (see KCF paper for explanation)
564 cv::Mat tmp = circshift(labels, range_x[0], range_y[0]);
565 tmp.copyTo(p_rot_labels);
567 assert(p_rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
570 cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
571 // sanity check, 1 at top left corner
572 assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
578 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
580 cv::Mat rot_patch(patch.size(), CV_32FC1);
581 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
583 // circular rotate x-axis
585 // move part that does not rotate over the edge
586 cv::Range orig_range(-x_rot, patch.cols);
587 cv::Range rot_range(0, patch.cols - (-x_rot));
588 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
591 orig_range = cv::Range(0, -x_rot);
592 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
593 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
594 } else if (x_rot > 0) {
595 // move part that does not rotate over the edge
596 cv::Range orig_range(0, patch.cols - x_rot);
597 cv::Range rot_range(x_rot, patch.cols);
598 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
601 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
602 rot_range = cv::Range(0, x_rot);
603 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
604 } else { // zero rotation
605 // move part that does not rotate over the edge
606 cv::Range orig_range(0, patch.cols);
607 cv::Range rot_range(0, patch.cols);
608 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
611 // circular rotate y-axis
613 // move part that does not rotate over the edge
614 cv::Range orig_range(-y_rot, patch.rows);
615 cv::Range rot_range(0, patch.rows - (-y_rot));
616 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
619 orig_range = cv::Range(0, -y_rot);
620 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
621 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
622 } else if (y_rot > 0) {
623 // move part that does not rotate over the edge
624 cv::Range orig_range(0, patch.rows - y_rot);
625 cv::Range rot_range(y_rot, patch.rows);
626 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
629 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
630 rot_range = cv::Range(0, y_rot);
631 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
632 } else { // zero rotation
633 // move part that does not rotate over the edge
634 cv::Range orig_range(0, patch.rows);
635 cv::Range rot_range(0, patch.rows);
636 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
642 // hann window actually (Power-of-cosine windows)
643 MatDynMem KCF_Tracker::cosine_window_function(int dim1, int dim2)
645 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
646 double N_inv = 1. / (static_cast<double>(dim1) - 1.);
647 for (int i = 0; i < dim1; ++i)
648 m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
649 N_inv = 1. / (static_cast<double>(dim2) - 1.);
650 for (int i = 0; i < dim2; ++i)
651 m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
652 MatDynMem ret = m2 * m1;
656 // Returns sub-window of image input centered at [cx, cy] coordinates),
657 // with size [width, height]. If any pixels are outside of the image,
658 // they will replicate the values at the borders.
659 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
663 int x1 = cx - width / 2;
664 int y1 = cy - height / 2;
665 int x2 = cx + width / 2;
666 int y2 = cy + height / 2;
669 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
670 patch.create(height, width, input.type());
671 patch.setTo(double(0.f));
675 int top = 0, bottom = 0, left = 0, right = 0;
677 // fit to image coordinates, set border extensions;
686 if (x2 >= input.cols) {
687 right = x2 - input.cols + width % 2;
692 if (y2 >= input.rows) {
693 bottom = y2 - input.rows + height % 2;
698 if (x2 - x1 == 0 || y2 - y1 == 0)
699 patch = cv::Mat::zeros(height, width, CV_32FC1);
701 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
702 cv::BORDER_REPLICATE);
703 // imshow( "copyMakeBorder", patch);
708 assert(patch.cols == width && patch.rows == height);
713 void KCF_Tracker::GaussianCorrelation::operator()(const KCF_Tracker &kcf, ComplexMat &result, const ComplexMat &xf,
714 const ComplexMat &yf, double sigma, bool auto_correlation)
716 xf.sqr_norm(xf_sqr_norm);
717 if (auto_correlation) {
718 yf_sqr_norm = xf_sqr_norm;
720 yf.sqr_norm(yf_sqr_norm);
722 xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
724 kcf.fft.inverse(xyf, vars.ifft2_res, m_use_cuda ? vars.data_i_features.deviceMem() : nullptr);
726 cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(),
727 vars.gc.xf_sqr_norm.deviceMem(), vars.gc.xf_sqr_norm.deviceMem(), sigma, xf.n_channels,
728 xf.n_scales, p_roi.height, p_roi.width);
730 // ifft2 and sum over 3rd dimension, we dont care about individual channels
731 //DEBUG_PRINTM(vars.ifft2_res);
733 if (xf.channels() != p_num_scales * p_num_of_feats)
734 xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
736 xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
738 for (int y = 0; y < vars.ifft2_res.rows; ++y) {
739 float *row_ptr = vars.ifft2_res.ptr<float>(y);
740 float *row_ptr_sum = xy_sum.ptr<float>(y);
741 for (int x = 0; x < vars.ifft2_res.cols; ++x) {
742 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
743 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
744 row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
745 (row_ptr + x * vars.ifft2_res.channels() +
746 (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
751 DEBUG_PRINTM(xy_sum);
753 std::vector<cv::Mat> scales;
754 cv::split(xy_sum, scales);
756 float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
757 for (uint i = 0; i < xf.n_scales; ++i) {
758 cv::Mat in_roi(vars.in_all, cv::Rect(0, i * scales[0].rows, scales[0].cols, scales[0].rows));
760 -1. / (sigma * sigma) *
761 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),
763 DEBUG_PRINTM(in_roi);
766 DEBUG_PRINTM(vars.in_all);
767 fft.forward(vars.in_all, auto_correlation ? vars.kf : vars.kzf, m_use_cuda ? vars.gauss_corr_res.deviceMem() : nullptr);
771 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
775 if (x < 0) x = response.cols + x;
776 if (y < 0) y = response.rows + y;
777 if (x >= response.cols) x = x - response.cols;
778 if (y >= response.rows) y = y - response.rows;
780 return response.at<float>(y, x);
783 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response)
785 // find neighbourhood of max_loc (response is circular)
789 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);
790 cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
791 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);
794 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
795 cv::Mat A = (cv::Mat_<float>(9, 6) <<
796 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
797 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
798 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
799 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
800 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
801 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
802 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
803 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
804 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);
805 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
806 get_response_circular(p1, response),
807 get_response_circular(p2, response),
808 get_response_circular(p3, response),
809 get_response_circular(p4, response),
810 get_response_circular(p5, response),
811 get_response_circular(p6, response),
812 get_response_circular(p7, response),
813 get_response_circular(p8, response),
814 get_response_circular(max_loc, response));
817 cv::solve(A, fval, x, cv::DECOMP_SVD);
819 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);
821 cv::Point2f sub_peak(max_loc.x, max_loc.y);
822 if (b > 0 || b < 0) {
823 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
824 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
830 double KCF_Tracker::sub_grid_scale(uint index)
833 if (index >= p_scales.size()) {
834 // interpolate from all values
835 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
836 A.create(p_scales.size(), 3, CV_32FC1);
837 fval.create(p_scales.size(), 1, CV_32FC1);
838 for (size_t i = 0; i < p_scales.size(); ++i) {
839 A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
840 A.at<float>(i, 1) = float(p_scales[i]);
841 A.at<float>(i, 2) = 1;
843 fval.at<float>(i) = d.threadctxs.back().max_responses[i];
845 fval.at<float>(i) = d.threadctxs[i].max_response;
849 // only from neighbours
850 if (index == 0 || index == p_scales.size() - 1)
851 return p_scales[index];
853 A = (cv::Mat_<float>(3, 3) <<
854 p_scales[index - 1] * p_scales[index - 1], p_scales[index - 1], 1,
855 p_scales[index + 0] * p_scales[index + 0], p_scales[index + 0], 1,
856 p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
858 fval = (cv::Mat_<float>(3, 1) <<
859 d.threadctxs.back().max_responses[index - 1],
860 d.threadctxs.back().max_responses[index + 0],
861 d.threadctxs.back().max_responses[index + 1]);
863 fval = (cv::Mat_<float>(3, 1) <<
864 d.threadctxs[index - 1].max_response,
865 d.threadctxs[index + 0].max_response,
866 d.threadctxs[index + 1].max_response);
871 cv::solve(A, fval, x, cv::DECOMP_SVD);
872 float a = x.at<float>(0), b = x.at<float>(1);
873 double scale = p_scales[index];
875 scale = -b / (2 * a);