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