]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blobdiff - src/kcf.cpp
Simplify scale initialization
[hercules2020/kcf.git] / src / kcf.cpp
index b7633387ed4bee9079ba8a7526b0723249e59b12..eb8d4c0a0c32007d2e3a4ab68b11b08803cb1bc2 100644 (file)
@@ -3,10 +3,7 @@
 #include <thread>
 #include <algorithm>
 #include "threadctx.hpp"
-#include <ios>
-#include <iomanip>
-#include <stdarg.h>
-#include <stdio.h>
+#include "debug.h"
 
 #ifdef FFTW
 #include "fft_fftw.h"
 #include <omp.h>
 #endif // OPENMP
 
-class IOSave
-{
-    std::ios&           stream;
-    std::ios::fmtflags  flags;
-    std::streamsize     precision;
-    char                fill;
-public:
-    IOSave( std::ios& userStream )
-        : stream( userStream )
-        , flags( userStream.flags() )
-        , precision( userStream.precision() )
-        , fill( userStream.fill() )
-    {
-    }
-    ~IOSave()
-    {
-        stream.flags( flags );
-        stream.precision( precision );
-        stream.fill( fill );
-    }
-};
-
-class DbgTracer {
-    int indentLvl = 0;
-
-  public:
-    bool debug = false;
-
-    std::string indent() { return std::string(indentLvl * 4, ' '); }
-
-    class FTrace {
-        DbgTracer &t;
-        const char *funcName;
-
-      public:
-        FTrace(DbgTracer &dt, const char *fn, const char *format, ...) : t(dt), funcName(fn)
-        {
-            if (!t.debug) return;
-            char *arg;
-            va_list vl;
-            va_start(vl, format);
-            if (-1 == vasprintf(&arg, format, vl))
-                throw std::runtime_error("vasprintf error");
-            va_end(vl);
-
-            std::cerr << t.indent() << funcName << "(" << arg << ") {" << std::endl;
-            dt.indentLvl++;
-        }
-        ~FTrace()
-        {
-            if (!t.debug) return;
-            t.indentLvl--;
-            std::cerr << t.indent() << "}" << std::endl;
-        }
-    };
-
-    template <typename T>
-    void traceVal(const char *name, const T& obj, int line)
-    {
-        (void)line;
-        if (debug)
-            std::cerr << indent() << name /*<< " @" << line */ << " " << print(obj) << std::endl;
-    }
-
-    template <typename T> struct Printer {
-        const T &obj;
-        Printer(const T &_obj) : obj(_obj) {}
-    };
-
-    template <typename T> Printer<T> print(const T& obj) { return Printer<T>(obj); }
-    Printer<cv::Mat> print(const MatScales& obj) { return Printer<cv::Mat>(obj); }
-    Printer<cv::Mat> print(const MatFeats& obj) { return Printer<cv::Mat>(obj); }
-    Printer<cv::Mat> print(const MatScaleFeats& obj) { return Printer<cv::Mat>(obj); }
-};
-
-template <typename T>
-std::ostream &operator<<(std::ostream &os, const DbgTracer::Printer<T> &p) {
-    os << p.obj;
-    return os;
-}
-std::ostream &operator<<(std::ostream &os, const DbgTracer::Printer<cv::Mat> &p) {
-    IOSave s(os);
-    os << std::setprecision(3);
-    os << p.obj.size << " " << p.obj.channels() << "ch " << static_cast<const void*>(p.obj.data);
-    os << " = [ ";
-    constexpr size_t num = 10;
-    for (size_t i = 0; i < std::min(num, p.obj.total()); ++i)
-        os << *p.obj.ptr<float>(i) << ", ";
-    os << (num < p.obj.total() ? "... ]" : "]");
-    return os;
-}
-#if defined(CUFFT)
-std::ostream &operator<<(std::ostream &os, const cufftComplex &p) {
-    (void)p; // TODO
-    return os;
-}
-#endif
-template <>
-std::ostream &operator<<(std::ostream &os, const DbgTracer::Printer<ComplexMat> &p) {
-    IOSave s(os);
-    os << std::setprecision(3);
-    os << "<cplx> " << p.obj.size() << " " << p.obj.channels() << "ch " << p.obj.get_p_data();
-    os << " = [ ";
-    constexpr int num = 10;
-    for (int i = 0; i < std::min(num, p.obj.size().area()); ++i)
-        os << p.obj.get_p_data()[i] << ", ";
-    os << (num < p.obj.size().area() ? "... ]" : "]");
-    return os;
-}
-
 DbgTracer __dbgTracer;
 
