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::findMaxReponse(uint &max_idx, cv::Point2f &new_location) const
314 for (uint j = 0; j < d.threadctxs.size(); ++j) {
315 if (d.threadctxs[j].max_response > max) {
316 max = d.threadctxs[j].max_response;
321 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
322 for (uint j = 0; j < p_scales.size(); ++j) {
323 if (d.threadctxs[0].max_responses[j] > max) {
324 max = d.threadctxs[0].max_responses[j];
329 cv::Point2i &max_response_pt = IF_BIG_BATCH(d.threadctxs[0].max_locs[max_idx], d.threadctxs[max_idx].max_loc);
330 cv::Mat &max_response_map = IF_BIG_BATCH(d.threadctxs[0].response_maps[max_idx], d.threadctxs[max_idx].response);
332 DEBUG_PRINTM(max_response_map);
333 DEBUG_PRINT(max_response_pt);
335 // sub pixel quadratic interpolation from neighbours
336 if (max_response_pt.y > max_response_map.rows / 2) // wrap around to negative half-space of vertical axis
337 max_response_pt.y = max_response_pt.y - max_response_map.rows;
338 if (max_response_pt.x > max_response_map.cols / 2) // same for horizontal axis
339 max_response_pt.x = max_response_pt.x - max_response_map.cols;
342 if (m_use_subpixel_localization) {
343 new_location = sub_pixel_peak(max_response_pt, max_response_map);
345 new_location = max_response_pt;
347 DEBUG_PRINT(new_location);
350 void KCF_Tracker::track(cv::Mat &img)
352 if (m_debug) std::cout << "NEW FRAME" << '\n';
353 cv::Mat input_gray, input_rgb = img.clone();
354 if (img.channels() == 3) {
355 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
356 input_gray.convertTo(input_gray, CV_32FC1);
358 img.convertTo(input_gray, CV_32FC1);
360 // don't need too large image
361 resizeImgs(input_rgb, input_gray);
364 for (auto &it : d.threadctxs)
365 it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
366 scale_track(it, input_rgb, input_gray);
368 for (auto const &it : d.threadctxs)
372 // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
373 NORMAL_OMP_PARALLEL_FOR
374 for (uint i = 0; i < d.threadctxs.size(); ++i)
375 scale_track(d.threadctxs[i], input_rgb, input_gray);
378 cv::Point2f new_location;
380 findMaxReponse(max_idx, new_location);
382 p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
383 p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
385 clamp2(p_pose.cx, 0.0, (img.cols * p_scale_factor_x) - 1);
386 clamp2(p_pose.cy, 0.0, (img.rows * p_scale_factor_y) - 1);
388 clamp2(p_pose.cx, 0.0, img.cols - 1.0);
389 clamp2(p_pose.cy, 0.0, img.rows - 1.0);
392 // sub grid scale interpolation
393 if (m_use_subgrid_scale) {
394 p_current_scale *= sub_grid_scale(max_idx);
396 p_current_scale *= p_scales[max_idx];
399 clamp2(p_current_scale, p_min_max_scale[0], p_min_max_scale[1]);
401 // train at newly estimated target position
402 train(input_rgb, input_gray, p_interp_factor);
405 void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray)
407 // TODO: Move matrices to thread ctx
408 int sizes[3] = {p_num_of_feats, p_windows_size.height, p_windows_size.width};
409 MatDynMem patch_feats(3, sizes, CV_32FC1);
410 MatDynMem temp(3, sizes, CV_32FC1);
413 BIG_BATCH_OMP_PARALLEL_FOR
414 for (uint i = 0; i < p_num_scales; ++i)
417 get_features(patch_feats, input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy,
418 this->p_windows_size.width, this->p_windows_size.height,
419 this->p_current_scale * IF_BIG_BATCH(this->p_scales[i], vars.scale));
422 fft.forward_window(patch_feats, vars.zf, temp);
423 DEBUG_PRINTM(vars.zf);
425 if (m_use_linearkernel) {
426 vars.kzf = vars.zf.mul(p_model_alphaf).sum_over_channels();
428 (*gaussian_correlation)(*this, vars.kzf, vars.zf, this->p_model_xf, this->p_kernel_sigma);
429 DEBUG_PRINTM(this->p_model_alphaf);
430 DEBUG_PRINTM(vars.kzf);
431 vars.kzf = vars.kzf.mul(this->p_model_alphaf);
433 fft.inverse(vars.kzf, vars.response);
435 DEBUG_PRINTM(vars.response);
437 /* target location is at the maximum response. we must take into
438 account the fact that, if the target doesn't move, the peak
439 will appear at the top-left corner, not at the center (this is
440 discussed in the paper). the responses wrap around cyclically. */
442 cv::split(vars.response, vars.response_maps);
444 for (size_t i = 0; i < p_scales.size(); ++i) {
445 double min_val, max_val;
446 cv::Point2i min_loc, max_loc;
447 cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
448 DEBUG_PRINT(max_loc);
449 double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
450 vars.max_responses[i] = max_val * weight;
451 vars.max_locs[i] = max_loc;
456 cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
458 DEBUG_PRINT(vars.max_loc);
460 double weight = vars.scale < 1. ? vars.scale : 1. / vars.scale;
461 vars.max_response = vars.max_val * weight;
466 // ****************************************************************************
468 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)
470 assert(result_3d.size[0] == p_num_of_feats);
471 assert(result_3d.size[1] == size_x);
472 assert(result_3d.size[2] == size_y);
474 int size_x_scaled = floor(size_x * scale);
475 int size_y_scaled = floor(size_y * scale);
477 cv::Mat patch_gray = get_subwindow(input_gray, cx, cy, size_x_scaled, size_y_scaled);
478 cv::Mat patch_rgb = get_subwindow(input_rgb, cx, cy, size_x_scaled, size_y_scaled);
480 // resize to default size
482 // if we downsample use INTER_AREA interpolation
483 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
485 cv::resize(patch_gray, patch_gray, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
488 // get hog(Histogram of Oriented Gradients) features
489 std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
491 // get color rgb features (simple r,g,b channels)
492 std::vector<cv::Mat> color_feat;
493 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
494 // resize to default size
496 // if we downsample use INTER_AREA interpolation
497 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_AREA);
499 cv::resize(patch_rgb, patch_rgb, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_LINEAR);
503 if (m_use_color && input_rgb.channels() == 3) {
504 // use rgb color space
505 cv::Mat patch_rgb_norm;
506 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
507 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
508 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
509 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
510 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
511 cv::split(patch_rgb_norm, rgb);
512 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
515 if (m_use_cnfeat && input_rgb.channels() == 3) {
516 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
517 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
520 hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
522 for (uint i = 0; i < hog_feat.size(); ++i) {
523 cv::Mat result_plane(result_3d.dims - 1, result_3d.size + 1, result_3d.cv::Mat::type(), result_3d.ptr<void>(i));
524 result_plane = hog_feat[i];
528 MatDynMem KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
530 MatDynMem labels(dim2, dim1, CV_32FC1);
531 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
532 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
534 double sigma_s = sigma * sigma;
536 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
537 float *row_ptr = labels.ptr<float>(j);
539 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
540 row_ptr[i] = std::exp(-0.5 * (y_s + x * x) / sigma_s); //-1/2*e^((y^2+x^2)/sigma^2)
544 // rotate so that 1 is at top-left corner (see KCF paper for explanation)
545 MatDynMem rot_labels = circshift(labels, range_x[0], range_y[0]);
546 // sanity check, 1 at top left corner
547 assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
552 MatDynMem KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
554 MatDynMem rot_patch(patch.size(), CV_32FC1);
555 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
557 // circular rotate x-axis
559 // move part that does not rotate over the edge
560 cv::Range orig_range(-x_rot, patch.cols);
561 cv::Range rot_range(0, patch.cols - (-x_rot));
562 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
565 orig_range = cv::Range(0, -x_rot);
566 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
567 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
568 } else if (x_rot > 0) {
569 // move part that does not rotate over the edge
570 cv::Range orig_range(0, patch.cols - x_rot);
571 cv::Range rot_range(x_rot, patch.cols);
572 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
575 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
576 rot_range = cv::Range(0, x_rot);
577 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
578 } else { // zero rotation
579 // move part that does not rotate over the edge
580 cv::Range orig_range(0, patch.cols);
581 cv::Range rot_range(0, patch.cols);
582 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
585 // circular rotate y-axis
587 // move part that does not rotate over the edge
588 cv::Range orig_range(-y_rot, patch.rows);
589 cv::Range rot_range(0, patch.rows - (-y_rot));
590 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
593 orig_range = cv::Range(0, -y_rot);
594 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
595 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
596 } else if (y_rot > 0) {
597 // move part that does not rotate over the edge
598 cv::Range orig_range(0, patch.rows - y_rot);
599 cv::Range rot_range(y_rot, patch.rows);
600 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
603 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
604 rot_range = cv::Range(0, y_rot);
605 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
606 } else { // zero rotation
607 // move part that does not rotate over the edge
608 cv::Range orig_range(0, patch.rows);
609 cv::Range rot_range(0, patch.rows);
610 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
616 // hann window actually (Power-of-cosine windows)
617 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
619 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
620 double N_inv = 1. / (static_cast<double>(dim1) - 1.);
621 for (int i = 0; i < dim1; ++i)
622 m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
623 N_inv = 1. / (static_cast<double>(dim2) - 1.);
624 for (int i = 0; i < dim2; ++i)
625 m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
626 cv::Mat ret = m2 * m1;
630 // Returns sub-window of image input centered at [cx, cy] coordinates),
631 // with size [width, height]. If any pixels are outside of the image,
632 // they will replicate the values at the borders.
633 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
637 int x1 = cx - width / 2;
638 int y1 = cy - height / 2;
639 int x2 = cx + width / 2;
640 int y2 = cy + height / 2;
643 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
644 patch.create(height, width, input.type());
645 patch.setTo(double(0.f));
649 int top = 0, bottom = 0, left = 0, right = 0;
651 // fit to image coordinates, set border extensions;
660 if (x2 >= input.cols) {
661 right = x2 - input.cols + width % 2;
666 if (y2 >= input.rows) {
667 bottom = y2 - input.rows + height % 2;
672 if (x2 - x1 == 0 || y2 - y1 == 0)
673 patch = cv::Mat::zeros(height, width, CV_32FC1);
675 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
676 cv::BORDER_REPLICATE);
677 // imshow( "copyMakeBorder", patch);
682 assert(patch.cols == width && patch.rows == height);
687 void KCF_Tracker::GaussianCorrelation::operator()(const KCF_Tracker &kcf, ComplexMat &result, const ComplexMat &xf,
688 const ComplexMat &yf, double sigma, bool auto_correlation)
690 xf.sqr_norm(xf_sqr_norm);
691 if (auto_correlation) {
692 yf_sqr_norm = xf_sqr_norm;
694 yf.sqr_norm(yf_sqr_norm);
696 xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
698 kcf.fft.inverse(xyf, ifft_res);
700 cuda_gaussian_correlation(ifft_res.deviceMem(), k.deviceMem(), xf_sqr_norm.deviceMem(),
701 auto_correlation ? xf_sqr_norm.deviceMem() : yf_sqr_norm.deviceMem(), sigma,
702 xf.n_channels, xf.n_scales, kcf.p_roi.height, kcf.p_roi.width);
704 // ifft2 and sum over 3rd dimension, we dont care about individual channels
705 //DEBUG_PRINTM(vars.ifft2_res);
707 if (xf.channels() != p_num_scales * p_num_of_feats)
708 xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
710 xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
712 for (int y = 0; y < vars.ifft2_res.rows; ++y) {
713 float *row_ptr = vars.ifft2_res.ptr<float>(y);
714 float *row_ptr_sum = xy_sum.ptr<float>(y);
715 for (int x = 0; x < vars.ifft2_res.cols; ++x) {
716 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
717 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
718 row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
719 (row_ptr + x * vars.ifft2_res.channels() +
720 (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
725 DEBUG_PRINTM(xy_sum);
727 std::vector<cv::Mat> scales;
728 cv::split(xy_sum, scales);
730 float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
731 for (uint i = 0; i < xf.n_scales; ++i) {
732 cv::Mat in_roi(vars.in_all, cv::Rect(0, i * scales[0].rows, scales[0].cols, scales[0].rows));
734 -1. / (sigma * sigma) *
735 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),
737 DEBUG_PRINTM(in_roi);
740 kcf.fft.forward(k, result);
744 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
748 if (x < 0) x = response.cols + x;
749 if (y < 0) y = response.rows + y;
750 if (x >= response.cols) x = x - response.cols;
751 if (y >= response.rows) y = y - response.rows;
753 return response.at<float>(y, x);
756 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response) const
758 // find neighbourhood of max_loc (response is circular)
762 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);
763 cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
764 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);
767 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
768 cv::Mat A = (cv::Mat_<float>(9, 6) <<
769 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
770 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
771 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
772 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
773 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
774 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
775 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
776 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
777 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);
778 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
779 get_response_circular(p1, response),
780 get_response_circular(p2, response),
781 get_response_circular(p3, response),
782 get_response_circular(p4, response),
783 get_response_circular(p5, response),
784 get_response_circular(p6, response),
785 get_response_circular(p7, response),
786 get_response_circular(p8, response),
787 get_response_circular(max_loc, response));
790 cv::solve(A, fval, x, cv::DECOMP_SVD);
792 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);
794 cv::Point2f sub_peak(max_loc.x, max_loc.y);
795 if (b > 0 || b < 0) {
796 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
797 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
803 double KCF_Tracker::sub_grid_scale(uint index)
806 if (index >= p_scales.size()) {
807 // interpolate from all values
808 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
809 A.create(p_scales.size(), 3, CV_32FC1);
810 fval.create(p_scales.size(), 1, CV_32FC1);
811 for (size_t i = 0; i < p_scales.size(); ++i) {
812 A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
813 A.at<float>(i, 1) = float(p_scales[i]);
814 A.at<float>(i, 2) = 1;
816 fval.at<float>(i) = d.threadctxs.back().max_responses[i];
818 fval.at<float>(i) = d.threadctxs[i].max_response;
822 // only from neighbours
823 if (index == 0 || index == p_scales.size() - 1)
824 return p_scales[index];
826 A = (cv::Mat_<float>(3, 3) <<
827 p_scales[index - 1] * p_scales[index - 1], p_scales[index - 1], 1,
828 p_scales[index + 0] * p_scales[index + 0], p_scales[index + 0], 1,
829 p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
831 fval = (cv::Mat_<float>(3, 1) <<
832 d.threadctxs.back().max_responses[index - 1],
833 d.threadctxs.back().max_responses[index + 0],
834 d.threadctxs.back().max_responses[index + 1]);
836 fval = (cv::Mat_<float>(3, 1) <<
837 d.threadctxs[index - 1].max_response,
838 d.threadctxs[index + 0].max_response,
839 d.threadctxs[index + 1].max_response);
844 cv::solve(A, fval, x, cv::DECOMP_SVD);
845 float a = x.at<float>(0), b = x.at<float>(1);
846 double scale = p_scales[index];
848 scale = -b / (2 * a);