]> rtime.felk.cvut.cz Git - hercules2020/kcf.git/blobdiff - src/kcf.cpp
Cleaned FFTW version
[hercules2020/kcf.git] / src / kcf.cpp
index 03555abbf428cc233a7875bc8dabc575037dd221..bb94a5390cbd770b0ece4464e1d6dc0b4aa1f878 100644 (file)
@@ -4,25 +4,54 @@
 #include <future>
 #include <algorithm>
 
-
-#ifdef OPENCV_CUFFT
-#include <cuda.h>
-#include <cuda_runtime.h>
-#endif //OPENCV_CUFFT
-
 #ifdef FFTW
-  #ifndef CUFFTW
-    #include <fftw3.h>
-  #else
-    #include <cufftw.h>
-  #endif
+  #include "fft_fftw.h"
+  #define FFT Fftw
+#elif defined(CUFFT)
+  #include "fft_cufft.h"
+  #define FFT cuFFT
+#else
+  #include "fft_opencv.h"
+  #define FFT FftOpencv
 #endif
 
 #ifdef OPENMP
 #include <omp.h>
+#endif //OPENMP
+
+#define DEBUG_PRINT(obj) if (m_debug) {std::cout << #obj << " @" << __LINE__ << std::endl << (obj) << std::endl;}
+#define DEBUG_PRINTM(obj) if (m_debug) {std::cout << #obj << " @" << __LINE__ << " " << (obj).size() << " CH: " << (obj).channels() << std::endl << (obj) << std::endl;}
+
+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) {}
+
+KCF_Tracker::KCF_Tracker()
+    : fft(*new FFT()) {}
+
+KCF_Tracker::~KCF_Tracker()
+{
+    delete &fft;
+#ifdef CUFFT
+    for (int i = 0;i < p_num_scales;++i) {
+        CudaSafeCall(cudaFreeHost(scale_vars[i].xf_sqr_norm));
+        CudaSafeCall(cudaFreeHost(scale_vars[i].yf_sqr_norm));
+        CudaSafeCall(cudaFreeHost(scale_vars[i].data_i_1ch));
+        CudaSafeCall(cudaFreeHost(scale_vars[i].data_i_features));
+        CudaSafeCall(cudaFree(scale_vars[i].gauss_corr_res));
+        CudaSafeCall(cudaFreeHost(scale_vars[i].rot_labels_data));
+        CudaSafeCall(cudaFreeHost(scale_vars[i].data_features));
+    }
+#else
+    for (int i = 0;i < p_num_scales;++i) {
+        free(scale_vars[i].xf_sqr_norm);
+        free(scale_vars[i].yf_sqr_norm);
+    }
 #endif
+}
 
