#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
int main() {
VideoCapture cap("video.mp4");
Ptr<BackgroundSubtractor> bg_sub = createBackgroundSubtractorMOG2();
std::vector<Rect> vehicles;
while (true) {
Mat frame;
cap >> frame;
Mat fg_mask;
bg_sub->apply(frame, fg_mask);
std::vector<vector<Point>> contours;
findContours(fg_mask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (auto& contour : contours) {
Rect bbox = boundingRect(contour);
vehicles.push_back(bbox);
}
for (int i = 0; i < vehicles.size(); i++) {
Rect prev_bbox = vehicles[i - 1];
float speed = (norm(prev_bbox.center() - vehicles[i].center()) / time_diff) * pixel_meter_ratio;
putText(frame, std::to_string(speed), vehicles[i].tl(), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 2);
}
imshow("Video", frame);
if (waitKey(30) == 'q') {
break;
}
}
return 0;
}