10 #include "fft_cufft.h"
13 #include "fft_opencv.h"
21 #define DEBUG_PRINT(obj) \
22 if (m_debug || m_visual_debug) { \
23 std::cout << #obj << " @" << __LINE__ << std::endl << (obj) << std::endl; \
25 #define DEBUG_PRINTM(obj) \
27 std::cout << #obj << " @" << __LINE__ << " " << (obj).size() << " CH: " << (obj).channels() << std::endl \
28 << (obj) << std::endl; \
31 KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor,
32 double output_sigma_factor, int cell_size)
33 : fft(*new FFT()), p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
34 p_lambda(lambda), p_interp_factor(interp_factor), p_cell_size(cell_size)
38 KCF_Tracker::KCF_Tracker() : fft(*new FFT()) {}
40 KCF_Tracker::~KCF_Tracker()
45 void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int fit_size_y)
47 // check boundary, enforce min size
48 double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
50 if (x2 > img.cols - 1) x2 = img.cols - 1;
52 if (y2 > img.rows - 1) y2 = img.rows - 1;
54 if (x2 - x1 < 2 * p_cell_size) {
55 double diff = (2 * p_cell_size - x2 + x1) / 2.;
56 if (x1 - diff >= 0 && x2 + diff < img.cols) {
59 } else if (x1 - 2 * diff >= 0) {
65 if (y2 - y1 < 2 * p_cell_size) {
66 double diff = (2 * p_cell_size - y2 + y1) / 2.;
67 if (y1 - diff >= 0 && y2 + diff < img.rows) {
70 } else if (y1 - 2 * diff >= 0) {
79 p_pose.cx = x1 + p_pose.w / 2.;
80 p_pose.cy = y1 + p_pose.h / 2.;
82 cv::Mat input_gray, input_rgb = img.clone();
83 if (img.channels() == 3) {
84 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
85 input_gray.convertTo(input_gray, CV_32FC1);
87 img.convertTo(input_gray, CV_32FC1);
89 // don't need too large image
90 if (p_pose.w * p_pose.h > 100. * 100. && (fit_size_x == -1 || fit_size_y == -1)) {
91 std::cout << "resizing image by factor of " << 1 / p_downscale_factor << std::endl;
92 p_resize_image = true;
93 p_pose.scale(p_downscale_factor);
94 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
95 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
96 } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
97 if (fit_size_x % p_cell_size != 0 || fit_size_y % p_cell_size != 0) {
98 std::cerr << "Error: Fit size is not multiple of HOG cell size (" << p_cell_size << ")" << std::endl;
99 std::exit(EXIT_FAILURE);
101 p_scale_factor_x = (double)fit_size_x / round(p_pose.w * (1. + p_padding));
102 p_scale_factor_y = (double)fit_size_y / round(p_pose.h * (1. + p_padding));
103 std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x << " and verticaly by factor of "
104 << p_scale_factor_y << std::endl;
106 p_pose.scale_x(p_scale_factor_x);
107 p_pose.scale_y(p_scale_factor_y);
108 if (fabs(p_scale_factor_x - 1) > p_floating_error || fabs(p_scale_factor_y - 1) > p_floating_error) {
109 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
110 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
111 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
113 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
114 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
119 // compute win size + fit to fhog cell size
120 p_windows_size.width = round(p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size;
121 p_windows_size.height = round(p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size;
122 p_roi.width = p_windows_size.width / p_cell_size;
123 p_roi.height = p_windows_size.height / p_cell_size;
127 for (int i = -int(p_num_scales) / 2; i <= int(p_num_scales) / 2; ++i)
128 p_scales.push_back(std::pow(p_scale_step, i));
130 p_scales.push_back(1.);
135 for (int i = p_angle_min; i <= p_angle_max; i += p_angle_step)
136 p_angles.push_back(i);
138 p_angles.push_back(0);
143 if (p_roi.height * (p_roi.width / 2 + 1) > 1024) {
144 std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
145 "the window dimensions so its size is less or equal to "
146 << 1024 * p_cell_size * p_cell_size * 2 + 1
147 << " pixels . Currently the size of the window is: " << p_windows_size.width << "x"
148 << p_windows_size.height << " which is " << p_windows_size.width * p_windows_size.height
149 << " pixels. " << std::endl;
150 std::exit(EXIT_FAILURE);
153 if (m_use_linearkernel) {
154 std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
155 std::exit(EXIT_FAILURE);
158 CudaSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost));
160 p_rot_labels_data = DynMem(p_roi.width * p_roi.height * sizeof(float));
161 p_rot_labels = cv::Mat(p_roi, CV_32FC1, p_rot_labels_data.hostMem());
164 #if defined(CUFFT) || defined(FFTW)
165 uint width = p_roi.width / 2 + 1;
167 uint width = p_roi.width;
169 p_model_xf.create(p_roi.height, width, p_num_of_feats);
170 p_yf.create(p_roi.height, width, 1);
171 p_xf.create(p_roi.height, width, p_num_of_feats);
173 int max1 = m_use_big_batch ? 2 : p_num_scales;
174 int max2 = m_use_big_batch ? 1 : p_num_angles;
175 for (int i = 0; i < max1; ++i) {
176 for (int j = 0; j < max2; ++j) {
177 if (m_use_big_batch && i == 1)
178 p_threadctxs.emplace_back(p_roi, p_num_of_feats * p_num_scales * p_num_angles, 1, 0, p_num_scales,
181 p_threadctxs.emplace_back(p_roi, p_num_of_feats, p_scales[i], p_angles[j]);
185 p_current_scale = 1.;
187 double min_size_ratio = std::max(5. * p_cell_size / p_windows_size.width, 5. * p_cell_size / p_windows_size.height);
188 double max_size_ratio =
189 std::min(floor((img.cols + p_windows_size.width / 3) / p_cell_size) * p_cell_size / p_windows_size.width,
190 floor((img.rows + p_windows_size.height / 3) / p_cell_size) * p_cell_size / p_windows_size.height);
191 p_min_max_scale[0] = std::pow(p_scale_step, std::ceil(std::log(min_size_ratio) / log(p_scale_step)));
192 p_min_max_scale[1] = std::pow(p_scale_step, std::floor(std::log(max_size_ratio) / log(p_scale_step)));
194 std::cout << "init: img size " << img.cols << "x" << img.rows << std::endl;
195 std::cout << "init: win size " << p_windows_size.width << "x" << p_windows_size.height << std::endl;
196 std::cout << "init: FFT size " << p_roi.width << "x" << p_roi.height << std::endl;
197 std::cout << "init: min max scales factors: " << p_min_max_scale[0] << " " << p_min_max_scale[1] << std::endl;
199 p_output_sigma = std::sqrt(p_pose.w * p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
201 fft.init(p_roi.width, p_roi.height, p_num_of_feats, p_num_scales * p_num_angles, m_use_big_batch);
202 fft.set_window(cosine_window_function(p_roi.width, p_roi.height));
204 // window weights, i.e. labels
205 fft.forward(gaussian_shaped_labels(p_output_sigma, p_roi.width, p_roi.height), p_yf,
206 m_use_cuda ? p_rot_labels_data.deviceMem() : nullptr, p_threadctxs.front().stream);
209 // obtain a sub-window for training initial model
210 p_threadctxs.front().patch_feats.clear();
212 int size_x_scaled = floor(p_windows_size.width);
213 int size_y_scaled = floor(p_windows_size.height);
215 cv::Mat patch_gray = get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
216 geometric_transformations(patch_gray, p_windows_size.width, p_windows_size.height, 0, false);
218 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
219 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
220 patch_rgb = get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
221 geometric_transformations(patch_rgb, p_windows_size.width, p_windows_size.height, 0, false);
224 get_features(patch_rgb, patch_gray, p_threadctxs.front());
225 fft.forward_window(p_threadctxs.front().patch_feats, p_model_xf, p_threadctxs.front().fw_all,
226 m_use_cuda ? p_threadctxs.front().data_features.deviceMem() : nullptr,
227 p_threadctxs.front().stream);
228 DEBUG_PRINTM(p_model_xf);
230 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
231 p_threadctxs.front().model_xf = p_model_xf;
232 p_threadctxs.front().model_xf.set_stream(p_threadctxs.front().stream);
233 p_yf.set_stream(p_threadctxs.front().stream);
234 p_model_xf.set_stream(p_threadctxs.front().stream);
235 p_xf.set_stream(p_threadctxs.front().stream);
238 if (m_use_linearkernel) {
239 ComplexMat xfconj = p_model_xf.conj();
240 p_model_alphaf_num = xfconj.mul(p_yf);
241 p_model_alphaf_den = (p_model_xf * xfconj);
243 // Kernel Ridge Regression, calculate alphas (in Fourier domain)
244 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
245 gaussian_correlation(p_threadctxs.front(), p_threadctxs.front().model_xf, p_threadctxs.front().model_xf,
246 p_kernel_sigma, true);
248 gaussian_correlation(p_threadctxs.front(), p_model_xf, p_model_xf, p_kernel_sigma, true);
250 DEBUG_PRINTM(p_threadctxs.front().kf);
251 p_model_alphaf_num = p_yf * p_threadctxs.front().kf;
252 DEBUG_PRINTM(p_model_alphaf_num);
253 p_model_alphaf_den = p_threadctxs.front().kf * (p_threadctxs.front().kf + float(p_lambda));
254 DEBUG_PRINTM(p_model_alphaf_den);
256 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
257 DEBUG_PRINTM(p_model_alphaf);
258 // p_model_alphaf = p_yf / (kf + p_lambda); //equation for fast training
260 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
261 for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
262 it->model_xf = p_model_xf;
263 it->model_xf.set_stream(it->stream);
264 it->model_alphaf = p_model_alphaf;
265 it->model_alphaf.set_stream(it->stream);
270 void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat &img, int fit_size_x, int fit_size_y)
272 init(img, bbox.get_rect(), fit_size_x, fit_size_y);
275 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
277 if (p_resize_image) {
279 tmp.scale(p_downscale_factor);
282 } else if (p_fit_to_pw2) {
284 tmp.scale_x(p_scale_factor_x);
285 tmp.scale_y(p_scale_factor_y);
294 BBox_c KCF_Tracker::getBBox()
297 tmp.w *= p_current_scale;
298 tmp.h *= p_current_scale;
299 tmp.a = p_current_angle;
301 if (p_resize_image) tmp.scale(1 / p_downscale_factor);
303 tmp.scale_x(1 / p_scale_factor_x);
304 tmp.scale_y(1 / p_scale_factor_y);
310 double KCF_Tracker::getFilterResponse() const
312 return this->max_response;
315 void KCF_Tracker::track(cv::Mat &img)
317 if (m_debug || m_visual_debug) std::cout << "\nNEW FRAME" << std::endl;
318 cv::Mat input_gray, input_rgb = img.clone();
319 if (img.channels() == 3) {
320 cv::cvtColor(img, input_gray, CV_BGR2GRAY);
321 input_gray.convertTo(input_gray, CV_32FC1);
323 img.convertTo(input_gray, CV_32FC1);
325 // don't need too large image
326 if (p_resize_image) {
327 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
328 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
329 } else if (p_fit_to_pw2 && fabs(p_scale_factor_x - 1) > p_floating_error &&
330 fabs(p_scale_factor_y - 1) > p_floating_error) {
331 if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
332 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
333 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
335 cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
336 cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
340 ThreadCtx *max = nullptr;
341 cv::Point2i *max_response_pt = nullptr;
342 cv::Mat *max_response_map = nullptr;
345 for (auto &it : p_threadctxs)
346 it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
347 scale_track(it, input_rgb, input_gray);
349 for (auto const &it : p_threadctxs)
352 NORMAL_OMP_PARALLEL_FOR
353 for (uint i = m_use_big_batch ? 1 : 0; i < p_threadctxs.size(); ++i)
354 scale_track(p_threadctxs[i], input_rgb, input_gray);
358 for (auto &it : p_threadctxs) {
359 if (it.max_response > max_response) {
360 max_response = it.max_response;
361 max_response_pt = &it.max_loc;
362 max_response_map = &it.response;
367 for (uint j = 0; j < p_num_scales; ++j) {
368 for (uint k = 0; k < p_num_angles; ++k) {
369 if (p_threadctxs.back().max_responses[j + k] > max_response) {
370 max_response = p_threadctxs.back().max_responses[j + k];
371 max_response_pt = &p_threadctxs.back().max_locs[j + k];
372 max_response_map = &p_threadctxs.back().response_maps[j + k];
376 max = &p_threadctxs.back();
378 if (m_visual_debug) {
379 cv::Mat all_responses(cv::Size(p_num_angles* p_debug_image_size, p_num_scales * p_debug_image_size),
380 p_debug_scale_responses[0].type(), cv::Scalar::all(0));
381 cv::Mat all_subwindows(cv::Size(p_num_angles* p_debug_image_size, p_num_scales* p_debug_image_size),
382 p_debug_subwindows[0].type(), cv::Scalar::all(0));
383 for (size_t i = 0; i < p_num_scales; ++i) {
384 for (size_t j = 0; j < p_num_angles; ++j) {
385 cv::Mat in_roi(all_responses, cv::Rect(j * p_debug_image_size, i * p_debug_image_size,
386 p_debug_image_size, p_debug_image_size));
387 p_debug_scale_responses[5 * i + j].copyTo(in_roi);
388 in_roi = all_subwindows(
389 cv::Rect(j * p_debug_image_size, i * p_debug_image_size, p_debug_image_size, p_debug_image_size));
390 p_debug_subwindows[5 * i + j].copyTo(in_roi);
393 cv::namedWindow("All subwindows", CV_WINDOW_AUTOSIZE);
394 cv::imshow("All subwindows", all_subwindows);
395 cv::namedWindow("All responses", CV_WINDOW_AUTOSIZE);
396 cv::imshow("All responses", all_responses);
398 p_debug_scale_responses.clear();
399 p_debug_subwindows.clear();
402 DEBUG_PRINTM(*max_response_map);
403 DEBUG_PRINT(*max_response_pt);
405 // sub pixel quadratic interpolation from neighbours
406 if (max_response_pt->y > max_response_map->rows / 2) // wrap around to negative half-space of vertical axis
407 max_response_pt->y = max_response_pt->y - max_response_map->rows;
408 if (max_response_pt->x > max_response_map->cols / 2) // same for horizontal axis
409 max_response_pt->x = max_response_pt->x - max_response_map->cols;
411 cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
412 DEBUG_PRINT(new_location);
414 if (m_use_subpixel_localization)
415 new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
416 DEBUG_PRINT(new_location);
418 if (m_visual_debug) std::cout << "Old p_pose, cx: " << p_pose.cx << " cy: " << p_pose.cy << std::endl;
420 p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
421 p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
423 if (m_visual_debug) std::cout << "New p_pose, cx: " << p_pose.cx << " cy: " << p_pose.cy << std::endl;
426 if (p_pose.cx < 0) p_pose.cx = 0;
427 if (p_pose.cx > (img.cols * p_scale_factor_x) - 1) p_pose.cx = (img.cols * p_scale_factor_x) - 1;
428 if (p_pose.cy < 0) p_pose.cy = 0;
429 if (p_pose.cy > (img.rows * p_scale_factor_y) - 1) p_pose.cy = (img.rows * p_scale_factor_y) - 1;
431 if (p_pose.cx < 0) p_pose.cx = 0;
432 if (p_pose.cx > img.cols - 1) p_pose.cx = img.cols - 1;
433 if (p_pose.cy < 0) p_pose.cy = 0;
434 if (p_pose.cy > img.rows - 1) p_pose.cy = img.rows - 1;
437 // sub grid scale interpolation
438 if (m_use_subgrid_scale) {
439 auto it = std::find_if(p_threadctxs.begin(), p_threadctxs.end(), [max](ThreadCtx &ctx) { return &ctx == max; });
440 p_current_scale *= sub_grid_scale(std::distance(p_threadctxs.begin(), it));
442 p_current_scale *= max->scale;
446 if (p_current_scale < p_min_max_scale[0]) p_current_scale = p_min_max_scale[0];
447 if (p_current_scale > p_min_max_scale[1]) p_current_scale = p_min_max_scale[1];
449 p_current_angle = (p_current_angle + max->angle) < 0
450 ? -std::abs(p_current_angle + max->angle) % 360
451 : (p_current_angle + max->angle) % 360;
453 // obtain a subwindow for training at newly estimated target position
454 int size_x_scaled = floor(p_windows_size.width * p_current_scale);
455 int size_y_scaled = floor(p_windows_size.height * p_current_scale);
457 cv::Mat patch_gray = get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
458 geometric_transformations(patch_gray, p_windows_size.width, p_windows_size.height, p_current_angle, false);
460 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
461 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
462 patch_rgb = get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
463 geometric_transformations(patch_rgb, p_windows_size.width, p_windows_size.height, p_current_angle, false);
466 p_threadctxs.front().patch_feats.clear();
467 get_features(patch_rgb, patch_gray, p_threadctxs.front());
468 fft.forward_window(p_threadctxs.front().patch_feats, p_xf, p_threadctxs.front().fw_all,
469 m_use_cuda ? p_threadctxs.front().data_features.deviceMem() : nullptr, p_threadctxs.front().stream);
471 // subsequent frames, interpolate model
472 p_model_xf = p_model_xf * float((1. - p_interp_factor)) + p_xf * float(p_interp_factor);
474 ComplexMat alphaf_num, alphaf_den;
476 if (m_use_linearkernel) {
477 ComplexMat xfconj = p_xf.conj();
478 alphaf_num = xfconj.mul(p_yf);
479 alphaf_den = (p_xf * xfconj);
481 // Kernel Ridge Regression, calculate alphas (in Fourier domain)
482 gaussian_correlation(p_threadctxs.front(), p_xf, p_xf, p_kernel_sigma,
484 // ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
485 // p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
486 alphaf_num = p_yf * p_threadctxs.front().kf;
487 alphaf_den = p_threadctxs.front().kf * (p_threadctxs.front().kf + float(p_lambda));
490 p_model_alphaf_num = p_model_alphaf_num * float((1. - p_interp_factor)) + alphaf_num * float(p_interp_factor);
491 p_model_alphaf_den = p_model_alphaf_den * float((1. - p_interp_factor)) + alphaf_den * float(p_interp_factor);
492 p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
494 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
495 for (auto it = p_threadctxs.begin(); it != p_threadctxs.end(); ++it) {
496 it->model_xf = p_model_xf;
497 it->model_xf.set_stream(it->stream);
498 it->model_alphaf = p_model_alphaf;
499 it->model_alphaf.set_stream(it->stream);
504 void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray)
506 if (m_use_big_batch) {
507 vars.patch_feats.clear();
508 BIG_BATCH_OMP_PARALLEL_FOR
509 for (uint i = 0; i < this->p_scales.size(); ++i) {
510 for (uint j = 0; j < this->p_angles.size(); ++j) {
511 int size_x_scaled = floor(this->p_windows_size.width * this->p_current_scale * this->p_scales[i]);
512 int size_y_scaled = floor(this->p_windows_size.height * this->p_current_scale * this->p_scales[i]);
515 get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
516 geometric_transformations(patch_gray, p_windows_size.width, p_windows_size.height,
517 p_current_scale * this->p_scales[i], p_current_angle + this->p_angles[j]);
519 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
520 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
522 get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
523 geometric_transformations(patch_rgb, p_windows_size.width, p_windows_size.height,
524 p_current_scale * this->p_scales[i], p_current_angle + this->p_angles[j]);
526 get_features(patch_rgb, patch_gray, vars);
530 int size_x_scaled = floor(this->p_windows_size.width * this->p_current_scale * vars.scale);
531 int size_y_scaled = floor(this->p_windows_size.height * this->p_current_scale * vars.scale);
533 cv::Mat patch_gray = get_subwindow(input_gray, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
534 geometric_transformations(patch_gray, p_windows_size.width, p_windows_size.height, p_current_scale * vars.scale);
536 cv::Mat patch_rgb = cv::Mat::zeros(size_y_scaled, size_x_scaled, CV_32F);
537 if ((m_use_color || m_use_cnfeat) && input_rgb.channels() == 3) {
538 patch_rgb = get_subwindow(input_rgb, this->p_pose.cx, this->p_pose.cy, size_x_scaled, size_y_scaled);
539 geometric_transformations(patch_rgb, p_windows_size.width, p_windows_size.height, p_current_scale * vars.scale,
540 p_current_angle + vars.angle);
542 vars.patch_feats.clear();
543 get_features(patch_rgb, patch_gray, vars);
546 fft.forward_window(vars.patch_feats, vars.zf, vars.fw_all, m_use_cuda ? vars.data_features.deviceMem() : nullptr,
548 DEBUG_PRINTM(vars.zf);
550 if (m_use_linearkernel) {
551 vars.kzf = m_use_big_batch ? (vars.zf.mul2(this->p_model_alphaf)).sum_over_channels()
552 : (p_model_alphaf * vars.zf).sum_over_channels();
553 fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr, vars.stream);
555 #if !defined(BIG_BATCH) && defined(CUFFT) && (defined(ASYNC) || defined(OPENMP))
556 gaussian_correlation(vars, vars.zf, vars.model_xf, this->p_kernel_sigma);
557 vars.kzf = vars.model_alphaf * vars.kzf;
559 gaussian_correlation(vars, vars.zf, this->p_model_xf, this->p_kernel_sigma);
560 DEBUG_PRINTM(this->p_model_alphaf);
561 DEBUG_PRINTM(vars.kzf);
562 vars.kzf = m_use_big_batch ? vars.kzf.mul(this->p_model_alphaf) : this->p_model_alphaf * vars.kzf;
564 fft.inverse(vars.kzf, vars.response, m_use_cuda ? vars.data_i_1ch.deviceMem() : nullptr, vars.stream);
567 DEBUG_PRINTM(vars.response);
569 /* target location is at the maximum response. we must take into
570 account the fact that, if the target doesn't move, the peak
571 will appear at the top-left corner, not at the center (this is
572 discussed in the paper). the responses wrap around cyclically. */
573 if (m_use_big_batch) {
574 cv::split(vars.response, vars.response_maps);
576 for (size_t i = 0; i < p_scales.size(); ++i) {
577 double min_val, max_val;
578 cv::Point2i min_loc, max_loc;
579 cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
580 DEBUG_PRINT(max_loc);
581 double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
582 vars.max_responses[i] = max_val * weight;
583 vars.max_locs[i] = max_loc;
588 cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
590 DEBUG_PRINT(vars.max_loc);
592 double weight = vars.scale < 1. ? vars.scale : 1. / vars.scale;
593 vars.max_response = vars.max_val * weight;
598 // ****************************************************************************
600 void KCF_Tracker::get_features(cv::Mat &patch_rgb, cv::Mat &patch_gray, ThreadCtx &vars)
602 // get hog(Histogram of Oriented Gradients) features
603 vars.patch_feats = FHoG::extract(patch_gray, 2, p_cell_size, 9);
605 // get color rgb features (simple r,g,b channels)
606 std::vector<cv::Mat> color_feat;
608 if (m_use_color && patch_rgb.channels() == 3) {
609 // use rgb color space
610 cv::Mat patch_rgb_norm;
611 patch_rgb.convertTo(patch_rgb_norm, CV_32F, 1. / 255., -0.5);
612 cv::Mat ch1(patch_rgb_norm.size(), CV_32FC1);
613 cv::Mat ch2(patch_rgb_norm.size(), CV_32FC1);
614 cv::Mat ch3(patch_rgb_norm.size(), CV_32FC1);
615 std::vector<cv::Mat> rgb = {ch1, ch2, ch3};
616 cv::split(patch_rgb_norm, rgb);
617 color_feat.insert(color_feat.end(), rgb.begin(), rgb.end());
620 if (m_use_cnfeat && patch_rgb.channels() == 3) {
621 std::vector<cv::Mat> cn_feat = CNFeat::extract(patch_rgb);
622 color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
624 BIG_BATCH_OMP_ORDERED
625 vars.patch_feats.insert(vars.patch_feats.end(), color_feat.begin(), color_feat.end());
629 cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
631 cv::Mat labels(dim2, dim1, CV_32FC1);
632 int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
633 int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
635 double sigma_s = sigma * sigma;
637 for (int y = range_y[0], j = 0; y < range_y[1]; ++y, ++j) {
638 float *row_ptr = labels.ptr<float>(j);
640 for (int x = range_x[0], i = 0; x < range_x[1]; ++x, ++i) {
641 row_ptr[i] = float(std::exp(-0.5 * (y_s + x * x) / sigma_s)); //-1/2*e^((y^2+x^2)/sigma^2)
645 // rotate so that 1 is at top-left corner (see KCF paper for explanation)
647 cv::Mat tmp = circshift(labels, range_x[0], range_y[0]);
648 tmp.copyTo(p_rot_labels);
650 assert(p_rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
653 cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
654 // sanity check, 1 at top left corner
655 assert(rot_labels.at<float>(0, 0) >= 1.f - 1e-10f);
661 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
663 cv::Mat rot_patch(patch.size(), CV_32FC1);
664 cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
666 // circular rotate x-axis
668 // move part that does not rotate over the edge
669 cv::Range orig_range(-x_rot, patch.cols);
670 cv::Range rot_range(0, patch.cols - (-x_rot));
671 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
674 orig_range = cv::Range(0, -x_rot);
675 rot_range = cv::Range(patch.cols - (-x_rot), patch.cols);
676 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
677 } else if (x_rot > 0) {
678 // move part that does not rotate over the edge
679 cv::Range orig_range(0, patch.cols - x_rot);
680 cv::Range rot_range(x_rot, patch.cols);
681 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
684 orig_range = cv::Range(patch.cols - x_rot, patch.cols);
685 rot_range = cv::Range(0, x_rot);
686 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
687 } else { // zero rotation
688 // move part that does not rotate over the edge
689 cv::Range orig_range(0, patch.cols);
690 cv::Range rot_range(0, patch.cols);
691 patch(cv::Range::all(), orig_range).copyTo(tmp_x_rot(cv::Range::all(), rot_range));
694 // circular rotate y-axis
696 // move part that does not rotate over the edge
697 cv::Range orig_range(-y_rot, patch.rows);
698 cv::Range rot_range(0, patch.rows - (-y_rot));
699 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
702 orig_range = cv::Range(0, -y_rot);
703 rot_range = cv::Range(patch.rows - (-y_rot), patch.rows);
704 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
705 } else if (y_rot > 0) {
706 // move part that does not rotate over the edge
707 cv::Range orig_range(0, patch.rows - y_rot);
708 cv::Range rot_range(y_rot, patch.rows);
709 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
712 orig_range = cv::Range(patch.rows - y_rot, patch.rows);
713 rot_range = cv::Range(0, y_rot);
714 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
715 } else { // zero rotation
716 // move part that does not rotate over the edge
717 cv::Range orig_range(0, patch.rows);
718 cv::Range rot_range(0, patch.rows);
719 tmp_x_rot(orig_range, cv::Range::all()).copyTo(rot_patch(rot_range, cv::Range::all()));
725 // hann window actually (Power-of-cosine windows)
726 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
728 cv::Mat m1(1, dim1, CV_32FC1), m2(dim2, 1, CV_32FC1);
729 double N_inv = 1. / (static_cast<double>(dim1) - 1.);
730 for (int i = 0; i < dim1; ++i)
731 m1.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
732 N_inv = 1. / (static_cast<double>(dim2) - 1.);
733 for (int i = 0; i < dim2; ++i)
734 m2.at<float>(i) = float(0.5 * (1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv)));
735 cv::Mat ret = m2 * m1;
739 // Returns sub-window of image input centered at [cx, cy] coordinates),
740 // with size [width, height]. If any pixels are outside of the image,
741 // they will replicate the values at the borders.
742 cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
746 int x1 = cx - width / 2;
747 int y1 = cy - height / 2;
748 int x2 = cx + width / 2;
749 int y2 = cy + height / 2;
752 if (x1 >= input.cols || y1 >= input.rows || x2 < 0 || y2 < 0) {
753 patch.create(height, width, input.type());
754 patch.setTo(double(0.f));
758 int top = 0, bottom = 0, left = 0, right = 0;
760 // fit to image coordinates, set border extensions;
769 if (x2 >= input.cols) {
770 right = x2 - input.cols + width % 2;
775 if (y2 >= input.rows) {
776 bottom = y2 - input.rows + height % 2;
781 if (x2 - x1 == 0 || y2 - y1 == 0)
782 patch = cv::Mat::zeros(height, width, CV_32FC1);
784 cv::copyMakeBorder(input(cv::Range(y1, y2), cv::Range(x1, x2)), patch, top, bottom, left, right,
785 cv::BORDER_REPLICATE);
788 assert(patch.cols == width && patch.rows == height);
793 void KCF_Tracker::geometric_transformations(cv::Mat &patch, int size_x, int size_y, int angle, bool allow_debug)
796 cv::Point2f center((patch.cols - 1) / 2., (patch.rows - 1) / 2.);
797 cv::Mat r = cv::getRotationMatrix2D(center, angle, 1.0);
799 cv::warpAffine(patch, patch, r, cv::Size(patch.cols, patch.rows), cv::INTER_LINEAR, cv::BORDER_REPLICATE);
802 // resize to default size
803 if (patch.channels() != 3) {
804 if (patch.cols / size_x > 1.) {
805 // if we downsample use INTER_AREA interpolation
806 cv::resize(patch, patch, cv::Size(size_x, size_y), 0., 0., cv::INTER_AREA);
808 cv::resize(patch, patch, cv::Size(size_x, size_y), 0., 0., cv::INTER_LINEAR);
811 if (patch.cols / size_x > 1.) {
812 // if we downsample use INTER_AREA interpolation
813 cv::resize(patch, patch, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_AREA);
815 cv::resize(patch, patch, cv::Size(size_x / p_cell_size, size_y / p_cell_size), 0., 0., cv::INTER_LINEAR);
817 if (m_visual_debug && allow_debug) {
818 cv::Mat input_clone = patch.clone();
819 cv::resize(input_clone, input_clone, cv::Size(p_debug_image_size, p_debug_image_size), 0., 0.,
822 std::string angle_string = std::to_string(p_current_angle + angle);
824 cv::putText(input_clone, angle_string, cv::Point(1, input_clone.rows - 5), cv::FONT_HERSHEY_COMPLEX_SMALL,
825 0.5, cv::Scalar(0, 255, 0), 1);
827 p_debug_subwindows.push_back(input_clone);
832 void KCF_Tracker::gaussian_correlation(struct ThreadCtx &vars, const ComplexMat &xf, const ComplexMat &yf, double sigma,
833 bool auto_correlation)
835 xf.sqr_norm(vars.xf_sqr_norm);
836 if (auto_correlation) {
837 vars.yf_sqr_norm.hostMem()[0] = vars.xf_sqr_norm.hostMem()[0];
839 yf.sqr_norm(vars.yf_sqr_norm);
841 vars.xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
842 DEBUG_PRINTM(vars.xyf);
843 fft.inverse(vars.xyf, vars.ifft2_res, m_use_cuda ? vars.data_i_features.deviceMem() : nullptr, vars.stream);
845 cuda_gaussian_correlation(vars.data_i_features.deviceMem(), vars.gauss_corr_res.deviceMem(),
846 vars.xf_sqr_norm.deviceMem(), vars.xf_sqr_norm.deviceMem(), sigma, xf.n_channels,
847 xf.n_scales, p_roi.height, p_roi.width, vars.stream);
849 // ifft2 and sum over 3rd dimension, we dont care about individual channels
850 DEBUG_PRINTM(vars.ifft2_res);
852 if (xf.channels() != p_num_scales * p_num_of_feats)
853 xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
855 xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
857 for (int y = 0; y < vars.ifft2_res.rows; ++y) {
858 float *row_ptr = vars.ifft2_res.ptr<float>(y);
859 float *row_ptr_sum = xy_sum.ptr<float>(y);
860 for (int x = 0; x < vars.ifft2_res.cols; ++x) {
861 for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
862 row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
863 row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
864 (row_ptr + x * vars.ifft2_res.channels() +
865 (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
870 DEBUG_PRINTM(xy_sum);
872 std::vector<cv::Mat> scales;
873 cv::split(xy_sum, scales);
875 float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
876 for (uint i = 0; i < xf.n_scales; ++i) {
877 cv::Mat in_roi(vars.in_all, cv::Rect(0, i * scales[0].rows, scales[0].cols, scales[0].rows));
879 -1. / (sigma * sigma) *
880 cv::max((double(vars.xf_sqr_norm.hostMem()[i] + vars.yf_sqr_norm.hostMem()[0]) - 2 * scales[i]) * double(numel_xf_inv), 0),
882 DEBUG_PRINTM(in_roi);
885 DEBUG_PRINTM(vars.in_all);
886 fft.forward(vars.in_all, auto_correlation ? vars.kf : vars.kzf, m_use_cuda ? vars.gauss_corr_res.deviceMem() : nullptr,
891 float get_response_circular(cv::Point2i &pt, cv::Mat &response)
895 if (x < 0) x = response.cols + x;
896 if (y < 0) y = response.rows + y;
897 if (x >= response.cols) x = x - response.cols;
898 if (y >= response.rows) y = y - response.rows;
900 return response.at<float>(y, x);
903 cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point &max_loc, cv::Mat &response)
905 // find neighbourhood of max_loc (response is circular)
909 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);
910 cv::Point2i p4(max_loc.x - 1, max_loc.y), p5(max_loc.x + 1, max_loc.y);
911 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);
914 // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
915 cv::Mat A = (cv::Mat_<float>(9, 6) <<
916 p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
917 p2.x*p2.x, p2.x*p2.y, p2.y*p2.y, p2.x, p2.y, 1.f,
918 p3.x*p3.x, p3.x*p3.y, p3.y*p3.y, p3.x, p3.y, 1.f,
919 p4.x*p4.x, p4.x*p4.y, p4.y*p4.y, p4.x, p4.y, 1.f,
920 p5.x*p5.x, p5.x*p5.y, p5.y*p5.y, p5.x, p5.y, 1.f,
921 p6.x*p6.x, p6.x*p6.y, p6.y*p6.y, p6.x, p6.y, 1.f,
922 p7.x*p7.x, p7.x*p7.y, p7.y*p7.y, p7.x, p7.y, 1.f,
923 p8.x*p8.x, p8.x*p8.y, p8.y*p8.y, p8.x, p8.y, 1.f,
924 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);
925 cv::Mat fval = (cv::Mat_<float>(9, 1) <<
926 get_response_circular(p1, response),
927 get_response_circular(p2, response),
928 get_response_circular(p3, response),
929 get_response_circular(p4, response),
930 get_response_circular(p5, response),
931 get_response_circular(p6, response),
932 get_response_circular(p7, response),
933 get_response_circular(p8, response),
934 get_response_circular(max_loc, response));
937 cv::solve(A, fval, x, cv::DECOMP_SVD);
939 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);
941 cv::Point2f sub_peak(max_loc.x, max_loc.y);
942 if (b > 0 || b < 0) {
943 sub_peak.y = ((2.f * a * e) / b - d) / (b - (4 * a * c) / b);
944 sub_peak.x = (-2 * c * sub_peak.y - e) / b;
950 double KCF_Tracker::sub_grid_scale(uint index)
953 if (index >= p_scales.size()) {
954 // interpolate from all values
955 // fit 1d quadratic function f(x) = a*x^2 + b*x + c
956 A.create(p_scales.size(), 3, CV_32FC1);
957 fval.create(p_scales.size(), 1, CV_32FC1);
958 for (size_t i = 0; i < p_scales.size(); ++i) {
959 A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
960 A.at<float>(i, 1) = float(p_scales[i]);
961 A.at<float>(i, 2) = 1;
962 fval.at<float>(i) = m_use_big_batch ? p_threadctxs.back().max_responses[i] : p_threadctxs[i].max_response;
965 // only from neighbours
966 if (index == 0 || index == p_scales.size() - 1)
967 return p_scales[index];
969 A = (cv::Mat_<float>(3, 3) <<
970 p_scales[index - 1] * p_scales[index - 1], p_scales[index - 1], 1,
971 p_scales[index + 0] * p_scales[index + 0], p_scales[index + 0], 1,
972 p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
973 fval = (cv::Mat_<float>(3, 1) <<
974 (m_use_big_batch ? p_threadctxs.back().max_responses[index - 1] : p_threadctxs[index - 1].max_response),
975 (m_use_big_batch ? p_threadctxs.back().max_responses[index + 0] : p_threadctxs[index + 0].max_response),
976 (m_use_big_batch ? p_threadctxs.back().max_responses[index + 1] : p_threadctxs[index + 1].max_response));
980 cv::solve(A, fval, x, cv::DECOMP_SVD);
981 float a = x.at<float>(0), b = x.at<float>(1);
982 double scale = p_scales[index];
984 scale = -b / (2 * a);