Fix nan issue in features
[trackerpp.git] / src / MultiTracker.cpp
index b1f380e..199d9f7 100644 (file)
@@ -1,8 +1,10 @@
 #include "MultiTracker.h"
-#include "Metrics.h"
 #include <algorithm>
 #include "hungarian.h"
 #include "Logger.h"
+#include "Utils.h"
+#include <cstdlib>
+#include <stdexcept>
 
 using namespace suanzi;
 using namespace cv;
@@ -10,18 +12,18 @@ using namespace std;
 
 static const std::string TAG = "MultiTracker";
 static const cv::Size PREFERRED_SIZE = Size(64, 128);
+static const double MaxCost  = 100000;
+static const double ProbThreshold = 0.05;
+static const int MaxTrackers  = 100;
 
-#define MaxCost  100000
-
-MultiTracker::MultiTracker()
+MultiTracker::MultiTracker(EngineWPtr e)
+: engine(e)
 {
     LOG_DEBUG(TAG, "init - loading model.pkl");
-    predictor = PredictorWrapper::create("./python/model.pkl");
+    predictor = PredictorWrapperPtr(new PredictorWrapper());
+    predictor->load("./resources/model.pkl");
     predictor->dump();
     this->descriptor = {Size(64, 128), Size(16, 16), Size(8, 8), Size(8, 8), 9};
-
-    std::vector<double> ff (40, 1);
-    double prob = predictor->predict(4, ff);
 }
 
 MultiTracker::~MultiTracker()
@@ -30,7 +32,6 @@ MultiTracker::~MultiTracker()
     trackers.clear();
 }
 
-
 static std::vector<double> similarity(const PatchPtr p1, const PatchPtr p2)
 {
     std::vector<double> feature;
@@ -38,7 +39,9 @@ static std::vector<double> similarity(const PatchPtr p1, const PatchPtr p2)
     cv::Mat im2(PREFERRED_SIZE, p2->image_crop.type());
     cv::resize(p1->image_crop, im1, im1.size());
     cv::resize(p2->image_crop, im2, im2.size());
-    cv::Mat result;
+
+    cv::Mat result = Mat::zeros(1,1, CV_64F);
+
     cv::matchTemplate(im1, im2, result, CV_TM_CCOEFF_NORMED);
     feature.push_back(result.at<double>(0, 0));
     cv::matchTemplate(im1, im2, result, CV_TM_CCORR_NORMED);
@@ -60,14 +63,19 @@ static std::vector<double> similarity(const PatchPtr p1, const PatchPtr p2)
     double center_distance = sqrt(pow((d1.center_x - d2.center_x), 2) + pow((d1.center_y - d2.center_y), 2));
     feature.push_back(center_distance / (d1.width + d1.height + d2.width + d2.height) * 4);
 
-    //TODO
-    double iou_ratio = 0.03;
-    feature.push_back(iou_ratio);
+    feature.push_back(calc_iou_ratio(getRectInDetection(d1), getRectInDetection(d2)));
 
+//    for (auto i : feature){
+//        cout << i << "\t";
+//        if (isnan(i)){
+//            throw overflow_error("Nan in feature");
+//        }
+//    }
+//    cout << endl;
+//
     return feature;
 }
 