-void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
+void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox, int fit_size_x, int fit_size_y)
 {
     //check boundary, enforce min size
     double x1 = bbox.x, x2 = bbox.x + bbox.width, y1 = bbox.y, y2 = bbox.y + bbox.height;
@@ -57,7 +86,7 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
     p_pose.w = x2-x1;
     p_pose.h = y2-y1;
     p_pose.cx = x1 + p_pose.w/2.;
-    p_pose.cy = y1 + p_pose.h/2.;
+    p_pose.cy = y1 + p_pose.h /2.;
 
 
     cv::Mat input_gray, input_rgb = img.clone();
@@ -68,12 +97,36 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
         img.convertTo(input_gray, CV_32FC1);
 
     // don't need too large image
-    if (p_pose.w * p_pose.h > 100.*100.) {
-        std::cout << "resizing image by factor of 2" << std::endl;
+    if (p_pose.w * p_pose.h > 100.*100. && (fit_size_x == -1 || fit_size_y == -1)) {
+        std::cout << "resizing image by factor of " << 1/p_downscale_factor << std::endl;
         p_resize_image = true;
-        p_pose.scale(0.5);
-        cv::resize(input_gray, input_gray, cv::Size(0,0), 0.5, 0.5, cv::INTER_AREA);
-        cv::resize(input_rgb, input_rgb, cv::Size(0,0), 0.5, 0.5, cv::INTER_AREA);
+        p_pose.scale(p_downscale_factor);
+        cv::resize(input_gray, input_gray, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
+        cv::resize(input_rgb, input_rgb, cv::Size(0,0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
+    } else if (!(fit_size_x == -1 && fit_size_y == -1)) {
+        if (fit_size_x%p_cell_size != 0 || fit_size_y%p_cell_size != 0) {
+            std::cerr << "Fit size does not fit to hog cell size. The dimensions have to be divisible by HOG cell size, which is: " << p_cell_size << std::endl;;
+            std::exit(EXIT_FAILURE);
+        }
+        double tmp;
+        if (( tmp = (p_pose.w * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_x)
+            p_scale_factor_x = fit_size_x/tmp;
+        if (( tmp = (p_pose.h * (1. + p_padding) / p_cell_size) * p_cell_size ) != fit_size_y)
+            p_scale_factor_y = fit_size_y/tmp;
+        std::cout << "resizing image horizontaly by factor of " << p_scale_factor_x
+                  << " and verticaly by factor of " << p_scale_factor_y << std::endl;
+        p_fit_to_pw2 = true;
+        p_pose.scale_x(p_scale_factor_x);
+        p_pose.scale_y(p_scale_factor_y);
+        if (p_scale_factor_x != 1 && p_scale_factor_y != 1) {
+            if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
+                cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
+                cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
+            } else {
+                cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
+                cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
+            }
+        }
     }
 
     //compute win size + fit to fhog cell size
@@ -87,6 +140,18 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
     else
         p_scales.push_back(1.);
 
+    for (int i = 0;i<p_num_scales;++i) {
+        scale_vars.push_back(Scale_vars());
+    }
+
+    p_num_of_feats = 31;
+    if(m_use_color) p_num_of_feats += 3;
+    if(m_use_cnfeat) p_num_of_feats += 10;
+    p_roi_width = p_windows_size[0]/p_cell_size;
+    p_roi_height = p_windows_size[1]/p_cell_size;
+
+    init_scale_vars();
+
     p_current_scale = 1.;
 
     double min_size_ratio = std::max(5.*p_cell_size/p_windows_size[0], 5.*p_cell_size/p_windows_size[1]);
@@ -100,17 +165,23 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
 
     p_output_sigma = std::sqrt(p_pose.w*p_pose.h) * p_output_sigma_factor / static_cast<double>(p_cell_size);
 
-#if defined(FFTW) && defined(OPENMP)
-    fftw_init_threads();
-    fftw_plan_with_nthreads(omp_get_max_threads());
-#endif
+    fft.init(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size, p_num_of_feats, p_num_scales, m_use_big_batch);
+    fft.set_window(cosine_window_function(p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
 
+    scale_vars[0].flag = Tracker_flags::TRACKER_INIT;
     //window weights, i.e. labels
-    p_yf = fft2(gaussian_shaped_labels(p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size));
-    p_cos_window = cosine_window_function(p_yf.cols, p_yf.rows);
+    gaussian_shaped_labels(scale_vars[0], p_output_sigma, p_windows_size[0]/p_cell_size, p_windows_size[1]/p_cell_size);
+    DEBUG_PRINTM(scale_vars[0].rot_labels);
+
+    fft.forward(scale_vars[0]);
+    DEBUG_PRINTM(p_yf);
+
     //obtain a sub-window for training initial model
-    std::vector<cv::Mat> path_feat = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1]);
-    p_model_xf = fft2(path_feat, p_cos_window);
+    get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], scale_vars[0]);
+    fft.forward_window(scale_vars[0]);
+    DEBUG_PRINTM(p_model_xf);
+    scale_vars[0].flag = Tracker_flags::AUTO_CORRELATION;
+
 
     if (m_use_linearkernel) {
         ComplexMat xfconj = p_model_xf.conj();
@@ -118,24 +189,138 @@ void KCF_Tracker::init(cv::Mat &img, const cv::Rect & bbox)
         p_model_alphaf_den = (p_model_xf * xfconj);
     } else {
         //Kernel Ridge Regression, calculate alphas (in Fourier domain)
-        ComplexMat kf = gaussian_correlation(p_model_xf, p_model_xf, p_kernel_sigma, true);
-        p_model_alphaf_num = p_yf * kf;
-        p_model_alphaf_den = kf * (kf + p_lambda);
+        gaussian_correlation(scale_vars[0], p_model_xf, p_model_xf, p_kernel_sigma, true);
+        DEBUG_PRINTM(scale_vars[0].kf);
+        p_model_alphaf_num = p_yf * scale_vars[0].kf;
+        DEBUG_PRINTM(p_model_alphaf_num);
+        p_model_alphaf_den = scale_vars[0].kf * (scale_vars[0].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);
 //        p_model_alphaf = p_yf / (kf + p_lambda);   //equation for fast training
 }
 
-void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img)
+void KCF_Tracker::init_scale_vars()
+{
+    double alloc_size;
+
+#ifdef CUFFT
+    if (p_windows_size[1]/p_cell_size*(p_windows_size[0]/p_cell_size/2+1) > 1024) {
+        std::cerr << "Window after forward FFT is too big for CUDA kernels. Plese use -f to set "
+        "the window dimensions so its size is less or equal to " << 1024*p_cell_size*p_cell_size*2+1 <<
+        " pixels . Currently the size of the window is: " <<  p_windows_size[0] << "x" <<  p_windows_size[1] <<
+        " which is  " <<  p_windows_size[0]*p_windows_size[1] << " pixels. " << std::endl;
+        std::exit(EXIT_FAILURE);
+    }
+
+    if (m_use_linearkernel){
+        std::cerr << "cuFFT supports only Gaussian kernel." << std::endl;
+        std::exit(EXIT_FAILURE);
+    }
+    cudaSetDeviceFlags(cudaDeviceMapHost);
+
+    for (int i = 0;i<p_num_scales;++i) {
+        alloc_size = p_windows_size[0]/p_cell_size*p_windows_size[1]/p_cell_size*sizeof(cufftReal);
+        CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].data_i_1ch, alloc_size, cudaHostAllocMapped));
+        CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].data_i_1ch_d, (void*)scale_vars[i].data_i_1ch, 0));
+
+        alloc_size = p_windows_size[0]/p_cell_size*p_windows_size[1]/p_cell_size*p_num_of_feats*sizeof(cufftReal);
+        CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].data_i_features, alloc_size, cudaHostAllocMapped));
+        CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].data_i_features_d, (void*)scale_vars[i].data_i_features, 0));
+
+
+        scale_vars[i].ifft2_res = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC(p_num_of_feats), scale_vars[i].data_i_features);
+        scale_vars[i].response = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC1, scale_vars[i].data_i_1ch);
+
+        scale_vars[i].zf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
+        scale_vars[i].kzf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, 1);
+        scale_vars[i].kf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, 1);
+
+#ifdef BIG_BATCH
+        alloc_size = p_num_of_feats;
+#else
+        alloc_size = 1;
+#endif
+
+        CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].xf_sqr_norm, alloc_size*sizeof(float), cudaHostAllocMapped));
+        CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].xf_sqr_norm_d, (void*)scale_vars[i].xf_sqr_norm, 0));
+
+        CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].yf_sqr_norm, sizeof(float), cudaHostAllocMapped));
+        CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].yf_sqr_norm_d, (void*)scale_vars[i].yf_sqr_norm, 0));
+
+        alloc_size =(p_windows_size[0]/p_cell_size)*(p_windows_size[1]/p_cell_size)*alloc_size*sizeof(float);
+        CudaSafeCall(cudaMalloc((void**)&scale_vars[i].gauss_corr_res, alloc_size));
+        scale_vars[i].in_all = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC1, scale_vars[i].gauss_corr_res);
+
+        alloc_size = (p_windows_size[0]/p_cell_size)*(p_windows_size[1]/p_cell_size)*alloc_size*sizeof(float);
+        CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].rot_labels_data, alloc_size, cudaHostAllocMapped));
+        CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].rot_labels_data_d, (void*)scale_vars[i].rot_labels_data, 0));
+        scale_vars[i].rot_labels = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC1, scale_vars[i].rot_labels_data);
+
+        alloc_size = (p_windows_size[0]/p_cell_size)*((p_windows_size[1]/p_cell_size)*p_num_of_feats)*sizeof(cufftReal);
+        CudaSafeCall(cudaHostAlloc((void**)&scale_vars[i].data_features, alloc_size, cudaHostAllocMapped));
+        CudaSafeCall(cudaHostGetDevicePointer((void**)&scale_vars[i].data_features_d, (void*)scale_vars[i].data_features, 0));
+        scale_vars[i].fw_all = cv::Mat((p_windows_size[1]/p_cell_size)*p_num_of_feats, p_windows_size[0]/p_cell_size, CV_32F, scale_vars[i].data_features);
+    }
+#else
+if(m_use_big_batch)
+        alloc_size = p_num_of_feats;
+else
+        alloc_size = 1;
+
+    for (int i = 0;i<p_num_scales;++i) {
+        scale_vars[i].xf_sqr_norm = (float*) malloc(alloc_size*sizeof(float));
+        scale_vars[i].yf_sqr_norm = (float*) malloc(sizeof(float));
+
+        scale_vars[i].patch_feats.reserve(p_num_of_feats);
+#ifdef FFTW
+        scale_vars[i].ifft2_res = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC(p_num_of_feats));
+        scale_vars[i].response = cv::Mat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, CV_32FC1);
+
+        scale_vars[i].zf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
+        scale_vars[i].kzf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, 1);
+        scale_vars[i].kf = ComplexMat(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, 1);
+
+        scale_vars[i].in_all = cv::Mat((p_windows_size[1]/p_cell_size)*p_num_of_feats, p_windows_size[0]/p_cell_size, CV_32F);
+        scale_vars[i].fw_all = cv::Mat((p_windows_size[1]/p_cell_size)*p_num_of_feats, p_windows_size[0]/p_cell_size, CV_32F);
+#else
+        scale_vars[i].zf = ComplexMat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, p_num_of_feats);
+        //We use scale_vars[0] for updating the tracker, so we only allocate memory for  its xf only.
+        if (i==0)
+            scale_vars[i].xf = ComplexMat(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, p_num_of_feats);
+#endif
+    }
+#endif
+#if defined(FFTW) || defined(CUFFT)
+    p_model_xf.create(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
+    p_yf.create(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, 1);
+    //We use scale_vars[0] for updating the tracker, so we only allocate memory for  its xf only.
+    scale_vars[0].xf.create(p_windows_size[1]/p_cell_size, (p_windows_size[0]/p_cell_size)/2+1, p_num_of_feats);
+#else
+    p_model_xf.create(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, p_num_of_feats);
+    p_yf.create(p_windows_size[1]/p_cell_size, p_windows_size[0]/p_cell_size, 1);
+#endif
+    scale_vars[0].p_model_xf_ptr = & p_model_xf;
+    scale_vars[0].p_yf_ptr = & p_yf;
+}
+
+void KCF_Tracker::setTrackerPose(BBox_c &bbox, cv::Mat & img, int fit_size_x, int fit_size_y)
 {
-    init(img, bbox.get_rect());
+    init(img, bbox.get_rect(), fit_size_x, fit_size_y);
 }
 
 void KCF_Tracker::updateTrackerPosition(BBox_c &bbox)
 {
     if (p_resize_image) {
         BBox_c tmp = bbox;
-        tmp.scale(0.5);
+        tmp.scale(p_downscale_factor);
+        p_pose.cx = tmp.cx;
+        p_pose.cy = tmp.cy;
+    } else if (p_fit_to_pw2) {
+        BBox_c tmp = bbox;
+        tmp.scale_x(p_scale_factor_x);
+        tmp.scale_y(p_scale_factor_y);
         p_pose.cx = tmp.cx;
         p_pose.cy = tmp.cy;
     } else {
@@ -151,14 +336,19 @@ BBox_c KCF_Tracker::getBBox()
     tmp.h *= p_current_scale;
 
     if (p_resize_image)
-        tmp.scale(2);
+        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);
+    }
 
     return tmp;
 }
 
 void KCF_Tracker::track(cv::Mat &img)
 {
-
+    if (m_debug)
+        std::cout << "NEW FRAME" << '\n';
     cv::Mat input_gray, input_rgb = img.clone();
     if (img.channels() == 3){
         cv::cvtColor(img, input_gray, CV_BGR2GRAY);
@@ -168,112 +358,89 @@ void KCF_Tracker::track(cv::Mat &img)
 
     // don't need too large image
     if (p_resize_image) {
-        cv::resize(input_gray, input_gray, cv::Size(0, 0), 0.5, 0.5, cv::INTER_AREA);
-        cv::resize(input_rgb, input_rgb, cv::Size(0, 0), 0.5, 0.5, cv::INTER_AREA);
+        cv::resize(input_gray, input_gray, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
+        cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_downscale_factor, p_downscale_factor, cv::INTER_AREA);
+    } else if (p_fit_to_pw2 && p_scale_factor_x != 1 && p_scale_factor_y != 1) {
+        if (p_scale_factor_x < 1 && p_scale_factor_y < 1) {
+            cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
+            cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_AREA);
+        } else {
+            cv::resize(input_gray, input_gray, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
+            cv::resize(input_rgb, input_rgb, cv::Size(0, 0), p_scale_factor_x, p_scale_factor_y, cv::INTER_LINEAR);
+        }
     }
 
-
-    std::vector<cv::Mat> patch_feat;
     double max_response = -1.;
-    cv::Mat max_response_map;
-    cv::Point2i max_response_pt;
     int scale_index = 0;
-    std::vector<double> scale_responses;
+    cv::Point2i *max_response_pt = nullptr;
+    cv::Mat *max_response_map = nullptr;
 
-    if (m_use_multithreading){
-        std::vector<std::future<cv::Mat>> async_res(p_scales.size());
-        for (size_t i = 0; i < p_scales.size(); ++i) {
+    if(m_use_multithreading) {
+        std::vector<std::future<void>> async_res(p_scales.size());
+        for (size_t i = 0; i < scale_vars.size(); ++i) {
             async_res[i] = std::async(std::launch::async,
-                                      [this, &input_gray, &input_rgb, i]() -> cv::Mat
-                                      {
-                                          std::vector<cv::Mat> patch_feat_async = get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy, this->p_windows_size[0],
-                                                                                               this->p_windows_size[1], this->p_current_scale * this->p_scales[i]);
-                                          ComplexMat zf = fft2(patch_feat_async, this->p_cos_window);
-                                          if (m_use_linearkernel)
-                                              return ifft2((p_model_alphaf * zf).sum_over_channels());
-                                          else {
-                                              ComplexMat kzf = gaussian_correlation(zf, this->p_model_xf, this->p_kernel_sigma);
-                                              return ifft2(this->p_model_alphaf * kzf);
-                                          }
-                                      });
+                                [this, &input_gray, &input_rgb, i]() -> void
+                                {return scale_track(this->scale_vars[i], input_rgb, input_gray, this->p_scales[i]);});
         }
-
         for (size_t i = 0; i < p_scales.size(); ++i) {
-            // wait for result
             async_res[i].wait();
-            cv::Mat response = async_res[i].get();
-
-            double min_val, max_val;
-            cv::Point2i min_loc, max_loc;
-            cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
-
-            double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
-            if (max_val*weight > max_response) {
-                max_response = max_val*weight;
-                max_response_map = response;
-                max_response_pt = max_loc;
+            if (this->scale_vars[i].max_response > max_response) {
+                max_response = this->scale_vars[i].max_response;
+                max_response_pt = & this->scale_vars[i].max_loc;
+                max_response_map = & this->scale_vars[i].response;
                 scale_index = i;
             }
-            scale_responses.push_back(max_val*weight);
         }
     } else {
-#pragma omp parallel for ordered  private(patch_feat) schedule(dynamic)
-        for (size_t i = 0; i < p_scales.size(); ++i) {
-            patch_feat = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], p_current_scale * p_scales[i]);
-            ComplexMat zf = fft2(patch_feat, p_cos_window);
-            cv::Mat response;
-            if (m_use_linearkernel)
-                response = ifft2((p_model_alphaf * zf).sum_over_channels());
-            else {
-                ComplexMat kzf = gaussian_correlation(zf, p_model_xf, p_kernel_sigma);
-                response = ifft2(p_model_alphaf * kzf);
-            }
-
-            /* 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;
-            cv::minMaxLoc(response, &min_val, &max_val, &min_loc, &max_loc);
-
-            double weight = p_scales[i] < 1. ? p_scales[i] : 1./p_scales[i];
+#pragma omp parallel for schedule(dynamic)
+        for (size_t i = 0; i < scale_vars.size(); ++i) {
+            scale_track(this->scale_vars[i], input_rgb, input_gray, this->p_scales[i]);
 #pragma omp critical
             {
-                if (max_val*weight > max_response) {
-                    max_response = max_val*weight;
-                    max_response_map = response;
-                    max_response_pt = max_loc;
+                if (this->scale_vars[i].max_response > max_response) {
+                    max_response = this->scale_vars[i].max_response;
+                    max_response_pt = & this->scale_vars[i].max_loc;
+                    max_response_map = & this->scale_vars[i].response;
                     scale_index = i;
                 }
             }
-#pragma omp ordered
-            scale_responses.push_back(max_val*weight);
         }
     }
 
+    DEBUG_PRINTM(*max_response_map);
+    DEBUG_PRINT(*max_response_pt);
+
     //sub pixel quadratic interpolation from neighbours
-    if (max_response_pt.y > max_response_map.rows / 2) //wrap around to negative half-space of vertical axis
-        max_response_pt.y = max_response_pt.y - max_response_map.rows;
-    if (max_response_pt.x > max_response_map.cols / 2) //same for horizontal axis
-        max_response_pt.x = max_response_pt.x - max_response_map.cols;
+    if (max_response_pt->y > max_response_map->rows / 2) //wrap around to negative half-space of vertical axis
+        max_response_pt->y = max_response_pt->y - max_response_map->rows;
+    if (max_response_pt->x > max_response_map->cols / 2) //same for horizontal axis
+        max_response_pt->x = max_response_pt->x - max_response_map->cols;
 
-    cv::Point2f new_location(max_response_pt.x, max_response_pt.y);
+    cv::Point2f new_location(max_response_pt->x, max_response_pt->y);
+    DEBUG_PRINT(new_location);
 
     if (m_use_subpixel_localization)
-        new_location = sub_pixel_peak(max_response_pt, max_response_map);
+        new_location = sub_pixel_peak(*max_response_pt, *max_response_map);
+    DEBUG_PRINT(new_location);
 
     p_pose.cx += p_current_scale*p_cell_size*new_location.x;
     p_pose.cy += p_current_scale*p_cell_size*new_location.y;
-    if (p_pose.cx < 0) p_pose.cx = 0;
-    if (p_pose.cx > img.cols-1) p_pose.cx = img.cols-1;
-    if (p_pose.cy < 0) p_pose.cy = 0;
-    if (p_pose.cy > img.rows-1) p_pose.cy = img.rows-1;
+    if (p_fit_to_pw2) {
+        if (p_pose.cx < 0) p_pose.cx = 0;
+        if (p_pose.cx > (img.cols*p_scale_factor_x)-1) p_pose.cx = (img.cols*p_scale_factor_x)-1;
+        if (p_pose.cy < 0) p_pose.cy = 0;
+        if (p_pose.cy > (img.rows*p_scale_factor_y)-1) p_pose.cy = (img.rows*p_scale_factor_y)-1;
+    } else {
+        if (p_pose.cx < 0) p_pose.cx = 0;
+        if (p_pose.cx > img.cols-1) p_pose.cx = img.cols-1;
+        if (p_pose.cy < 0) p_pose.cy = 0;
+        if (p_pose.cy > img.rows-1) p_pose.cy = img.rows-1;
+    }
 
     //sub grid scale interpolation
     double new_scale = p_scales[scale_index];
     if (m_use_subgrid_scale)
-        new_scale = sub_grid_scale(scale_responses, scale_index);
+        new_scale = sub_grid_scale(scale_index);
 
     p_current_scale *= new_scale;
 
@@ -281,27 +448,28 @@ void KCF_Tracker::track(cv::Mat &img)
         p_current_scale = p_min_max_scale[0];
     if (p_current_scale > p_min_max_scale[1])
         p_current_scale = p_min_max_scale[1];
-
     //obtain a subwindow for training at newly estimated target position
-    patch_feat = get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], p_current_scale);
-    ComplexMat xf = fft2(patch_feat, p_cos_window);
+    get_features(input_rgb, input_gray, p_pose.cx, p_pose.cy, p_windows_size[0], p_windows_size[1], scale_vars[0], p_current_scale);
+    scale_vars[0].flag = Tracker_flags::TRACKER_UPDATE;
+    fft.forward_window(scale_vars[0]);
 
     //subsequent frames, interpolate model
-    p_model_xf = p_model_xf * (1. - p_interp_factor) + xf * p_interp_factor;
+    p_model_xf = p_model_xf * (1. - p_interp_factor) + scale_vars[0].xf * p_interp_factor;
 
     ComplexMat alphaf_num, alphaf_den;
 
     if (m_use_linearkernel) {
-        ComplexMat xfconj = xf.conj();
+        ComplexMat xfconj = scale_vars[0].xf.conj();
         alphaf_num = xfconj.mul(p_yf);
-        alphaf_den = (xf * xfconj);
+        alphaf_den = (scale_vars[0].xf * xfconj);
     } else {
+        scale_vars[0].flag = Tracker_flags::AUTO_CORRELATION;
         //Kernel Ridge Regression, calculate alphas (in Fourier domain)
-        ComplexMat kf = gaussian_correlation(xf, xf, p_kernel_sigma, true);
+        gaussian_correlation(scale_vars[0], scale_vars[0].xf, scale_vars[0].xf, p_kernel_sigma, true);
 //        ComplexMat alphaf = p_yf / (kf + p_lambda); //equation for fast training
 //        p_model_alphaf = p_model_alphaf * (1. - p_interp_factor) + alphaf * p_interp_factor;
-        alphaf_num = p_yf * kf;
-        alphaf_den = kf * (kf + p_lambda);
+        alphaf_num = p_yf * scale_vars[0].kf;
+        alphaf_den = scale_vars[0].kf * (scale_vars[0].kf + p_lambda);
     }
 
     p_model_alphaf_num = p_model_alphaf_num * (1. - p_interp_factor) + alphaf_num * p_interp_factor;
@@ -309,9 +477,50 @@ void KCF_Tracker::track(cv::Mat &img)
     p_model_alphaf = p_model_alphaf_num / p_model_alphaf_den;
 }
 
+void KCF_Tracker::scale_track(Scale_vars & vars, cv::Mat & input_rgb, cv::Mat & input_gray, double scale)
+{
+    get_features(input_rgb, input_gray, this->p_pose.cx, this->p_pose.cy, this->p_windows_size[0], this->p_windows_size[1],
+                                vars, this->p_current_scale * scale);
+
+    vars.flag = Tracker_flags::SCALE_RESPONSE;
+    fft.forward_window(vars);
+    DEBUG_PRINTM(vars.zf);
+
+    if (m_use_linearkernel) {
+                vars.kzf = (vars.zf.mul2(this->p_model_alphaf)).sum_over_channels();
+                vars.flag = Tracker_flags::RESPONSE;
+                fft.inverse(vars);
+    } else {
+        vars.flag = Tracker_flags::CROSS_CORRELATION;
+        gaussian_correlation(vars, vars.zf, this->p_model_xf, this->p_kernel_sigma);
+        DEBUG_PRINTM(this->p_model_alphaf);
+        DEBUG_PRINTM(vars.kzf);
+        DEBUG_PRINTM(this->p_model_alphaf * vars.kzf);
+        vars.flag = Tracker_flags::RESPONSE;
+        vars.kzf = this->p_model_alphaf * vars.kzf;
+        //TODO Add support for fft.inverse(vars) for CUFFT
+        fft.inverse(vars);
+    }
+
+    DEBUG_PRINTM(vars.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;
+    cv::Point2i min_loc;
+    cv::minMaxLoc(vars.response, &min_val, &vars.max_val, &min_loc, &vars.max_loc);
+
+    DEBUG_PRINT(vars.max_loc);
+
+    double weight = scale < 1. ? scale : 1./scale;
+    vars.max_response = vars.max_val*weight;
+}
+
 // ****************************************************************************
 
-std::vector<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)
+void KCF_Tracker::get_features(cv::Mat & input_rgb, cv::Mat & input_gray, int cx, int cy, int size_x, int size_y, Scale_vars &vars, double scale)
 {
     int size_x_scaled = floor(size_x*scale);
     int size_y_scaled = floor(size_y*scale);
@@ -328,7 +537,7 @@ std::vector<cv::Mat> KCF_Tracker::get_features(cv::Mat & input_rgb, cv::Mat & in
     }
 
     // get hog(Histogram of Oriented Gradients) features
-    std::vector<cv::Mat> hog_feat = FHoG::extract(patch_gray, 2, p_cell_size, 9);
+    FHoG::extract(patch_gray, vars, 2, p_cell_size, 9);
 
     //get color rgb features (simple r,g,b channels)
     std::vector<cv::Mat> color_feat;
@@ -359,11 +568,11 @@ std::vector<cv::Mat> KCF_Tracker::get_features(cv::Mat & input_rgb, cv::Mat & in
         color_feat.insert(color_feat.end(), cn_feat.begin(), cn_feat.end());
     }
 
-    hog_feat.insert(hog_feat.end(), color_feat.begin(), color_feat.end());
-    return hog_feat;
+    vars.patch_feats.insert(vars.patch_feats.end(), color_feat.begin(), color_feat.end());
+    return;
 }
 
-cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
+void KCF_Tracker::gaussian_shaped_labels(Scale_vars & vars, double sigma, int dim1, int dim2)
 {
     cv::Mat labels(dim2, dim1, CV_32FC1);
     int range_y[2] = {-dim2 / 2, dim2 - dim2 / 2};
@@ -380,11 +589,12 @@ cv::Mat KCF_Tracker::gaussian_shaped_labels(double sigma, int dim1, int dim2)
     }
 
     //rotate so that 1 is at top-left corner (see KCF paper for explanation)
-    cv::Mat rot_labels = circshift(labels, range_x[0], range_y[0]);
+    cv::Mat tmp = circshift(labels, range_x[0], range_y[0]);
+    tmp.copyTo(vars.rot_labels);
     //sanity check, 1 at top left corner
-    assert(rot_labels.at<float>(0,0) >= 1.f - 1e-10f);
+    assert(vars.rot_labels.at<float>(0,0) >= 1.f - 1e-10f);
 
-    return rot_labels;
+    return;
 }
 
 cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
@@ -451,351 +661,6 @@ cv::Mat KCF_Tracker::circshift(const cv::Mat &patch, int x_rot, int y_rot)
     return rot_patch;
 }
 
-ComplexMat KCF_Tracker::fft2(const cv::Mat &input)
-{
-    cv::Mat complex_result;
-#ifdef OPENCV_CUFFT
-    cv::Mat flip_h,imag_h;
-
-    cv::cuda::HostMem hostmem_input(input, cv::cuda::HostMem::SHARED);
-    cv::cuda::HostMem hostmem_real(cv::Size(input.cols,input.rows/2+1), CV_32FC2, cv::cuda::HostMem::SHARED);
-
-    cv::cuda::dft(hostmem_input,hostmem_real,hostmem_input.size(),0,stream);
-    stream.waitForCompletion();
-
-    cv::Mat real_h = hostmem_real.createMatHeader();
-
-    //create reversed copy of result and merge them
-    cv::flip(hostmem_real,flip_h,1);
-    flip_h(cv::Range(0, flip_h.rows), cv::Range(1, flip_h.cols)).copyTo(imag_h);
-
-    std::vector<cv::Mat> matarray = {real_h,imag_h};
-
-    cv::hconcat(matarray,complex_result);
-#endif
-#ifdef FFTW
-    // Prepare variables and FFTW plan for float precision FFT
-//     float *data_in;
-    fftwf_complex    *fft;
-
-    fftwf_plan       plan_f;
-
-    int  width, height;
-
-    width         = input.cols;
-    height        = input.rows;
-
-    float* outdata = new float[2*width * height];
-
-//     data_in =  fftwf_alloc_real(width * height);
-    #pragma omp critical
-    {
-    fft = fftwf_alloc_complex((width/2+1) * height);
-    plan_f=fftwf_plan_dft_r2c_2d( height , width , (float*)input.data , fft ,  FFTW_ESTIMATE );
-    }
-    // Prepare input data
-//     for(int i = 0,k=0; i < height; ++i) {
-//         const float* row = input.ptr<float>(i);
-//         for(int j = 0; j < width; j++) {
-//             data_in[k]=(float)row[j];
-//             k++;
-//         }
-//     }
-
-    // Exectue fft
-    fftwf_execute( plan_f );
-
-    // Get output data to right format
-    int width2=2*width;
-    for(int  i = 0, k = 0,l=0 ; i < height; i++ ) {
-        for(int  j = 0 ; j < width2 ; j++ ) {
-            if(j<=width2/2-1){
-                outdata[i * width2 + j] = (float)fft[k][0];
-                outdata[i * width2 + j+1] = (float)fft[k][1];
-
-                j++;
-                k++;
-                l++;
-            }else{
-                l--;
-                outdata[i * width2 + j] = (float)fft[l][0];
-                outdata[i * width2 + j+1] = (float)fft[l][1];
-
-                j++;
-            }
-        }
-    }
-    cv::Mat tmp(height,width,CV_32FC2,outdata);
-    complex_result=tmp;
-    // Destroy FFTW plan and variables
-#pragma omp critical
-    {
-    fftwf_destroy_plan(plan_f);
-    fftwf_free(fft); /*fftwf_free(data_in);*/
-    }
-#endif
-#if !defined OPENCV_CUFFT || !defined FFTW
-    cv::dft(input, complex_result, cv::DFT_COMPLEX_OUTPUT);
-#endif
-#ifdef DEBUG_MODE
-    //extraxt x and y channels
-    cv::Mat xy[2]; //X,Y
-    cv::split(complex_result, xy);
-
-    //calculate angle and magnitude
-    cv::Mat magnitude, angle;
-    cv::cartToPolar(xy[0], xy[1], magnitude, angle, true);
-
-    //translate magnitude to range [0;1]
-    double mag_max;
-    cv::minMaxLoc(magnitude, 0, &mag_max);
-    magnitude.convertTo(magnitude, -1, 1.0 / mag_max);
-
-    //build hsv image
-    cv::Mat _hsv[3], hsv;
-    _hsv[0] = angle;
-    _hsv[1] = cv::Mat::ones(angle.size(), CV_32F);
-    _hsv[2] = magnitude;
-    cv::merge(_hsv, 3, hsv);
-
-    //convert to BGR and show
-    cv::Mat bgr;//CV_32FC3 matrix
-    cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
-    cv::resize(bgr, bgr, cv::Size(600,600));
-    cv::imshow("DFT", bgr);
-    cv::waitKey(0);
-#endif //DEBUG_MODE
-    return ComplexMat(complex_result);
-}
-
-ComplexMat KCF_Tracker::fft2(const std::vector<cv::Mat> &input, const cv::Mat &cos_window)
-{
-    int n_channels = input.size();
-    cv::Mat complex_result;
-
-#ifdef OPENCV_CUFFT
-    cv::Mat flip_h,imag_h;
-    cv::cuda::GpuMat src_gpu;
-    cv::cuda::HostMem hostmem_real(cv::Size(input[0].cols,input[0].rows/2+1), CV_32FC2, cv::cuda::HostMem::SHARED);
-#endif
-#ifdef FFTW
-    // Prepare variables and FFTW plan for float precision FFT
-//     float *data_in;
-    fftwf_complex    *fft;
-
-    fftwf_plan       plan_f;
-
-    int  width, height, width2;
-
-    width         = input[0].cols;
-    height        = input[0].rows;
-    width2=2*width;
-
-    float* outdata = new float[2*width * height];
-    cv::Mat in_img  = cv::Mat::zeros(height, width, CV_32FC1);
-//     data_in =  fftwf_alloc_real(width * height);
-    #pragma omp critical 
-    {
-    fft = fftwf_alloc_complex((width/2+1) * height);
-    plan_f=fftwf_plan_dft_r2c_2d( height , width , (float*) in_img.data , fft ,  FFTW_ESTIMATE );
-    }
-#endif
-
-    ComplexMat result(input[0].rows, input[0].cols, n_channels);
-    for (int i = 0; i < n_channels; ++i){
-#ifdef OPENCV_CUFFT
-        cv::cuda::HostMem hostmem_input(input[i], cv::cuda::HostMem::SHARED);
-        cv::cuda::multiply(hostmem_input,p_cos_window_d,src_gpu);
-        cv::cuda::dft(src_gpu,hostmem_real,src_gpu.size(),0,stream);
-        stream.waitForCompletion();
-
-        cv::Mat real_h = hostmem_real.createMatHeader();
-
-        //create reversed copy of result and merge them
-        cv::flip(hostmem_real,flip_h,1);
-        flip_h(cv::Range(0, flip_h.rows), cv::Range(1, flip_h.cols)).copyTo(imag_h);
-
-        std::vector<cv::Mat> matarray = {real_h,imag_h};
-
-        cv::hconcat(matarray,complex_result);
-#endif
-#ifdef FFTW
-        // Prepare input data
-        cv::Mat in_img = input[i].mul(cos_window);
-//         for(int x = 0,k=0; x< height; ++x) {
-//             const float* row = in_img.ptr<float>(x);
-//             for(int j = 0; j < width; j++) {
-//                 data_in[k]=(float)row[j];
-//                 k++;
-//             }
-//         }
-
-        // Execute FFT
-        fftwf_execute( plan_f );
-
-        // Get output data to right format
-        for(int  x = 0, k = 0,l=0 ; x < height; ++x ) {
-            for(int  j = 0 ; j < width2 ; j++ ) {
-                if(j<=width2/2-1){
-                    outdata[x* width2 + j] = (float)fft[k][0];
-                    outdata[x * width2 + j+1] = (float)fft[k][1];
-                    j++;
-                    k++;
-                    l++;
-                }else{
-                    l--;
-                    outdata[x * width2 + j] = (float)fft[l][0];
-                    outdata[x * width2 + j+1] = (float)fft[l][1];
-                    j++;
-                }
-            }
-        }
-        cv::Mat tmp(height,width,CV_32FC2,outdata);
-        complex_result = tmp;
-
-#endif
-#if !defined OPENCV_CUFFT || !defined FFTW
-        cv::dft(input[i].mul(cos_window), complex_result, cv::DFT_COMPLEX_OUTPUT);
-#endif
-
-        result.set_channel(i, complex_result);
-    }
-#ifdef FFTW
-    // Destroy FFT plans and variables
-    #pragma omp critical
-{
-    fftwf_destroy_plan(plan_f);
-    fftwf_free(fft); /*fftwf_free(data_in);*/
-}
-#endif //FFTW
-    return result;
-}
-
-cv::Mat KCF_Tracker::ifft2(const ComplexMat &inputf)
-{
-#ifdef FFTW
-    // Prepare variables and FFTW plan for float precision IFFT
-    fftwf_complex *data_in;
-    float    *ifft;
-    fftwf_plan       plan_if;
-    int  width, height;
-#endif //FFTW
-    cv::Mat real_result;
-
-    if (inputf.n_channels == 1){
-#ifdef FFTW
-        cv::Mat input=inputf.to_cv_mat()  ;
-
-        width     = input.cols;
-        height    = input.rows;
-
-        float* outdata = new float[width * height];
-#pragma omp critical
-        {
-        data_in =  fftwf_alloc_complex(2*(width/2+1) * height);
-        ifft = fftwf_alloc_real(width * height);
-
-        plan_if=fftwf_plan_dft_c2r_2d( height , width , data_in , ifft ,  FFTW_MEASURE );
-        }
-        //Prepare input data
-        for(int x = 0,k=0; x< height; ++x) {
-            const float* row = input.ptr<float>(x);
-            for(int j = 0; j < width; j++) {
-                data_in[k][0]=(float)row[j];
-                data_in[k][1]=(float)row[j+1];
-
-                k++;
-                j++;
-            }
-        }
-
-        // Execute IFFT
-        fftwf_execute( plan_if );
-
-        // Get output data to right format
-        for(int x = 0,k=0; x< height; ++x) {
-            for(int j = 0; j < width; j++) {
-                outdata[k]=(float)ifft[x*width+j]/(float)(width*height);
-
-                k++;
-            }
-        }
-
-        cv::Mat  tmp(height,width,CV_32FC1,outdata);
-        real_result = tmp;
-        // Destroy FFTW plans and variables
-#pragma omp critical
-        {
-        fftwf_destroy_plan(plan_if);
-        fftwf_free(ifft); fftwf_free(data_in);
-        }
-#else
-        cv::dft(inputf.to_cv_mat(),real_result, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE);
-#endif //FFTW
-
-    } else {
-        std::vector<cv::Mat> mat_channels = inputf.to_cv_mat_vector();
-        std::vector<cv::Mat> ifft_mats(inputf.n_channels);
-#ifdef FFTW
-        width    = mat_channels[0].cols;
-        height    = mat_channels[0].rows;
-
-        float* outdata = new float[width * height];
-#pragma omp critical
-        {
-        data_in =  fftwf_alloc_complex(2*(width/2+1) * height);
-        ifft = fftwf_alloc_real(width * height);
-            
-        plan_if=fftwf_plan_dft_c2r_2d( height , width , data_in , ifft ,  FFTW_MEASURE );
-        }
-#endif //FFTW
-        for (int i = 0; i < inputf.n_channels; ++i) {
-#ifdef FFTW
-            //Prepare input data
-            for(int x = 0,k=0; x< height; ++x) {
-                const float* row = mat_channels[i].ptr<float>(x);
-                for(int j = 0; j < width; j++) {
-                    data_in[k][0]=(float)row[j];
-                    data_in[k][1]=(float)row[j+1];
-
-                    k++;
-                    j++;
-                }
-            }
-
-            // Execute IFFT
-            fftwf_execute( plan_if );
-
-            // Get output data to right format
-            for(int x = 0,k=0; x< height; ++x) {
-                for(int j = 0; j < width; j++) {
-                    outdata[k]=(float)ifft[x*width+j]/(float)(width*height);
-
-                    k++;
-                }
-            }
-
-            cv::Mat  tmp(height,width,CV_32FC1,outdata);
-
-            ifft_mats[i]=tmp;
-
-#else
-            cv::dft(mat_channels[i], ifft_mats[i], cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE);
-#endif //FFTW
-        }
-#ifdef FFTW
-        // Destroy FFTW plans and variables
-#pragma omp critical
-{
-        fftwf_destroy_plan(plan_if);
-        fftwf_free(ifft); fftwf_free(data_in);
-}
-#endif //FFTW
-        cv::merge(ifft_mats, real_result);
-    }
-    return real_result;
-}
-
 //hann window actually (Power-of-cosine windows)
 cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
 {
@@ -807,17 +672,13 @@ cv::Mat KCF_Tracker::cosine_window_function(int dim1, int dim2)
     for (int i = 0; i < dim2; ++i)
         m2.at<float>(i) = 0.5*(1. - std::cos(2. * CV_PI * static_cast<double>(i) * N_inv));
     cv::Mat ret = m2*m1;
-#ifdef OPENCV_CUFFT
-    cv::cuda::createContinuous(cv::Size(ret.cols,ret.rows),CV_32FC1,p_cos_window_d);
-    p_cos_window_d.upload(ret);
-#endif
     return ret;
 }
 
 // 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)
 {
     cv::Mat patch;
 
@@ -871,30 +732,63 @@ cv::Mat KCF_Tracker::get_subwindow(const cv::Mat &input, int cx, int cy, int wid
     return patch;
 }
 
-ComplexMat KCF_Tracker::gaussian_correlation(const ComplexMat &xf, const ComplexMat &yf, double sigma, bool auto_correlation)
+void KCF_Tracker::gaussian_correlation(struct Scale_vars & vars, const ComplexMat & xf, const ComplexMat & yf, double sigma, bool auto_correlation)
 {
-    float xf_sqr_norm = xf.sqr_norm();
-    float yf_sqr_norm = auto_correlation ? xf_sqr_norm : yf.sqr_norm();
-
-    ComplexMat xyf = auto_correlation ? xf.sqr_mag() : xf * yf.conj();
-
+#ifdef CUFFT
+    xf.sqr_norm(vars.xf_sqr_norm_d);
+    if (!auto_correlation)
+        yf.sqr_norm(vars.yf_sqr_norm_d);
+#else
+    xf.sqr_norm(vars.xf_sqr_norm);
+    if (auto_correlation){
+      vars.yf_sqr_norm[0] = vars.xf_sqr_norm[0];
+    } else {
+       yf.sqr_norm(vars.yf_sqr_norm);
+    }
+#endif
+    vars.xyf = auto_correlation ? xf.sqr_mag() : xf.mul2(yf.conj());
+    DEBUG_PRINTM(vars.xyf);
+#ifdef CUFFT
+    fft.inverse(vars);
+    if(auto_correlation)
+        cuda_gaussian_correlation(vars.data_i_features, vars.gauss_corr_res, vars.xf_sqr_norm_d, vars.xf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
+    else
+        cuda_gaussian_correlation(vars.data_i_features, vars.gauss_corr_res, vars.xf_sqr_norm_d, vars.yf_sqr_norm_d, sigma, xf.n_channels, xf.n_scales, p_roi_height, p_roi_width);
+#else
     //ifft2 and sum over 3rd dimension, we dont care about individual channels
-    cv::Mat xy_sum(xf.rows, xf.cols, CV_32FC1);
+    fft.inverse(vars);
+    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);
-    cv::Mat ifft2_res = ifft2(xyf);
-    for (int y = 0; y < xf.rows; ++y) {
-        float * row_ptr = ifft2_res.ptr<float>(y);
+    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 < xf.cols; ++x){
-            row_ptr_sum[x] = std::accumulate((row_ptr + x*ifft2_res.channels()), (row_ptr + x*ifft2_res.channels() + ifft2_res.channels()), 0.f);
+        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);
 
-    float numel_xf_inv = 1.f/(xf.cols * xf.rows * xf.n_channels);
-    cv::Mat tmp;
-    cv::exp(- 1.f / (sigma * sigma) * cv::max((xf_sqr_norm + yf_sqr_norm - 2 * xy_sum) * numel_xf_inv, 0), tmp);
+    std::vector<cv::Mat> scales;
+    cv::split(xy_sum,scales);
 
-    return fft2(tmp);
+    float numel_xf_inv = 1.f/(xf.cols * xf.rows * (xf.channels()/xf.n_scales));
+    for (int 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.f / (sigma * sigma) * cv::max((vars.xf_sqr_norm[i] + vars.yf_sqr_norm[0] - 2 * scales[i]) * numel_xf_inv, 0), in_roi);
+        DEBUG_PRINTM(in_roi);
+    }
+#endif
+    DEBUG_PRINTM(vars.in_all);
+    fft.forward(vars);
+    return;
 }
 
 float get_response_circular(cv::Point2i & pt, cv::Mat & response)
@@ -923,6 +817,7 @@ cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
     cv::Point2i p4(max_loc.x-1, max_loc.y), p5(max_loc.x+1, max_loc.y);
     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);
 
