138657e9b8630c65110eb8e2b0e2f634dab1d452
[trackerpp.git] / src / MultiTracker.cpp
1 #include "MultiTracker.h"
2 #include "Metrics.h"
3 #include <algorithm>
4 #include "hungarian.h"
5 #include "Logger.h"
6 #include "Utils.h"
7
8 using namespace suanzi;
9 using namespace cv;
10 using namespace std;
11
12 static const std::string TAG = "MultiTracker";
13 static const cv::Size PREFERRED_SIZE = Size(64, 128);
14 static const double MaxCost  = 100000;
15 static const double ProbThreshold = 0.05;
16
17 MultiTracker::MultiTracker(EngineWPtr e)
18 : engine(e)
19 {
20     LOG_DEBUG(TAG, "init - loading model.pkl");
21     predictor = PredictorWrapper::create("./python", "./python/model.pkl");
22     predictor->dump();
23     this->descriptor = {Size(64, 128), Size(16, 16), Size(8, 8), Size(8, 8), 9};
24 }
25
26 MultiTracker::~MultiTracker()
27 {
28     predictor.reset();
29     trackers.clear();
30 }
31
32 static std::vector<double> similarity(const PatchPtr p1, const PatchPtr p2)
33 {
34     std::vector<double> feature;
35     cv::Mat im1(PREFERRED_SIZE, p1->image_crop.type());
36     cv::Mat im2(PREFERRED_SIZE, p2->image_crop.type());
37     cv::resize(p1->image_crop, im1, im1.size());
38     cv::resize(p2->image_crop, im2, im2.size());
39     cv::Mat result;
40     cv::matchTemplate(im1, im2, result, CV_TM_CCOEFF_NORMED);
41     feature.push_back(result.at<double>(0, 0));
42     cv::matchTemplate(im1, im2, result, CV_TM_CCORR_NORMED);
43     feature.push_back(result.at<double>(0, 0));
44
45
46     vector<double>& f1_hog = p1->features.first; Mat f1_hue = p1->features.second;
47     vector<double>& f2_hog = p1->features.first; Mat f2_hue = p1->features.second;
48     feature.push_back(distance_cosine(Eigen::Map<Eigen::VectorXd>(f1_hog.data(), f1_hog.size()), 
49                                     Eigen::Map<Eigen::VectorXd>(f2_hog.data(), f2_hog.size())));
50     feature.push_back(distance_euclidean(Eigen::Map<Eigen::VectorXd>(f1_hog.data(), f1_hog.size()), 
51                                     Eigen::Map<Eigen::VectorXd>(f2_hog.data(), f2_hog.size())));
52     feature.push_back(compareHist(f1_hue, f2_hue, HISTCMP_CORREL));
53     feature.push_back(compareHist(f1_hue, f2_hue, HISTCMP_HELLINGER));
54
55     Detection& d1 = p1->detection;
56     Detection& d2 = p2->detection;
57
58     double center_distance = sqrt(pow((d1.center_x - d2.center_x), 2) + pow((d1.center_y - d2.center_y), 2));
59     feature.push_back(center_distance / (d1.width + d1.height + d2.width + d2.height) * 4);
60
61     feature.push_back(calc_iou_ratio(getRectInDetection(d1), getRectInDetection(d2)));
62
63     return feature;
64 }
65
66 double MultiTracker::distance(TrackerPtr tracker, const cv::Mat& image, const Detection& d)
67 {
68     PatchPtr patch = createPatch(image, d);
69     std::vector<double> features;
70
71     std::vector<double> ss;
72     for (auto i : tracker->patches){
73         ss = similarity(i, patch);
74         features.insert(features.end(),  ss.begin(), ss.end());
75     }
76     double prob = predictor->predict(Tracker::MaxPatch - 1, features); // TODO why is MaxPatch-1
77     if (prob > ProbThreshold)
78         return -log(prob);
79     else 
80         return MaxCost;
81 }
82
83 static float calc_iou_ratio(const Detection& d1, const Detection& d2)
84 {
85     return calc_iou_ratio(getRectInDetection(d1), getRectInDetection(d2));
86 }
87
88 void MultiTracker::update(unsigned int total, const Detection* detections, const Mat& image)
89 {
90     // predict trackers, update trackers using kalman filter
91     for (auto t : trackers){
92         t->predict();
93     }
94
95     // match the trackers with the detections using linear sum assignment (hungarian)
96     int row = trackers.size();
97     int col = total;
98     Eigen::MatrixXi cost_matrix = Eigen::MatrixXi::Zero(row, col);
99     for (int i = 0; i < row; i++){
100         for (int j = 0; j < col; j++){
101             if (calc_iou_ratio(trackers[i]->detection, detections[j]) < -0.1)
102                 cost_matrix(i, j) = MaxCost;
103             else
104                 cost_matrix(i, j) = distance(trackers[i], image, detections[j]);
105         }
106     }
107
108     Eigen::VectorXi tracker_inds, bb_inds;
109     linear_sum_assignment(cost_matrix, tracker_inds, bb_inds);
110
111     set<TrackerPtr> unmatched_trackers;
112     set<int> unmatch_bbs_indices;
113
114     for(unsigned int i = 0; i < trackers.size(); i++){
115         if (!(tracker_inds.array() == i).any()){
116             unmatched_trackers.insert(trackers[i]);
117         }
118     }
119     for (unsigned int j = 0; j < total; j++){
120         if (!(bb_inds.array() == j).any()){
121             unmatch_bbs_indices.insert(j);
122         }
123     }
124
125     // handle matched trackers
126     for (unsigned int i = 0; i < tracker_inds.size(); i++){
127         for (int j = 0; j < bb_inds.size(); j++){
128             int rr = tracker_inds(i);
129             int cc = bb_inds(j);
130             TrackerPtr tracker = trackers[rr];
131             const Detection& detect = detections[cc];
132             if (cost_matrix(rr, cc) < MaxCost){
133                 tracker->correct(image, detect);
134                 tracker->addPatch(createPatch(image, detect));
135             } else {
136                 unmatched_trackers.insert(tracker);  // failed trackers
137                 unmatch_bbs_indices.insert(cc);     // filed detection
138             }
139         }
140     }
141
142     // handle unmatched trackers
143     for (auto t : unmatched_trackers){
144         t->updateState(image);
145     }
146
147     // handle unmatched detections - Create new trackers
148     vector<Person> inPersons;
149     for (auto i : unmatch_bbs_indices){
150         TrackerPtr new_tracker (new Tracker(image, detections[i]));
151         new_tracker->addPatch(createPatch(image, detections[i]));
152         this->trackers.push_back(new_tracker);
153         Person test; // TODO
154         inPersons.push_back(test);
155     }
156     
157     // callback and notify engine - persons in
158     if (inPersons.size() > 0){
159         if (auto e = engine.lock()){
160             e->onPersonsIn(inPersons);
161         }
162     }
163
164     // Delete lost trackers
165     vector<Person> outPersons;
166     for (auto it = trackers.begin(); it < trackers.end(); it++){
167         if ((*it)->status == TrackerStatus::Delete){
168             Person test; // TODO
169             outPersons.push_back(test);
170             trackers.erase(it);
171         }
172     }
173
174     // callback and notify engine - persons out
175     if (outPersons.size() > 0){
176         if (auto e = engine.lock()){
177             e->onPersonsOut(outPersons);
178         }
179     }
180 }
181
182 static cv::Mat image_crop(const cv::Mat& image, const Detection& bb)
183 {
184     return image(getRectInDetection(bb));
185 }
186
187 PatchPtr MultiTracker::createPatch(const Mat& image, const Detection& detect)
188 {
189     PatchPtr patch(new Patch());
190
191     // calculate hog descriptors, size is 3780
192     Mat im, im2;
193     im = image_crop(image, detect);
194     resize(im, im2, PREFERRED_SIZE);
195     vector<float> feature_hog;
196     this->descriptor.compute(im2, feature_hog);
197
198     // calculate histogram, size is (64 x 45)
199     Mat hsv, hist;
200     cvtColor(im, hsv, COLOR_BGR2HSV);
201     int channels[] = {0, 1};
202     int histSize[] = {45, 64};
203     float hranges[] = {0, 180};
204     float sranges[] = {0, 256};
205     const float* ranges[] = {hranges, sranges};
206     calcHist(&hsv, 1, channels, Mat(), hist, 2, histSize, ranges, true, false);
207
208     patch->image_crop = im.clone();
209     patch->detection = detect;
210     std::vector<double> feature_hog_double (feature_hog.begin(), feature_hog.end()); // convert to double
211     patch->features = std::make_pair(feature_hog_double, hist);
212     return patch;
213 }