-
 double MultiTracker::distance(TrackerPtr tracker, const cv::Mat& image, const Detection& d)
 {
     PatchPtr patch = createPatch(image, d);
@@ -78,61 +86,115 @@ double MultiTracker::distance(TrackerPtr tracker, const cv::Mat& image, const De
         ss = similarity(i, patch);
         features.insert(features.end(),  ss.begin(), ss.end());
     }
-    double prob = predictor->predict(4, features);
-    return prob; 
+    double prob = predictor->predict(tracker->patches.size() - 1, features); // TODO why is MaxPatch-1
+    if (prob > ProbThreshold)
+        return -log(prob);
+    else 
+        return MaxCost;
+}
+
+static float calc_iou_ratio(const Detection& d1, const Detection& d2)
+{
+    return calc_iou_ratio(getRectInDetection(d1), getRectInDetection(d2));
 }
 
 void MultiTracker::update(unsigned int total, const Detection* detections, const Mat& image)
 {
+    // predict trackers, update trackers using kalman filter
+    for (auto t : trackers){
+        t->predict();
+    }
+
+    // match the trackers with the detections using linear sum assignment (hungarian)
     int row = trackers.size();
     int col = total;
     Eigen::MatrixXi cost_matrix = Eigen::MatrixXi::Zero(row, col);
     for (int i = 0; i < row; i++){
         for (int j = 0; j < col; j++){
-            // TODO
-            cost_matrix(i, j) = distance(trackers[i], image, detections[j]);
+            if (calc_iou_ratio(trackers[i]->detection, detections[j]) < -0.1)
+                cost_matrix(i, j) = MaxCost;
+            else
+                cost_matrix(i, j) = distance(trackers[i], image, detections[j]);
         }
     }
 
-    // assignment
     Eigen::VectorXi tracker_inds, bb_inds;
     linear_sum_assignment(cost_matrix, tracker_inds, bb_inds);
 
-    // handle unmatched trackers
-    vector<TrackerPtr> unmatched_trackers;
-    for (int i = 0; i < row; i++){
+    set<TrackerPtr> unmatched_trackers;
+    set<int> unmatch_bbs_indices;
+
+    for(unsigned int i = 0; i < trackers.size(); i++){
         if (!(tracker_inds.array() == i).any()){
-            unmatched_trackers.push_back(trackers[i]);
+            unmatched_trackers.insert(trackers[i]);
+        }
+    }
+    for (unsigned int j = 0; j < total; j++){
+        if (!(bb_inds.array() == j).any()){
+            unmatch_bbs_indices.insert(j);
         }
     }
+
+    // handle matched trackers
+    for (unsigned int i = 0; i < tracker_inds.size(); i++){
+        for (int j = 0; j < bb_inds.size(); j++){
+            int rr = tracker_inds(i);
+            int cc = bb_inds(j);
+            TrackerPtr tracker = trackers[rr];
+            const Detection& detect = detections[cc];
+            if (cost_matrix(rr, cc) < MaxCost){
+                tracker->correct(image, detect);
+                tracker->addPatch(createPatch(image, detect));
+            } else {
+                unmatched_trackers.insert(tracker);  // failed trackers
+                unmatch_bbs_indices.insert(cc);     // filed detection
+            }
+        }
+    }
+
+    // handle unmatched trackers
     for (auto t : unmatched_trackers){
         t->updateState(image);
     }
 
-    // handle unmatched detections
-    vector<int> unmatched_detection;
-    for(int j = 0; j < col; j++){
-        if (!(bb_inds.array() == j).any()){
-            unmatched_detection.push_back(j);
-        }
+    // handle unmatched detections - Create new trackers
+    vector<Person> inPersons;
+    for (auto i : unmatch_bbs_indices){
+        TrackerPtr new_tracker (new Tracker(image, detections[i]));
+        new_tracker->addPatch(createPatch(image, detections[i]));
+        addTracker(new_tracker);
+        Person test; // TODO
+        inPersons.push_back(test);
     }
-    // create new trackers for new detections
-    for (auto i : unmatched_detection){
-        TrackerPtr t (new Tracker(image));
-        this->trackers.push_back(t);
+    
+    // callback and notify engine - persons in
+    if (inPersons.size() > 0){
+        if (auto e = engine.lock()){
+            e->onPersonsIn(inPersons);
+        }
     }
 
-    Detection dd;
+    // Delete lost trackers
+    vector<Person> outPersons;
+    for (auto it = trackers.begin(); it < trackers.end(); it++){
+        if ((*it)->status == TrackerStatus::Delete){
+            Person test; // TODO
+            outPersons.push_back(test);
+            trackers.erase(it);
+        }
+    }
 
-    PatchPtr pp = createPatch(image, dd);
+    // callback and notify engine - persons out
+    if (outPersons.size() > 0){
+        if (auto e = engine.lock()){
+            e->onPersonsOut(outPersons);
+        }
+    }
 }
 
-// Get image crop from input image within given bounding box - Detecinon
 static cv::Mat image_crop(const cv::Mat& image, const Detection& bb)
 {
-    // RECT
-    // TODO;
-    return image.clone();
+    return image(getRectInDetection(bb));
 }
 
 PatchPtr MultiTracker::createPatch(const Mat& image, const Detection& detect)
@@ -155,7 +217,6 @@ PatchPtr MultiTracker::createPatch(const Mat& image, const Detection& detect)
     float sranges[] = {0, 256};
     const float* ranges[] = {hranges, sranges};
     calcHist(&hsv, 1, channels, Mat(), hist, 2, histSize, ranges, true, false);
-    Size sm = hist.size();
 
     patch->image_crop = im.clone();
     patch->detection = detect;
@@ -163,3 +224,12 @@ PatchPtr MultiTracker::createPatch(const Mat& image, const Detection& detect)
     patch->features = std::make_pair(feature_hog_double, hist);
     return patch;
 }
+
+void MultiTracker::addTracker(TrackerPtr t)
+{
+    trackers.insert(trackers.begin(), t);
+    if(trackers.size() > MaxTrackers){
+        LOG_ERROR(TAG, "trackers reaches the maximum " + to_string(MaxTrackers));
+        trackers.pop_back();
+    }
+}