This repository contains a lightweight vehicle detection and counting project built using classical computer-vision techniques. The goal is to detect moving vehicles in video, track them by centroid, and classify their exit routes so counts can be aggregated by direction.
Count and classify moving vehicles in a scene by tracking object centroids and mapping trajectories to exit zones.
- Motion Segmentation: Uses a background subtractor to extract moving foreground regions.
- Blob Extraction: Filters contours by size and shape to produce candidate vehicle bounding boxes and centroids.
- Centroid Tracking: Associates detections across frames with a simple centroid-based tracker that maintains object IDs and trajectories.
- Route Classification: Maps object trajectories to predefined exit zones and aggregates counts per route.
vehicle_counter1.py: Main implementation showing the pipeline (motion segmentation, blob extraction, centroid tracker, route classifier) and a runnablerun(video_path)entrypoint.vh_count1.py,counter1.py: Additional variants or experiments for vehicle counting (see each file for differences in heuristics and parameters).requirements.txt: Python dependencies used by the project.
- Background subtraction produces a binary foreground mask.
- Contours are found in the foreground mask and filtered by area and aspect ratio to identify likely vehicles.
- Centroids of filtered blobs are tracked using pairwise distance matching; tracks are created, maintained, and removed when objects disappear.
- Trajectories are inspected to find which exit zone the object ended in; that zone is used to increment the route's count.
- Create and activate a Python virtual environment, then install dependencies:
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt- Run the reference script (edit
video.mp4path or pass your own video):
python vehicle_counter1.py- Blob size: Tweak
min_areaandmax_areain the blob extractor to match the scale of vehicles in your video. - Background model: Adjust
historyandvarThresholdin the background subtractor for different scene dynamics. - Exit zones: Edit the
exit_zonesrectangles invehicle_counter1.pyto match regions where vehicles leave the frame. - Max disappearance: Change
max_disappearedin the centroid tracker to tolerate longer occlusions.
- The reference script prints final route counts to stdout. The repository contains
vehicle_count_report.txtwith a sample result for reference.
- This project uses classic CV techniques (contours, background subtraction, centroid matching). For higher accuracy on crowded scenes consider adding Kalman filters, appearance models, or switching to deep-learning detectors + trackers.
- The code is intentionally modular:
MotionSegmenter,VehicleBlobExtractor,CentroidTracker, andRouteClassifierare easy to experiment with or replace.