real-time-object-detection 1.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- real_time_object_detection-1.1.0/PKG-INFO +218 -0
- real_time_object_detection-1.1.0/README.md +203 -0
- real_time_object_detection-1.1.0/main.py +178 -0
- real_time_object_detection-1.1.0/pyproject.toml +36 -0
- real_time_object_detection-1.1.0/real_time_object_detection.egg-info/PKG-INFO +218 -0
- real_time_object_detection-1.1.0/real_time_object_detection.egg-info/SOURCES.txt +30 -0
- real_time_object_detection-1.1.0/real_time_object_detection.egg-info/dependency_links.txt +1 -0
- real_time_object_detection-1.1.0/real_time_object_detection.egg-info/entry_points.txt +2 -0
- real_time_object_detection-1.1.0/real_time_object_detection.egg-info/requires.txt +9 -0
- real_time_object_detection-1.1.0/real_time_object_detection.egg-info/top_level.txt +7 -0
- real_time_object_detection-1.1.0/setup.cfg +4 -0
- real_time_object_detection-1.1.0/src/__init__.py +1 -0
- real_time_object_detection-1.1.0/src/camera.py +46 -0
- real_time_object_detection-1.1.0/src/config.py +25 -0
- real_time_object_detection-1.1.0/src/config_loader.py +21 -0
- real_time_object_detection-1.1.0/src/detector.py +43 -0
- real_time_object_detection-1.1.0/src/device_utils.py +36 -0
- real_time_object_detection-1.1.0/src/exporter.py +88 -0
- real_time_object_detection-1.1.0/src/logger.py +30 -0
- real_time_object_detection-1.1.0/src/model.py +26 -0
- real_time_object_detection-1.1.0/src/pipeline.py +190 -0
- real_time_object_detection-1.1.0/src/runtime_tracker.py +164 -0
- real_time_object_detection-1.1.0/src/tracker.py +174 -0
- real_time_object_detection-1.1.0/src/validation.py +110 -0
- real_time_object_detection-1.1.0/tests/__init__.py +1 -0
- real_time_object_detection-1.1.0/tests/conftest.py +6 -0
- real_time_object_detection-1.1.0/tests/test_config_loader.py +89 -0
- real_time_object_detection-1.1.0/tests/test_detector.py +83 -0
- real_time_object_detection-1.1.0/tests/test_exporter.py +79 -0
- real_time_object_detection-1.1.0/tests/test_logger.py +31 -0
- real_time_object_detection-1.1.0/tests/test_tracker.py +48 -0
- real_time_object_detection-1.1.0/tests/test_validation.py +87 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: real-time-object-detection
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: A real-time computer vision project that uses a webcam and the YOLOv8 model to detect and label objects as they appear on screen, drawing bounding boxes around them using OpenCV.
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: numpy>=2.4.1
|
|
8
|
+
Requires-Dist: opencv-python>=4.13.0.90
|
|
9
|
+
Requires-Dist: pytest>=9.0.2
|
|
10
|
+
Requires-Dist: pyyaml>=6.0.3
|
|
11
|
+
Requires-Dist: scipy>=1.17.0
|
|
12
|
+
Requires-Dist: ultralytics>=8.4.8
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
15
|
+
|
|
16
|
+
# Real-Time Object Detection - Computer Vision & YOLOv8 Inference Pipeline
|
|
17
|
+
|
|
18
|
+
An intelligent computer vision application built with **Python**, **OpenCV**, **Ultralytics YOLOv8**, **SciPy**, and **PyYAML**. It enables real-time object detection and multi-object centroid tracking across live webcam feeds and video files with full analytics reporting (CSV/JSON), optional annotated video recording, class filtering, and high-performance execution modes (`live`, `video`, `headless`, `benchmark`).
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Project Overview & Application Architecture
|
|
23
|
+
|
|
24
|
+
The **Real-Time Object Detection** system leverages an end-to-end vision pipeline to process video frames, identify multi-class targets using neural networks, track object movement across frames, and export structured operational analytics.
|
|
25
|
+
|
|
26
|
+
The core application architecture follows a modular vision & tracking pipeline:
|
|
27
|
+
|
|
28
|
+
1. **Configuration & Validation (`src/config_loader.py` & `src/validation.py`):** Loads and validates YAML settings (`config.yaml`) and CLI parameters, validating confidence thresholds, camera indices, frame rates, image sizes (`imgsz`), model paths, and device parameters (`cpu`, `cuda`, `mps`).
|
|
29
|
+
2. **Device Detection & Fallback (`src/device_utils.py`):** Checks GPU availability (CUDA / Apple Silicon MPS) and automatically selects the optimal hardware compute device with automatic CPU fallback.
|
|
30
|
+
3. **Model Loader & Downloader (`src/model.py`):** Initializes the Ultralytics YOLOv8 architecture (e.g. `yolov8n.pt`, `yolov8s.pt`), automatically fetching standard pretrained weights if missing locally.
|
|
31
|
+
4. **Video Stream Handling (`src/camera.py`):** Wraps OpenCV `VideoCapture` streams for low-latency frame reading from webcams or video files with graceful stream termination.
|
|
32
|
+
5. **Detector Engine & Class Filtering (`src/detector.py`):** Runs YOLOv8 inference per frame, converts bounding box structures, applies confidence thresholds, and filters detections against allowed COCO target classes.
|
|
33
|
+
6. **Centroid Multi-Object Tracker (`src/tracker.py`):** Class-aware and box-aware `CentroidTracker` using SciPy Euclidean distance matrices to track object movement, assign unique IDs, record lifetime durations, and detect frame entry/exit events.
|
|
34
|
+
7. **Runtime Analytics & Serialized Exporter (`src/runtime_tracker.py` & `src/exporter.py`):** Aggregates frame rates, object counts, per-class lifetime statistics, and exports structured reports (`summary.json`, `summary.csv`, `run_index.json`).
|
|
35
|
+
8. **Pipeline Engine & GUI Overlay (`src/pipeline.py` & `main.py`):** Drives the processing loop, renders bounding boxes and performance overlays, records output video (`VideoWriter`), and provides the `main.py` entry point with custom formatted help menus.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Core Modules & Features
|
|
40
|
+
|
|
41
|
+
* **Real-Time Object Detection:** Powered by Ultralytics YOLOv8 for precise multi-class object detection across live video feeds.
|
|
42
|
+
* **Class-Aware Centroid Tracking:** Stable multi-object tracking with persistent object IDs, entrance/exit event triggers, and lifetime duration monitoring.
|
|
43
|
+
* **Dual Input Sources:** Supports live webcam hardware feeds as well as video file inputs (`--video path/to/video.mp4`).
|
|
44
|
+
* **Flexible Execution Modes:** Four distinct runtime operating modes:
|
|
45
|
+
* `live`: Interactive GUI window displaying real-time webcam feed with object bounding boxes.
|
|
46
|
+
* `video`: Processes input video files with on-screen bounding boxes and FPS overlays.
|
|
47
|
+
* `headless`: Background processing without rendering GUI display windows (ideal for headless servers).
|
|
48
|
+
* `benchmark`: Automated performance benchmark mode calculating total frames, elapsed time, and average FPS.
|
|
49
|
+
* **Annotated Video Saving (`--save-video`):** Optionally records fully annotated detection feeds to MP4 video files using OpenCV `VideoWriter`.
|
|
50
|
+
* **Configurable Class Filtering:** Filter detections to specific target COCO classes (e.g., `person`, `car`, `dog`) via CLI or configuration.
|
|
51
|
+
* **Automatic Hardware Acceleration:** Auto-detects CUDA GPUs or Apple Silicon MPS, gracefully falling back to CPU when acceleration is unavailable.
|
|
52
|
+
* **Comprehensive Analytics Export:** Automatically generates per-run structured reports (`summary.csv`, `summary.json`, `run_index.json`) containing object statistics, total frames, and lifetime aggregates.
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Data & Pipeline Details
|
|
57
|
+
|
|
58
|
+
The system processes video feeds through structured pipeline modules:
|
|
59
|
+
|
|
60
|
+
| Component / Module | Implementation File | Description & Functionality |
|
|
61
|
+
| :--- | :--- | :--- |
|
|
62
|
+
| **Config Loader** | `src/config_loader.py` | Parses YAML configurations and merges command-line parameter overrides. |
|
|
63
|
+
| **Validator Engine** | `src/validation.py` | Validates model paths, confidence ranges, device selections, FPS limits, and `imgsz`. |
|
|
64
|
+
| **Device Utility** | `src/device_utils.py` | Detects CUDA/MPS hardware capabilities and enforces CPU fallback when needed. |
|
|
65
|
+
| **Model Loader** | `src/model.py` | Loads YOLO neural network instances and auto-downloads standard pretrained weights. |
|
|
66
|
+
| **Camera Interface** | `src/camera.py` | Opens, reads frames, and safely releases webcam hardware or video file streams. |
|
|
67
|
+
| **Detection Engine** | `src/detector.py` | Performs YOLOv8 object inference, confidence thresholding, and target class filtering. |
|
|
68
|
+
| **Centroid Tracker** | `src/tracker.py` | Associates bounding box centroids across frames using Euclidean distance matrix calculations. |
|
|
69
|
+
| **Runtime Tracker** | `src/runtime_tracker.py` | Tracks object entrance/exit events, active frame counts, and per-class aggregate metrics. |
|
|
70
|
+
| **Results Exporter** | `src/exporter.py` | Serializes session analytics to `summary.csv`, `summary.json`, and `run_index.json`. |
|
|
71
|
+
| **Logger Module** | `src/logger.py` | Configures structured logging to console streams and log files. |
|
|
72
|
+
| **Pipeline Runner** | `src/pipeline.py` | Orchestrates the main execution loop, rendering, video recording, and resource teardown. |
|
|
73
|
+
| **Entry Point** | `main.py` | Development entry point featuring custom help formatting, signal handling, and argument parsing. |
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Tech Stack & Specifications
|
|
78
|
+
|
|
79
|
+
* **Language:** Python `>=3.11`
|
|
80
|
+
* **Computer Vision:** OpenCV (`opencv-python>=4.13.0`)
|
|
81
|
+
* **Deep Learning & Inference:** Ultralytics YOLOv8 (`ultralytics>=8.4.8`), PyTorch
|
|
82
|
+
* **Mathematical Utilities:** SciPy (`scipy>=1.17.0`), NumPy (`numpy>=2.4.1`)
|
|
83
|
+
* **Configuration & Serialization:** PyYAML (`pyyaml>=6.0.3`)
|
|
84
|
+
* **Packaging & Tools:** Setuptools (`setuptools>=61.0`)
|
|
85
|
+
* **Testing Suite:** Pytest (`pytest>=9.0.2`)
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## Environment Setup & Local Development
|
|
90
|
+
|
|
91
|
+
Follow these steps to set up the development environment and run the application locally:
|
|
92
|
+
|
|
93
|
+
### Prerequisites
|
|
94
|
+
* **Python 3.11** or higher installed.
|
|
95
|
+
* **Git** installed.
|
|
96
|
+
* **Webcam** (optional, required for live mode).
|
|
97
|
+
|
|
98
|
+
### Step 1: Clone the Repository
|
|
99
|
+
```bash
|
|
100
|
+
git clone https://github.com/AP-Abhishek/Real-Time-Object-Detector.git
|
|
101
|
+
cd Real-Time-Object-Detector
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Step 2: Create & Activate Virtual Environment
|
|
105
|
+
```bash
|
|
106
|
+
# On Windows
|
|
107
|
+
python -m venv .venv
|
|
108
|
+
.venv\Scripts\activate
|
|
109
|
+
|
|
110
|
+
# On macOS / Linux
|
|
111
|
+
python3 -m venv .venv
|
|
112
|
+
source .venv/bin/activate
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Step 3: Install Dependencies
|
|
116
|
+
```bash
|
|
117
|
+
pip install -r requirements.txt
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Step 4: Run Development Script (`main.py`)
|
|
121
|
+
|
|
122
|
+
#### 1. Live Webcam Detection (Default)
|
|
123
|
+
```bash
|
|
124
|
+
python main.py
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
#### 2. Video File Detection
|
|
128
|
+
```bash
|
|
129
|
+
python main.py --video path/to/video.mp4
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
#### 3. Save Annotated Video Output
|
|
133
|
+
```bash
|
|
134
|
+
python main.py --save-video --output runs/detection_run
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
#### 4. Headless & Benchmark Modes
|
|
138
|
+
```bash
|
|
139
|
+
# Run without rendering display window
|
|
140
|
+
python main.py --headless
|
|
141
|
+
|
|
142
|
+
# Performance benchmark mode
|
|
143
|
+
python main.py --benchmark
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
#### 5. Custom Model & Confidence Threshold
|
|
147
|
+
```bash
|
|
148
|
+
python main.py --model models/yolov8s.pt --confidence 0.7 --device cpu
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Command Line Arguments Reference
|
|
152
|
+
|
|
153
|
+
```text
|
|
154
|
+
usage: python main.py [-h] [--config CONFIG] [--mode {live,video,headless,benchmark}] [--confidence [0-1]]
|
|
155
|
+
[--camera INDEX] [--video PATH] [--output DIR] [--model PATH] [--device {cpu,cuda,mps}]
|
|
156
|
+
[--max-fps N] [--headless] [--benchmark] [--save-video] [-v]
|
|
157
|
+
|
|
158
|
+
Real-Time Object Detection using YOLOv8
|
|
159
|
+
|
|
160
|
+
options:
|
|
161
|
+
-h, --help show this help message and exit
|
|
162
|
+
--config CONFIG Config file path (default: config.yaml)
|
|
163
|
+
--mode {live,video,headless,benchmark} Execution mode
|
|
164
|
+
--confidence [0-1] Detection confidence threshold
|
|
165
|
+
--camera INDEX Camera device index
|
|
166
|
+
--video PATH Video file path (sets mode to video)
|
|
167
|
+
--output DIR Output directory
|
|
168
|
+
--model PATH Model file path
|
|
169
|
+
--device {cpu,cuda,mps} Compute device
|
|
170
|
+
--max-fps N Maximum FPS limit
|
|
171
|
+
--headless No display window (headless mode)
|
|
172
|
+
--benchmark Benchmark mode (no display, print metrics)
|
|
173
|
+
--save-video Save annotated video output to file
|
|
174
|
+
-v, --version show program's version number and exit
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Step 5: Run Automated Test Suite
|
|
178
|
+
```bash
|
|
179
|
+
python -m pytest tests/ -v
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## Project Structure
|
|
185
|
+
|
|
186
|
+
```text
|
|
187
|
+
Real-Time-Object-Detector/
|
|
188
|
+
├── models/ # YOLOv8 model weights (.pt files)
|
|
189
|
+
├── src/
|
|
190
|
+
│ ├── __init__.py # Package initializer
|
|
191
|
+
│ ├── camera.py # OpenCV VideoCapture wrappers for camera and video
|
|
192
|
+
│ ├── config.py # Config dataclass and schema definitions
|
|
193
|
+
│ ├── config_loader.py # YAML config loader and validator integration
|
|
194
|
+
│ ├── detector.py # YOLOv8 inference engine and class filtering
|
|
195
|
+
│ ├── device_utils.py # CUDA / MPS hardware detection and CPU fallback
|
|
196
|
+
│ ├── exporter.py # Export summary JSON, CSV, and index files
|
|
197
|
+
│ ├── logger.py # Logging setup and stream/file handler configuration
|
|
198
|
+
│ ├── model.py # Ultralytics model loader and auto-downloader
|
|
199
|
+
│ ├── pipeline.py # Main detection pipeline, rendering, and recording
|
|
200
|
+
│ ├── runtime_tracker.py # Per-session object lifecycle and class aggregate tracker
|
|
201
|
+
│ ├── tracker.py # CentroidTracker for multi-object tracking and distance association
|
|
202
|
+
│ └── validation.py # Input validation rules and ValidationError exception
|
|
203
|
+
├── tests/ # Automated test suite
|
|
204
|
+
│ ├── __init__.py
|
|
205
|
+
│ ├── conftest.py # Pytest fixtures and mock objects
|
|
206
|
+
│ ├── test_config_loader.py # Config loading and schema validation tests
|
|
207
|
+
│ ├── test_detector.py # YOLO inference wrapper tests
|
|
208
|
+
│ ├── test_exporter.py # CSV/JSON summary export tests
|
|
209
|
+
│ ├── test_logger.py # Logging output tests
|
|
210
|
+
│ ├── test_tracker.py # Centroid tracker association tests
|
|
211
|
+
│ └── test_validation.py # Input parameter validation tests
|
|
212
|
+
├── config.yaml # Default system configuration file
|
|
213
|
+
├── main.py # Development entry point and argument parser
|
|
214
|
+
├── pyproject.toml # Project dependencies and metadata manifest
|
|
215
|
+
├── requirements.txt # Dependency requirements list
|
|
216
|
+
├── verify_setup.py # Setup verification utility script
|
|
217
|
+
└── README.md # Comprehensive project documentation
|
|
218
|
+
```
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# Real-Time Object Detection - Computer Vision & YOLOv8 Inference Pipeline
|
|
2
|
+
|
|
3
|
+
An intelligent computer vision application built with **Python**, **OpenCV**, **Ultralytics YOLOv8**, **SciPy**, and **PyYAML**. It enables real-time object detection and multi-object centroid tracking across live webcam feeds and video files with full analytics reporting (CSV/JSON), optional annotated video recording, class filtering, and high-performance execution modes (`live`, `video`, `headless`, `benchmark`).
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Project Overview & Application Architecture
|
|
8
|
+
|
|
9
|
+
The **Real-Time Object Detection** system leverages an end-to-end vision pipeline to process video frames, identify multi-class targets using neural networks, track object movement across frames, and export structured operational analytics.
|
|
10
|
+
|
|
11
|
+
The core application architecture follows a modular vision & tracking pipeline:
|
|
12
|
+
|
|
13
|
+
1. **Configuration & Validation (`src/config_loader.py` & `src/validation.py`):** Loads and validates YAML settings (`config.yaml`) and CLI parameters, validating confidence thresholds, camera indices, frame rates, image sizes (`imgsz`), model paths, and device parameters (`cpu`, `cuda`, `mps`).
|
|
14
|
+
2. **Device Detection & Fallback (`src/device_utils.py`):** Checks GPU availability (CUDA / Apple Silicon MPS) and automatically selects the optimal hardware compute device with automatic CPU fallback.
|
|
15
|
+
3. **Model Loader & Downloader (`src/model.py`):** Initializes the Ultralytics YOLOv8 architecture (e.g. `yolov8n.pt`, `yolov8s.pt`), automatically fetching standard pretrained weights if missing locally.
|
|
16
|
+
4. **Video Stream Handling (`src/camera.py`):** Wraps OpenCV `VideoCapture` streams for low-latency frame reading from webcams or video files with graceful stream termination.
|
|
17
|
+
5. **Detector Engine & Class Filtering (`src/detector.py`):** Runs YOLOv8 inference per frame, converts bounding box structures, applies confidence thresholds, and filters detections against allowed COCO target classes.
|
|
18
|
+
6. **Centroid Multi-Object Tracker (`src/tracker.py`):** Class-aware and box-aware `CentroidTracker` using SciPy Euclidean distance matrices to track object movement, assign unique IDs, record lifetime durations, and detect frame entry/exit events.
|
|
19
|
+
7. **Runtime Analytics & Serialized Exporter (`src/runtime_tracker.py` & `src/exporter.py`):** Aggregates frame rates, object counts, per-class lifetime statistics, and exports structured reports (`summary.json`, `summary.csv`, `run_index.json`).
|
|
20
|
+
8. **Pipeline Engine & GUI Overlay (`src/pipeline.py` & `main.py`):** Drives the processing loop, renders bounding boxes and performance overlays, records output video (`VideoWriter`), and provides the `main.py` entry point with custom formatted help menus.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Core Modules & Features
|
|
25
|
+
|
|
26
|
+
* **Real-Time Object Detection:** Powered by Ultralytics YOLOv8 for precise multi-class object detection across live video feeds.
|
|
27
|
+
* **Class-Aware Centroid Tracking:** Stable multi-object tracking with persistent object IDs, entrance/exit event triggers, and lifetime duration monitoring.
|
|
28
|
+
* **Dual Input Sources:** Supports live webcam hardware feeds as well as video file inputs (`--video path/to/video.mp4`).
|
|
29
|
+
* **Flexible Execution Modes:** Four distinct runtime operating modes:
|
|
30
|
+
* `live`: Interactive GUI window displaying real-time webcam feed with object bounding boxes.
|
|
31
|
+
* `video`: Processes input video files with on-screen bounding boxes and FPS overlays.
|
|
32
|
+
* `headless`: Background processing without rendering GUI display windows (ideal for headless servers).
|
|
33
|
+
* `benchmark`: Automated performance benchmark mode calculating total frames, elapsed time, and average FPS.
|
|
34
|
+
* **Annotated Video Saving (`--save-video`):** Optionally records fully annotated detection feeds to MP4 video files using OpenCV `VideoWriter`.
|
|
35
|
+
* **Configurable Class Filtering:** Filter detections to specific target COCO classes (e.g., `person`, `car`, `dog`) via CLI or configuration.
|
|
36
|
+
* **Automatic Hardware Acceleration:** Auto-detects CUDA GPUs or Apple Silicon MPS, gracefully falling back to CPU when acceleration is unavailable.
|
|
37
|
+
* **Comprehensive Analytics Export:** Automatically generates per-run structured reports (`summary.csv`, `summary.json`, `run_index.json`) containing object statistics, total frames, and lifetime aggregates.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Data & Pipeline Details
|
|
42
|
+
|
|
43
|
+
The system processes video feeds through structured pipeline modules:
|
|
44
|
+
|
|
45
|
+
| Component / Module | Implementation File | Description & Functionality |
|
|
46
|
+
| :--- | :--- | :--- |
|
|
47
|
+
| **Config Loader** | `src/config_loader.py` | Parses YAML configurations and merges command-line parameter overrides. |
|
|
48
|
+
| **Validator Engine** | `src/validation.py` | Validates model paths, confidence ranges, device selections, FPS limits, and `imgsz`. |
|
|
49
|
+
| **Device Utility** | `src/device_utils.py` | Detects CUDA/MPS hardware capabilities and enforces CPU fallback when needed. |
|
|
50
|
+
| **Model Loader** | `src/model.py` | Loads YOLO neural network instances and auto-downloads standard pretrained weights. |
|
|
51
|
+
| **Camera Interface** | `src/camera.py` | Opens, reads frames, and safely releases webcam hardware or video file streams. |
|
|
52
|
+
| **Detection Engine** | `src/detector.py` | Performs YOLOv8 object inference, confidence thresholding, and target class filtering. |
|
|
53
|
+
| **Centroid Tracker** | `src/tracker.py` | Associates bounding box centroids across frames using Euclidean distance matrix calculations. |
|
|
54
|
+
| **Runtime Tracker** | `src/runtime_tracker.py` | Tracks object entrance/exit events, active frame counts, and per-class aggregate metrics. |
|
|
55
|
+
| **Results Exporter** | `src/exporter.py` | Serializes session analytics to `summary.csv`, `summary.json`, and `run_index.json`. |
|
|
56
|
+
| **Logger Module** | `src/logger.py` | Configures structured logging to console streams and log files. |
|
|
57
|
+
| **Pipeline Runner** | `src/pipeline.py` | Orchestrates the main execution loop, rendering, video recording, and resource teardown. |
|
|
58
|
+
| **Entry Point** | `main.py` | Development entry point featuring custom help formatting, signal handling, and argument parsing. |
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Tech Stack & Specifications
|
|
63
|
+
|
|
64
|
+
* **Language:** Python `>=3.11`
|
|
65
|
+
* **Computer Vision:** OpenCV (`opencv-python>=4.13.0`)
|
|
66
|
+
* **Deep Learning & Inference:** Ultralytics YOLOv8 (`ultralytics>=8.4.8`), PyTorch
|
|
67
|
+
* **Mathematical Utilities:** SciPy (`scipy>=1.17.0`), NumPy (`numpy>=2.4.1`)
|
|
68
|
+
* **Configuration & Serialization:** PyYAML (`pyyaml>=6.0.3`)
|
|
69
|
+
* **Packaging & Tools:** Setuptools (`setuptools>=61.0`)
|
|
70
|
+
* **Testing Suite:** Pytest (`pytest>=9.0.2`)
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## Environment Setup & Local Development
|
|
75
|
+
|
|
76
|
+
Follow these steps to set up the development environment and run the application locally:
|
|
77
|
+
|
|
78
|
+
### Prerequisites
|
|
79
|
+
* **Python 3.11** or higher installed.
|
|
80
|
+
* **Git** installed.
|
|
81
|
+
* **Webcam** (optional, required for live mode).
|
|
82
|
+
|
|
83
|
+
### Step 1: Clone the Repository
|
|
84
|
+
```bash
|
|
85
|
+
git clone https://github.com/AP-Abhishek/Real-Time-Object-Detector.git
|
|
86
|
+
cd Real-Time-Object-Detector
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Step 2: Create & Activate Virtual Environment
|
|
90
|
+
```bash
|
|
91
|
+
# On Windows
|
|
92
|
+
python -m venv .venv
|
|
93
|
+
.venv\Scripts\activate
|
|
94
|
+
|
|
95
|
+
# On macOS / Linux
|
|
96
|
+
python3 -m venv .venv
|
|
97
|
+
source .venv/bin/activate
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Step 3: Install Dependencies
|
|
101
|
+
```bash
|
|
102
|
+
pip install -r requirements.txt
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Step 4: Run Development Script (`main.py`)
|
|
106
|
+
|
|
107
|
+
#### 1. Live Webcam Detection (Default)
|
|
108
|
+
```bash
|
|
109
|
+
python main.py
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
#### 2. Video File Detection
|
|
113
|
+
```bash
|
|
114
|
+
python main.py --video path/to/video.mp4
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
#### 3. Save Annotated Video Output
|
|
118
|
+
```bash
|
|
119
|
+
python main.py --save-video --output runs/detection_run
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
#### 4. Headless & Benchmark Modes
|
|
123
|
+
```bash
|
|
124
|
+
# Run without rendering display window
|
|
125
|
+
python main.py --headless
|
|
126
|
+
|
|
127
|
+
# Performance benchmark mode
|
|
128
|
+
python main.py --benchmark
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
#### 5. Custom Model & Confidence Threshold
|
|
132
|
+
```bash
|
|
133
|
+
python main.py --model models/yolov8s.pt --confidence 0.7 --device cpu
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Command Line Arguments Reference
|
|
137
|
+
|
|
138
|
+
```text
|
|
139
|
+
usage: python main.py [-h] [--config CONFIG] [--mode {live,video,headless,benchmark}] [--confidence [0-1]]
|
|
140
|
+
[--camera INDEX] [--video PATH] [--output DIR] [--model PATH] [--device {cpu,cuda,mps}]
|
|
141
|
+
[--max-fps N] [--headless] [--benchmark] [--save-video] [-v]
|
|
142
|
+
|
|
143
|
+
Real-Time Object Detection using YOLOv8
|
|
144
|
+
|
|
145
|
+
options:
|
|
146
|
+
-h, --help show this help message and exit
|
|
147
|
+
--config CONFIG Config file path (default: config.yaml)
|
|
148
|
+
--mode {live,video,headless,benchmark} Execution mode
|
|
149
|
+
--confidence [0-1] Detection confidence threshold
|
|
150
|
+
--camera INDEX Camera device index
|
|
151
|
+
--video PATH Video file path (sets mode to video)
|
|
152
|
+
--output DIR Output directory
|
|
153
|
+
--model PATH Model file path
|
|
154
|
+
--device {cpu,cuda,mps} Compute device
|
|
155
|
+
--max-fps N Maximum FPS limit
|
|
156
|
+
--headless No display window (headless mode)
|
|
157
|
+
--benchmark Benchmark mode (no display, print metrics)
|
|
158
|
+
--save-video Save annotated video output to file
|
|
159
|
+
-v, --version show program's version number and exit
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Step 5: Run Automated Test Suite
|
|
163
|
+
```bash
|
|
164
|
+
python -m pytest tests/ -v
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## Project Structure
|
|
170
|
+
|
|
171
|
+
```text
|
|
172
|
+
Real-Time-Object-Detector/
|
|
173
|
+
├── models/ # YOLOv8 model weights (.pt files)
|
|
174
|
+
├── src/
|
|
175
|
+
│ ├── __init__.py # Package initializer
|
|
176
|
+
│ ├── camera.py # OpenCV VideoCapture wrappers for camera and video
|
|
177
|
+
│ ├── config.py # Config dataclass and schema definitions
|
|
178
|
+
│ ├── config_loader.py # YAML config loader and validator integration
|
|
179
|
+
│ ├── detector.py # YOLOv8 inference engine and class filtering
|
|
180
|
+
│ ├── device_utils.py # CUDA / MPS hardware detection and CPU fallback
|
|
181
|
+
│ ├── exporter.py # Export summary JSON, CSV, and index files
|
|
182
|
+
│ ├── logger.py # Logging setup and stream/file handler configuration
|
|
183
|
+
│ ├── model.py # Ultralytics model loader and auto-downloader
|
|
184
|
+
│ ├── pipeline.py # Main detection pipeline, rendering, and recording
|
|
185
|
+
│ ├── runtime_tracker.py # Per-session object lifecycle and class aggregate tracker
|
|
186
|
+
│ ├── tracker.py # CentroidTracker for multi-object tracking and distance association
|
|
187
|
+
│ └── validation.py # Input validation rules and ValidationError exception
|
|
188
|
+
├── tests/ # Automated test suite
|
|
189
|
+
│ ├── __init__.py
|
|
190
|
+
│ ├── conftest.py # Pytest fixtures and mock objects
|
|
191
|
+
│ ├── test_config_loader.py # Config loading and schema validation tests
|
|
192
|
+
│ ├── test_detector.py # YOLO inference wrapper tests
|
|
193
|
+
│ ├── test_exporter.py # CSV/JSON summary export tests
|
|
194
|
+
│ ├── test_logger.py # Logging output tests
|
|
195
|
+
│ ├── test_tracker.py # Centroid tracker association tests
|
|
196
|
+
│ └── test_validation.py # Input parameter validation tests
|
|
197
|
+
├── config.yaml # Default system configuration file
|
|
198
|
+
├── main.py # Development entry point and argument parser
|
|
199
|
+
├── pyproject.toml # Project dependencies and metadata manifest
|
|
200
|
+
├── requirements.txt # Dependency requirements list
|
|
201
|
+
├── verify_setup.py # Setup verification utility script
|
|
202
|
+
└── README.md # Comprehensive project documentation
|
|
203
|
+
```
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import os
|
|
2
|
+
os.environ["YOLO_VERBOSE"] = "False"
|
|
3
|
+
import sys
|
|
4
|
+
import argparse
|
|
5
|
+
from src import __version__
|
|
6
|
+
from src.pipeline import run_pipeline
|
|
7
|
+
from src.config_loader import load_config
|
|
8
|
+
from src.model import load_model
|
|
9
|
+
from src.camera import open_camera, open_video
|
|
10
|
+
from src.logger import setup_logger, get_logger
|
|
11
|
+
from src.validation import ValidationError
|
|
12
|
+
from src.device_utils import get_device_info, validate_and_fallback
|
|
13
|
+
|
|
14
|
+
class CustomHelpFormatter(argparse.RawDescriptionHelpFormatter):
|
|
15
|
+
def __init__(self, prog):
|
|
16
|
+
super().__init__(prog, max_help_position=42, width=110)
|
|
17
|
+
|
|
18
|
+
def parse_args() -> argparse.Namespace:
|
|
19
|
+
is_uv = any(k.startswith("UV") for k in os.environ)
|
|
20
|
+
is_rtod = sys.argv[0].endswith("rtod") or sys.argv[0].endswith("rtod.exe")
|
|
21
|
+
if is_uv:
|
|
22
|
+
cmd = "uv run rtod" if is_rtod else "uv run main.py"
|
|
23
|
+
else:
|
|
24
|
+
cmd = "rtod" if is_rtod else "python main.py"
|
|
25
|
+
parser = argparse.ArgumentParser(
|
|
26
|
+
description="Real-Time Object Detection using YOLOv8",
|
|
27
|
+
formatter_class=CustomHelpFormatter,
|
|
28
|
+
epilog=f"""
|
|
29
|
+
Examples:
|
|
30
|
+
{cmd}
|
|
31
|
+
{cmd} --video video.mp4
|
|
32
|
+
{cmd} --confidence 0.7
|
|
33
|
+
{cmd} --headless
|
|
34
|
+
{cmd} --model models/yolov8s.pt
|
|
35
|
+
"""
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
parser.add_argument("--config", type=str, default="config.yaml",
|
|
39
|
+
help="Config file path (default: config.yaml)")
|
|
40
|
+
parser.add_argument("--mode", type=str, choices=["live", "video", "headless", "benchmark"],
|
|
41
|
+
help="Execution mode")
|
|
42
|
+
parser.add_argument("--confidence", type=float, metavar="[0-1]",
|
|
43
|
+
help="Detection confidence threshold")
|
|
44
|
+
parser.add_argument("--camera", type=int, metavar="INDEX",
|
|
45
|
+
help="Camera device index")
|
|
46
|
+
parser.add_argument("--video", type=str, metavar="PATH",
|
|
47
|
+
help="Video file path (sets mode to video)")
|
|
48
|
+
parser.add_argument("--output", type=str, metavar="DIR",
|
|
49
|
+
help="Output directory")
|
|
50
|
+
parser.add_argument("--model", type=str, metavar="PATH",
|
|
51
|
+
help="Model file path")
|
|
52
|
+
parser.add_argument("--device", type=str, choices=["cpu", "cuda", "mps"],
|
|
53
|
+
help="Compute device")
|
|
54
|
+
parser.add_argument("--max-fps", type=float, metavar="N",
|
|
55
|
+
help="Maximum FPS limit")
|
|
56
|
+
parser.add_argument("--headless", action="store_true",
|
|
57
|
+
help="No display window (headless mode)")
|
|
58
|
+
parser.add_argument("--benchmark", action="store_true",
|
|
59
|
+
help="Benchmark mode (no display, print metrics)")
|
|
60
|
+
parser.add_argument("--save-video", action="store_true",
|
|
61
|
+
help="Save annotated video output to file")
|
|
62
|
+
parser.add_argument("-v", "--version", action="version", version=__version__)
|
|
63
|
+
|
|
64
|
+
return parser.parse_args()
|
|
65
|
+
|
|
66
|
+
def main() -> None:
|
|
67
|
+
args = parse_args()
|
|
68
|
+
|
|
69
|
+
logger = setup_logger()
|
|
70
|
+
|
|
71
|
+
dev_info = get_device_info()
|
|
72
|
+
if dev_info["cuda_available"]:
|
|
73
|
+
logger.info(f"GPU available: {dev_info['cuda_device_name']}")
|
|
74
|
+
else:
|
|
75
|
+
logger.info("GPU not available, using CPU")
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
logger.info("Loading configuration...")
|
|
79
|
+
cfg = load_config(args.config)
|
|
80
|
+
logger.info("Configuration loaded successfully")
|
|
81
|
+
except FileNotFoundError as e:
|
|
82
|
+
logger.error(f"Config not found: {e}")
|
|
83
|
+
sys.exit(1)
|
|
84
|
+
except ValidationError as e:
|
|
85
|
+
logger.error(f"Config invalid: {e}")
|
|
86
|
+
sys.exit(1)
|
|
87
|
+
|
|
88
|
+
runtime = cfg.get("runtime", {})
|
|
89
|
+
model_cfg = cfg.get("model", {})
|
|
90
|
+
|
|
91
|
+
if args.mode:
|
|
92
|
+
runtime["mode"] = args.mode
|
|
93
|
+
if args.video:
|
|
94
|
+
runtime["mode"] = "video"
|
|
95
|
+
runtime["video_path"] = args.video
|
|
96
|
+
if args.confidence is not None:
|
|
97
|
+
runtime["confidence"] = args.confidence
|
|
98
|
+
if args.camera is not None:
|
|
99
|
+
runtime["camera_index"] = args.camera
|
|
100
|
+
if args.output:
|
|
101
|
+
runtime["output_dir"] = args.output
|
|
102
|
+
if args.max_fps is not None:
|
|
103
|
+
runtime["max_fps"] = args.max_fps
|
|
104
|
+
if args.headless:
|
|
105
|
+
runtime["mode"] = "headless"
|
|
106
|
+
if args.benchmark:
|
|
107
|
+
runtime["mode"] = "benchmark"
|
|
108
|
+
if args.save_video:
|
|
109
|
+
runtime["save_video"] = True
|
|
110
|
+
if args.model:
|
|
111
|
+
model_cfg["path"] = args.model
|
|
112
|
+
if args.device:
|
|
113
|
+
model_cfg["device"] = args.device
|
|
114
|
+
|
|
115
|
+
mode = runtime.get("mode", "live")
|
|
116
|
+
conf = runtime.get("confidence", 0.5)
|
|
117
|
+
max_fps = runtime.get("max_fps")
|
|
118
|
+
window_name = runtime.get("window_name", "Real-Time Object Detector")
|
|
119
|
+
output_dir = runtime.get("output_dir") or "runs/latest"
|
|
120
|
+
save_video = runtime.get("save_video", False)
|
|
121
|
+
|
|
122
|
+
logger.info(f"Mode: {mode}, Confidence: {conf}, FPS: {max_fps}")
|
|
123
|
+
|
|
124
|
+
allowed_classes = runtime.get("allowed_classes")
|
|
125
|
+
if isinstance(allowed_classes, (list, tuple, set)):
|
|
126
|
+
allowed_classes = set(allowed_classes)
|
|
127
|
+
else:
|
|
128
|
+
allowed_classes = None
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
logger.info(f"Loading model from {model_cfg.get('path')}...")
|
|
132
|
+
model = load_model(cfg)
|
|
133
|
+
logger.info(f"Model loaded on device: {model_cfg.get('device')}")
|
|
134
|
+
except (ValidationError, RuntimeError) as e:
|
|
135
|
+
logger.error(f"Model load failed: {e}")
|
|
136
|
+
sys.exit(1)
|
|
137
|
+
|
|
138
|
+
is_video = mode == "video"
|
|
139
|
+
headless = mode in ("headless", "benchmark")
|
|
140
|
+
benchmark = mode == "benchmark"
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
if mode == "video":
|
|
144
|
+
logger.info(f"Opening video: {runtime.get('video_path')}")
|
|
145
|
+
cap = open_video(runtime.get("video_path"))
|
|
146
|
+
else:
|
|
147
|
+
logger.info(f"Opening camera at index {runtime.get('camera_index', 0)}")
|
|
148
|
+
cap = open_camera(runtime.get("camera_index", 0))
|
|
149
|
+
logger.info("Camera/video opened successfully")
|
|
150
|
+
|
|
151
|
+
logger.info("Starting detection pipeline...")
|
|
152
|
+
run_pipeline(
|
|
153
|
+
cap=cap,
|
|
154
|
+
model=model,
|
|
155
|
+
logger=logger,
|
|
156
|
+
conf=conf,
|
|
157
|
+
allowed_classes=allowed_classes,
|
|
158
|
+
window_name=window_name,
|
|
159
|
+
output_dir=output_dir,
|
|
160
|
+
max_fps=max_fps,
|
|
161
|
+
is_video=is_video,
|
|
162
|
+
headless=headless,
|
|
163
|
+
benchmark=benchmark,
|
|
164
|
+
save_video=save_video,
|
|
165
|
+
)
|
|
166
|
+
logger.info("Pipeline completed successfully")
|
|
167
|
+
except KeyboardInterrupt:
|
|
168
|
+
logger.info("Keyboard interrupt received (Ctrl+C). Exiting pipeline cleanly.")
|
|
169
|
+
sys.exit(0)
|
|
170
|
+
except (ValidationError, RuntimeError) as e:
|
|
171
|
+
logger.error(f"Failed to open camera/video: {e}")
|
|
172
|
+
sys.exit(1)
|
|
173
|
+
except Exception as e:
|
|
174
|
+
logger.error(f"Pipeline failed: {e}")
|
|
175
|
+
sys.exit(1)
|
|
176
|
+
|
|
177
|
+
if __name__ == "__main__":
|
|
178
|
+
main()
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "real-time-object-detection"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "A real-time computer vision project that uses a webcam and the YOLOv8 model to detect and label objects as they appear on screen, drawing bounding boxes around them using OpenCV."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"numpy>=2.4.1",
|
|
13
|
+
"opencv-python>=4.13.0.90",
|
|
14
|
+
"pytest>=9.0.2",
|
|
15
|
+
"pyyaml>=6.0.3",
|
|
16
|
+
"scipy>=1.17.0",
|
|
17
|
+
"ultralytics>=8.4.8",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[tool.setuptools]
|
|
21
|
+
py-modules = ["main"]
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.dynamic]
|
|
24
|
+
version = {attr = "src.__version__"}
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
where = ["."]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
dev = [
|
|
31
|
+
"pytest>=7.0",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
rtod = "main:main"
|
|
36
|
+
|