-#define TRACE(...) const DbgTracer::FTrace __tracer(__dbgTracer, __PRETTY_FUNCTION__, ##__VA_ARGS__)
-
-#define DEBUG_PRINT(obj) __dbgTracer.traceVal(#obj, (obj), __LINE__)
-#define DEBUG_PRINTM(obj) DEBUG_PRINT(obj)
-
-
 template <typename T>
 T clamp(const T& n, const T& lower, const T& upper)
 {
@@ -173,16 +54,21 @@ KCF_Tracker::~KCF_Tracker()
     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
     // 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).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);
 
@@ -194,15 +80,12 @@ void KCF_Tracker::train(cv::Mat input_gray, cv::Mat input_rgb, double interp_fac
         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);
@@ -293,11 +176,8 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int f
     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) {
@@ -313,7 +193,6 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int f
         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
@@ -334,8 +213,7 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int f
     d.threadctxs.emplace_back(p_roi, p_num_of_feats, p_num_scales);
 #endif
 
-    gaussian_correlation.reset(
-                new GaussianCorrelation(IF_BIG_BATCH(p_num_scales, 1), p_roi));
+    gaussian_correlation.reset(new GaussianCorrelation(1, p_roi));
 
     p_current_scale = 1.;
 
@@ -363,7 +241,7 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect &bbox, int fit_size_x, int f
     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)
@@ -427,7 +305,7 @@ void KCF_Tracker::resizeImgs(cv::Mat &input_rgb, cv::Mat &input_gray)
     }
 }
 
-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
@@ -465,6 +343,7 @@ void KCF_Tracker::findMaxReponse(uint &max_idx, cv::Point2f &new_location) const
         new_location = max_response_pt;
     }
     DEBUG_PRINT(new_location);
+    return max;
 }
 
 void KCF_Tracker::track(cv::Mat &img)
@@ -499,7 +378,7 @@ void KCF_Tracker::track(cv::Mat &img)
 
     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);
@@ -538,18 +417,15 @@ void ThreadCtx::track(const KCF_Tracker &kcf, cv::Mat &input_rgb, cv::Mat &input
         DEBUG_PRINT(patch_feats.scale(i));
     }
 
-    DEBUG_PRINT(patch_feats);
     kcf.fft.forward_window(patch_feats, zf, temp);
     DEBUG_PRINTM(zf);
 
     if (kcf.m_use_linearkernel) {
         kzf = zf.mul(kcf.p_model_alphaf).sum_over_channels();
     } else {
-        gaussian_correlation(kcf, kzf, zf, kcf.p_model_xf, kcf.p_kernel_sigma);
-        DEBUG_PRINTM(kcf.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);
-        DEBUG_PRINTM(kzf);
     }
     kcf.fft.inverse(kzf, response);
 
@@ -573,6 +449,7 @@ void ThreadCtx::track(const KCF_Tracker &kcf, cv::Mat &input_rgb, cv::Mat &input
     cv::minMaxLoc(response.plane(0), &min_val, &max_val, &min_loc, &max_loc);
 
     DEBUG_PRINT(max_loc);
+    DEBUG_PRINT(max_val);
 
     double weight = scale < 1. ? scale : 1. / scale;
     max.response = max_val * weight;
@@ -800,8 +677,8 @@ cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int wid
     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);
@@ -811,54 +688,37 @@ void KCF_Tracker::GaussianCorrelation::operator()(const KCF_Tracker &kcf, Comple
         yf.sqr_norm(yf_sqr_norm);
     }
     xyf = auto_correlation ? xf.sqr_mag() : xf * yf.conj(); // xf.muln(yf.conj());
-    //DEBUG_PRINTM(xyf);
-    kcf.fft.inverse(xyf, ifft_res);
+    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(ifft_res);
-    cv::Mat xy_sum;
-    if (xf.channels() != kcf.p_num_scales * kcf.p_num_of_feats)
-        xy_sum.create(ifft_res.size(), CV_32FC1);
-    else
-        xy_sum.create(ifft_res.size(), CV_32FC(kcf.p_scales.size()));
-    xy_sum.setTo(0);
-    for (int y = 0; y < ifft_res.rows; ++y) {
-        float *row_ptr = ifft_res.ptr<float>(y);
-        float *row_ptr_sum = xy_sum.ptr<float>(y);
-        for (int x = 0; x < ifft_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 * ifft_res.channels() + sum_ch * (ifft_res.channels() / xy_sum.channels()),
-                    (row_ptr + x * ifft_res.channels() +
-                     (sum_ch + 1) * (ifft_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 k_roi = k.plane(i);
-        cv::exp(-1. / (sigma * sigma) * cv::max((xf_sqr_norm[i] + yf_sqr_norm[0] - 2 * scales[i]) * numel_xf_inv, 0),
-                k_roi);
-        DEBUG_PRINTM(k_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);
+    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;