+    // clang-format off
     // fit 2d quadratic function f(x, y) = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f
     cv::Mat A = (cv::Mat_<float>(9, 6) <<
                  p1.x*p1.x, p1.x*p1.y, p1.y*p1.y, p1.x, p1.y, 1.f,
@@ -944,6 +839,7 @@ cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
                     get_response_circular(p7, response),
                     get_response_circular(p8, response),
                     get_response_circular(max_loc, response));
+    // clang-format on
     cv::Mat x;
     cv::solve(A, fval, x, cv::DECOMP_SVD);
 
@@ -959,7 +855,7 @@ cv::Point2f KCF_Tracker::sub_pixel_peak(cv::Point & max_loc, cv::Mat & response)
     return sub_peak;
 }
 
-double KCF_Tracker::sub_grid_scale(std::vector<double> & responses, int index)
+double KCF_Tracker::sub_grid_scale(int index)
 {
     cv::Mat A, fval;
     if (index < 0 || index > (int)p_scales.size()-1) {
@@ -971,7 +867,7 @@ double KCF_Tracker::sub_grid_scale(std::vector<double> & responses, int index)
             A.at<float>(i, 0) = p_scales[i] * p_scales[i];
             A.at<float>(i, 1) = p_scales[i];
             A.at<float>(i, 2) = 1;
-            fval.at<float>(i) = responses[i];
+            fval.at<float>(i) = scale_vars[i].max_response;
         }
     } else {
         //only from neighbours
@@ -982,7 +878,7 @@ double KCF_Tracker::sub_grid_scale(std::vector<double> & responses, int index)
              p_scales[index-1] * p_scales[index-1], p_scales[index-1], 1,
              p_scales[index] * p_scales[index], p_scales[index], 1,
              p_scales[index+1] * p_scales[index+1], p_scales[index+1], 1);
-        fval = (cv::Mat_<float>(3, 1) << responses[index-1], responses[index], responses[index+1]);
+        fval = (cv::Mat_<float>(3, 1) << scale_vars[index-1].max_response, scale_vars[index].max_response, scale_vars[index+1].max_response);
     }
 
     cv::Mat x;