const cv::Size MAX_DETECT_SIZE = cv::Size(100, 200);
const int MAX_MISS_FRAME = 10;
const double MIN_NEW_DETECT_INTERSECTION_RATE = 0.5;
class MyTracker
{
private:
static int next_id;
int id;
int n_miss_frame = 0;
cv::Rect2d rect;
cv::Ptrcv_tracker;
public:
MyTracker(const cv::Mat& _frame, const cv::Rect2d& _rect)
: id(next_id++), rect(_rect)
{
cv_tracker = cv::Tracker::create("BOOSTING"); // or "MIL"
cv_tracker->init(_frame, _rect);
}
bool update(const cv::Mat& _frame)
{
n_miss_frame++;
return cv_tracker->update(_frame, rect) && n_miss_frame MIN_NEW_DETECT_INTERSECTION_RATE;
if (is_registered) n_miss_frame = 0;
return is_registered;
}
void draw(cv::Mat& _image) const
{
cv::rectangle(_image, rect, cv::Scalar(255, 0, 0), 2, 1);
cv::putText(_image, cv::format("%03d", id), cv::Point(rect.x + 5, rect.y + 17),
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,0,0), 1, CV_AA);
}
};
int MyTracker::next_id = 0;
int main(int argc, char* argv[])
{
if(argc != 2)
{
std::cout
for(auto it = fs::directory_iterator(argv[1]); it != fs::directory_iterator(); ++it)
{
frame_paths.push_back(it->path().string());
}
cv::HOGDescriptor detector;
detector.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector());
std::vectortrackers;
for (auto& frame_path : frame_paths)
{
std::cout
detector.detectMultiScale(frame, detections);
for (auto t_it = trackers.begin(); t_it != trackers.end();)
{
t_it = (t_it->update(frame)) ? std::next(t_it) : trackers.erase(t_it);
}
for(auto& d_rect : detections)
{
if (d_rect.size().area() > MAX_DETECT_SIZE.area()) continue;
bool is_exsisting = std::any_of(trackers.begin(), trackers.end(),
[&d_rect](MyTracker& t)
{
return t.registerNewDetect(d_rect);
});
if(!is_exsisting) trackers.push_back(MyTracker(frame, d_rect));
}
cv::Mat image = frame.clone();
for(auto& t : trackers) t.draw(image);
for(auto& d_rect : detections) cv::rectangle(image, d_rect, cv::Scalar(0, 255, 0), 2, 1);
cv::imshow("demo", image);
cv::waitKey(1);
}
return 0;
}