#include <thread>
#include <algorithm>
#include "threadctx.hpp"
+#include "debug.h"
#ifdef FFTW
#include "fft_fftw.h"
#include <omp.h>
#endif // OPENMP
-static bool kcf_debug = false;
-
-#define DEBUG_PRINT(obj) \
- if (kcf_debug) { \
- std::cout << #obj << " @" << __LINE__ << std::endl << (obj) << std::endl; \
- }
-#define DEBUG_PRINTM(obj) \
- if (kcf_debug) { \
- std::cout << #obj << " @" << __LINE__ << " " << (obj).size() << " CH: " << (obj).channels() << std::endl \
- << (obj) << std::endl; \
- }
+DbgTracer __dbgTracer;
template <typename T>
T clamp(const T& n, const T& lower, const T& upper)
KCF_Tracker::KCF_Tracker(double padding, double kernel_sigma, double lambda, double interp_factor,
double output_sigma_factor, int cell_size)
- : fft(*new FFT()), p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
- p_lambda(lambda), p_interp_factor(interp_factor), p_cell_size(cell_size), d(*new Kcf_Tracker_Private)
+ : p_cell_size(cell_size), fft(*new FFT()), p_padding(padding), p_output_sigma_factor(output_sigma_factor), p_kernel_sigma(kernel_sigma),
+ p_lambda(lambda), p_interp_factor(interp_factor), d(*new Kcf_Tracker_Private)
{
}
delete &d;
}
-void KCF_Tracker::train(cv::Mat input_gray, cv::Mat input_rgb, double interp_factor)
+void KCF_Tracker::train(cv::Mat input_rgb, cv::Mat input_gray, double interp_factor)
{
+ TRACE("");
+
// obtain a sub-window for training
- int sizes[3] = {p_num_of_feats, p_windows_size.height, p_windows_size.width};
- MatDynMem patch_feats(3, sizes, CV_32FC1);
- MatDynMem temp(3, sizes, CV_32FC1);
- get_features(patch_feats, input_rgb, input_gray, p_pose.cx, p_pose.cy,
+ // TODO: Move Mats outside from here
+ MatScaleFeats patch_feats(1, p_num_of_feats, p_roi);
+ DEBUG_PRINT(patch_feats);
+ MatScaleFeats temp(1, p_num_of_feats, p_roi);
+ get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy,
p_windows_size.width, p_windows_size.height,
- p_current_scale);
+ p_current_scale).copyTo(patch_feats.scale(0));
+ DEBUG_PRINT(patch_feats);
fft.forward_window(patch_feats, p_xf, temp);
+ DEBUG_PRINTM(p_xf);
p_model_xf = p_model_xf * (1. - interp_factor) + p_xf * interp_factor;
DEBUG_PRINTM(p_model_xf);
alphaf_den = (p_xf * xfconj);
} else {
// Kernel Ridge Regression, calculate alphas (in Fourier domain)
- const uint num_scales = BIG_BATCH_MODE ? p_num_scales : 1;
cv::Size sz(Fft::freq_size(p_roi));
- ComplexMat kf(sz.height, sz.width, num_scales);
- (*gaussian_correlation)(*this, kf, p_model_xf, p_model_xf, p_kernel_sigma, true);
+ ComplexMat kf(sz.height, sz.width, 1);
+ (*gaussian_correlation)(kf, p_model_xf, p_model_xf, p_kernel_sigma, true, *this);
DEBUG_PRINTM(kf);
p_model_alphaf_num = p_yf * kf;
- DEBUG_PRINTM(p_model_alphaf_num);
p_model_alphaf_den = kf * (kf + p_lambda);
- DEBUG_PRINTM(p_model_alphaf_den);
}
p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
DEBUG_PRINTM(p_model_alphaf);
void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int fit_size_y)
{
+ __dbgTracer.debug = m_debug;
+ TRACE("");
+
// check boundary, enforce min size
double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
if (x1 < 0) x1 = 0.;
p_roi.height = p_windows_size.height / p_cell_size;
p_scales.clear();
- if (m_use_scale)
- for (int i = -int(p_num_scales) / 2; i <= int(p_num_scales) / 2; ++i)
- p_scales.push_back(std::pow(p_scale_step, i));
- else
- p_scales.push_back(1.);
+ for (int i = -int(p_num_scales) / 2; i <= int(p_num_scales) / 2; ++i)
+ p_scales.push_back(std::pow(p_scale_step, i));
#ifdef CUFFT
if (p_roi.height * (p_roi.width / 2 + 1) > 1024) {
std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
std::exit(EXIT_FAILURE);
}
- CudaSafeCall(cudaSetDeviceFlags(cudaDeviceMapHost));
#else
p_xf.create(p_roi.height, p_roi.height / 2 + 1, p_num_of_feats);
#endif
#ifndef BIG_BATCH
for (auto scale: p_scales)
- d.threadctxs.emplace_back(p_roi, p_num_of_feats, 1, scale);
+ d.threadctxs.emplace_back(p_roi, p_num_of_feats, scale);
#else
- d.threadctxs.emplace_back(p_roi, p_num_of_feats * p_num_scales, p_num_scales);
+ d.threadctxs.emplace_back(p_roi, p_num_of_feats, p_num_scales);
#endif
+ gaussian_correlation.reset(new GaussianCorrelation(1, p_roi));
+
p_current_scale = 1.;
double min_size_ratio = std::max(5. * p_cell_size / p_windows_size.width, 5. * p_cell_size / p_windows_size.height);
fft.set_window(MatDynMem(cosine_window_function(p_roi.width, p_roi.height)));
// window weights, i.e. labels
- fft.forward(gaussian_shaped_labels(p_output_sigma, p_roi.width, p_roi.height), p_yf);
+ MatScales gsl(1, p_roi);
+ gaussian_shaped_labels(p_output_sigma, p_roi.width, p_roi.height).copyTo(gsl.plane(0));
+ fft.forward(gsl, p_yf);
DEBUG_PRINTM(p_yf);
// train initial model
- train(input_gray, input_rgb, 1.0);
+ train(input_rgb, input_gray, 1.0);
}
void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat &img, int fit_size_x, int fit_size_y)
tmp.w *= p_current_scale;
tmp.h *= p_current_scale;
- if (p_resize_image) tmp.scale(1 / p_downscale_factor);
+ if (p_resize_image)
+ tmp.scale(1 / p_downscale_factor);
if (p_fit_to_pw2) {
tmp.scale_x(1 / p_scale_factor_x);
tmp.scale_y(1 / p_scale_factor_y);
}
}
-void KCF_Tracker::findMaxReponse(uint &max_idx, cv::Point2f &new_location) const
+double KCF_Tracker::findMaxReponse(uint &max_idx, cv::Point2f &new_location) const
{
double max = -1.;
#ifndef BIG_BATCH
for (uint j = 0; j < d.threadctxs.size(); ++j) {
- if (d.threadctxs[j].max_response > max) {
- max = d.threadctxs[j].max_response;
+ if (d.threadctxs[j].max.response > max) {
+ max = d.threadctxs[j].max.response;
max_idx = j;
}
}
#else
- // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
for (uint j = 0; j < p_scales.size(); ++j) {
- if (d.threadctxs[0].max_responses[j] > max) {
- max = d.threadctxs[0].max_responses[j];
+ if (d.threadctxs[0].max[j].response > max) {
+ max = d.threadctxs[0].max[j].response;
max_idx = j;
}
}
#endif
- cv::Point2i &max_response_pt = IF_BIG_BATCH(d.threadctxs[0].max_locs[max_idx], d.threadctxs[max_idx].max_loc);
- cv::Mat &max_response_map = IF_BIG_BATCH(d.threadctxs[0].response_maps[max_idx], d.threadctxs[max_idx].response);
+ cv::Point2i &max_response_pt = IF_BIG_BATCH(d.threadctxs[0].max[max_idx].loc, d.threadctxs[max_idx].max.loc);
+ cv::Mat max_response_map = IF_BIG_BATCH(d.threadctxs[0].response.plane(max_idx), d.threadctxs[max_idx].response.plane(0));
DEBUG_PRINTM(max_response_map);
DEBUG_PRINT(max_response_pt);
new_location = max_response_pt;
}
DEBUG_PRINT(new_location);
+ return max;
}
void KCF_Tracker::track(cv::Mat &img)
{
- kcf_debug = m_debug;
- if (m_debug) std::cout << "NEW FRAME" << '\n';
+ __dbgTracer.debug = m_debug;
+ TRACE("");
cv::Mat input_gray, input_rgb = img.clone();
if (img.channels() == 3) {
#ifdef ASYNC
for (auto &it : d.threadctxs)
it.async_res = std::async(std::launch::async, [this, &input_gray, &input_rgb, &it]() -> void {
- scale_track(it, input_rgb, input_gray);
+ it.track(*this, input_rgb, input_gray);
});
for (auto const &it : d.threadctxs)
it.async_res.wait();
#else // !ASYNC
- // FIXME: Iterate correctly in big batch mode - perhaps have only one element in the list
NORMAL_OMP_PARALLEL_FOR
for (uint i = 0; i < d.threadctxs.size(); ++i)
- scale_track(d.threadctxs[i], input_rgb, input_gray);
+ d.threadctxs[i].track(*this, input_rgb, input_gray);
#endif
cv::Point2f new_location;
uint max_idx;
- findMaxReponse(max_idx, new_location);
+ max_response = findMaxReponse(max_idx, new_location);
p_pose.cx += p_current_scale * p_cell_size * double(new_location.x);
p_pose.cy += p_current_scale * p_cell_size * double(new_location.y);
train(input_rgb, input_gray, p_interp_factor);
}
-void KCF_Tracker::scale_track(ThreadCtx &vars, cv::Mat &input_rgb, cv::Mat &input_gray)
+void ThreadCtx::track(const KCF_Tracker &kcf, cv::Mat &input_rgb, cv::Mat &input_gray)
{
- // TODO: Move matrices to thread ctx
- int sizes[3] = {p_num_of_feats, p_windows_size.height, p_windows_size.width};
- MatDynMem patch_feats(3, sizes, CV_32FC1);
- MatDynMem temp(3, sizes, CV_32FC1);
+ TRACE("");
-#ifdef BIG_BATCH
BIG_BATCH_OMP_PARALLEL_FOR
- for (uint i = 0; i < p_num_scales; ++i)
-#endif
+ for (uint i = 0; i < IF_BIG_BATCH(kcf.p_num_scales, 1); ++i)
{
- get_features(patch_feats, input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy,
- this->p_windows_size.width, this->p_windows_size.height,
- this->p_current_scale * IF_BIG_BATCH(this->p_scales[i], vars.scale));
+ kcf.get_features(input_rgb, input_gray, kcf.p_pose.cx, kcf.p_pose.cy,
+ kcf.p_windows_size.width, kcf.p_windows_size.height,
+ kcf.p_current_scale * IF_BIG_BATCH(kcf.p_scales[i], scale))
+ .copyTo(patch_feats.scale(i));
+ DEBUG_PRINT(patch_feats.scale(i));
}
- fft.forward_window(patch_feats, vars.zf, temp);
- DEBUG_PRINTM(vars.zf);
+ kcf.fft.forward_window(patch_feats, zf, temp);
+ DEBUG_PRINTM(zf);
- if (m_use_linearkernel) {
- vars.kzf = vars.zf.mul(p_model_alphaf).sum_over_channels();
+ if (kcf.m_use_linearkernel) {
+ kzf = zf.mul(kcf.p_model_alphaf).sum_over_channels();
} else {
- (*gaussian_correlation)(*this, vars.kzf, vars.zf, this->p_model_xf, this->p_kernel_sigma);
- DEBUG_PRINTM(this->p_model_alphaf);
- DEBUG_PRINTM(vars.kzf);
- vars.kzf = vars.kzf.mul(this->p_model_alphaf);
+ gaussian_correlation(kzf, zf, kcf.p_model_xf, kcf.p_kernel_sigma, false, kcf);
+ DEBUG_PRINTM(kzf);
+ kzf = kzf.mul(kcf.p_model_alphaf);
}
- fft.inverse(vars.kzf, vars.response);
+ kcf.fft.inverse(kzf, response);
- DEBUG_PRINTM(vars.response);
+ DEBUG_PRINTM(response);
/* target location is at the maximum response. we must take into
account the fact that, if the target doesn't move, the peak
will appear at the top-left corner, not at the center (this is
discussed in the paper). the responses wrap around cyclically. */
+ double min_val, max_val;
+ cv::Point2i min_loc, max_loc;
#ifdef BIG_BATCH
- cv::split(vars.response, vars.response_maps);
-
- for (size_t i = 0; i < p_scales.size(); ++i) {
- double min_val, max_val;
- cv::Point2i min_loc, max_loc;
- cv::minMaxLoc(vars.response_maps[i], &min_val, &max_val, &min_loc, &max_loc);
+ for (size_t i = 0; i < kcf.p_scales.size(); ++i) {
+ cv::minMaxLoc(response.plane(i), &min_val, &max_val, &min_loc, &max_loc);
DEBUG_PRINT(max_loc);
- double weight = p_scales[i] < 1. ? p_scales[i] : 1. / p_scales[i];
- vars.max_responses[i] = max_val * weight;
- vars.max_locs[i] = max_loc;
+ double weight = kcf.p_scales[i] < 1. ? kcf.p_scales[i] : 1. / kcf.p_scales[i];
+ max[i].response = max_val * weight;
+ max[i].loc = max_loc;
}
#else
- double min_val;
- cv::Point2i min_loc;
- cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
+ cv::minMaxLoc(response.plane(0), &min_val, &max_val, &min_loc, &max_loc);
- DEBUG_PRINT(vars.max_loc);
+ DEBUG_PRINT(max_loc);
+ DEBUG_PRINT(max_val);
- double weight = vars.scale < 1. ? vars.scale : 1. / vars.scale;
- vars.max_response = vars.max_val * weight;
+ double weight = scale < 1. ? scale : 1. / scale;
+ max.response = max_val * weight;
+ max.loc = max_loc;
#endif
- return;
}
// ****************************************************************************
-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)
+cv::Mat KCF_Tracker::get_features(cv::Mat &input_rgb, cv::Mat &input_gray, int cx, int cy,
+ int size_x, int size_y, double scale) const
{
- assert(result_3d.size[0] == p_num_of_feats);
- assert(result_3d.size[1] == size_x);
- assert(result_3d.size[2] == size_y);
-
int size_x_scaled = floor(size_x * scale);
int size_y_scaled = floor(size_y * scale);
hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
- for (uint i = 0; i < hog_feat.size(); ++i) {
- cv::Mat result_plane(result_3d.dims - 1, result_3d.size + 1, result_3d.cv::Mat::type(), result_3d.ptr<void>(i));
- result_plane = hog_feat[i];
- }
+ int size[] = {p_num_of_feats, p_roi.height, p_roi.width};
+ cv::Mat result(3, size, CV_32F);
+ for (uint i = 0; i < hog_feat.size(); ++i)
+ hog_feat[i].copyTo(cv::Mat(size[1], size[2], CV_32FC1, result.ptr(i)));
+
+ return result;
}
-MatDynMem KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
+cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
{
- MatDynMem labels(dim2, dim1, CV_32FC1);
+ cv::Mat labels(dim2, dim1, CV_32FC1);
int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
int range_x[2] = {-dim1 / 2, dim1 - dim1 / 2};
return rot_labels;
}
-MatDynMem KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
+cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
{
- MatDynMem rot_patch(patch.size(), CV_32FC1);
+ cv::Mat rot_patch(patch.size(), CV_32FC1);
cv::Mat tmp_x_rot(patch.size(), CV_32FC1);
// circular rotate x-axis
// Returns sub-window of image input centered at [cx, cy] coordinates),
// with size [width, height]. If any pixels are outside of the image,
// they will replicate the values at the borders.
-cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height)
+cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int width, int height) const
{
cv::Mat patch;
return patch;
}
-void KCF_Tracker::GaussianCorrelation::operator()(const KCF_Tracker &kcf, ComplexMat &result, const ComplexMat &xf,
- const ComplexMat &yf, double sigma, bool auto_correlation)
+void KCF_Tracker::GaussianCorrelation::operator()(ComplexMat &result, const ComplexMat &xf, const ComplexMat &yf,
+ double sigma, bool auto_correlation, const KCF_Tracker &kcf)
{
+ TRACE("");
xf.sqr_norm(xf_sqr_norm);
if (auto_correlation) {
yf_sqr_norm = xf_sqr_norm;
} else {
yf.sqr_norm(yf_sqr_norm);
}
- xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
- //DEBUG_PRINTM(xyf);
- kcf.fft.inverse(xyf, ifft_res);
+ xyf = auto_correlation ? xf.sqr_mag() : xf * yf.conj(); // xf.muln(yf.conj());
+ DEBUG_PRINTM(xyf);
+
+ // ifft2 and sum over 3rd dimension, we dont care about individual channels
+ ComplexMat xyf_sum = xyf.sum_over_channels();
+ DEBUG_PRINTM(xyf_sum);
+ kcf.fft.inverse(xyf_sum, ifft_res);
+ DEBUG_PRINTM(ifft_res);
#ifdef CUFFT
+ // FIXME
cuda_gaussian_correlation(ifft_res.deviceMem(), k.deviceMem(), xf_sqr_norm.deviceMem(),
auto_correlation ? xf_sqr_norm.deviceMem() : yf_sqr_norm.deviceMem(), sigma,
xf.n_channels, xf.n_scales, kcf.p_roi.height, kcf.p_roi.width);
#else
- // ifft2 and sum over 3rd dimension, we dont care about individual channels
- //DEBUG_PRINTM(vars.ifft2_res);
- cv::Mat xy_sum;
- if (xf.channels() != p_num_scales * p_num_of_feats)
- xy_sum.create(vars.ifft2_res.size(), CV_32FC1);
- else
- xy_sum.create(vars.ifft2_res.size(), CV_32FC(p_scales.size()));
- xy_sum.setTo(0);
- for (int y = 0; y < vars.ifft2_res.rows; ++y) {
- float *row_ptr = vars.ifft2_res.ptr<float>(y);
- float *row_ptr_sum = xy_sum.ptr<float>(y);
- for (int x = 0; x < vars.ifft2_res.cols; ++x) {
- for (int sum_ch = 0; sum_ch < xy_sum.channels(); ++sum_ch) {
- row_ptr_sum[(x * xy_sum.channels()) + sum_ch] += std::accumulate(
- row_ptr + x * vars.ifft2_res.channels() + sum_ch * (vars.ifft2_res.channels() / xy_sum.channels()),
- (row_ptr + x * vars.ifft2_res.channels() +
- (sum_ch + 1) * (vars.ifft2_res.channels() / xy_sum.channels())),
- 0.f);
- }
- }
- }
- DEBUG_PRINTM(xy_sum);
-
- std::vector<cv::Mat> scales;
- cv::split(xy_sum, scales);
float numel_xf_inv = 1.f / (xf.cols * xf.rows * (xf.channels() / xf.n_scales));
for (uint i = 0; i < xf.n_scales; ++i) {
- cv::Mat in_roi(vars.in_all, cv::Rect(0, i * scales[0].rows, scales[0].cols, scales[0].rows));
- cv::exp(
- -1. / (sigma * sigma) *
- 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),
- in_roi);
- DEBUG_PRINTM(in_roi);
+ cv::Mat plane = ifft_res.plane(i);
+ DEBUG_PRINT(ifft_res.plane(i));
+ cv::exp(-1. / (sigma * sigma) * cv::max((xf_sqr_norm[i] + yf_sqr_norm[0] - 2 * ifft_res.plane(i))
+ * numel_xf_inv, 0), plane);
+ DEBUG_PRINTM(plane);
}
#endif
- kcf.fft.forward(k, result);
- return;
+ kcf.fft.forward(ifft_res, result);
}
float get_response_circular(cv::Point2i &pt, cv::Mat &response)
{
int x = pt.x;
int y = pt.y;
+ assert(response.dims == 2); // ensure .cols and .rows are valid
if (x < 0) x = response.cols + x;
if (y < 0) y = response.rows + y;
if (x >= response.cols) x = x - response.cols;
A.at<float>(i, 0) = float(p_scales[i] * p_scales[i]);
A.at<float>(i, 1) = float(p_scales[i]);
A.at<float>(i, 2) = 1;
-#ifdef BIG_BATCH
- fval.at<float>(i) = d.threadctxs.back().max_responses[i];
-#else
- fval.at<float>(i) = d.threadctxs[i].max_response;
-#endif
+ fval.at<float>(i) = d.threadctxs.back().IF_BIG_BATCH(max[i].response, max.response);
}
} else {
// only from neighbours
p_scales[index + 1] * p_scales[index + 1], p_scales[index + 1], 1);
#ifdef BIG_BATCH
fval = (cv::Mat_<float>(3, 1) <<
- d.threadctxs.back().max_responses[index - 1],
- d.threadctxs.back().max_responses[index + 0],
- d.threadctxs.back().max_responses[index + 1]);
+ d.threadctxs.back().max[index - 1].response,
+ d.threadctxs.back().max[index + 0].response,
+ d.threadctxs.back().max[index + 1].response);
#else
fval = (cv::Mat_<float>(3, 1) <<
- d.threadctxs[index - 1].max_response,
- d.threadctxs[index + 0].max_response,
- d.threadctxs[index + 1].max_response);
+ d.threadctxs[index - 1].max.response,
+ d.threadctxs[index + 0].max.response,
+ d.threadctxs[index + 1].max.response);
#endif
}