It sounds like you're experiencing a limitation where your current traffic monitoring system is only analyzing a corner of the video frame rather than the entire frame. To address this, we can enhance your existing system with more advanced logic to ensure comprehensive analysis across the whole frame. Below are several improvements and an updated version of your code incorporating these enhancements:
-
Enhanced Object Tracking:
- Issue: The current tracking mechanism is relatively simple, relying on the distance between bounding box centers. This can lead to inaccuracies, especially in crowded scenes.
- Solution: Integrate a more robust tracking algorithm like Deep SORT or ByteTrack. These trackers use additional features and algorithms to maintain object identities more reliably across frames.
-
Full-Frame Analysis:
- Issue: If the current implementation unintentionally restricts analysis to a corner (possibly due to overlaying the legend or other processing), we need to ensure that the entire frame is utilized for detection and tracking.
- Solution: Adjust the layout to ensure that overlays (like the legend) do not interfere with the detection area. Ensure that the detection model processes the full frame without cropping or masking.
-
Optimized Legend Placement:
- Issue: The legend panel occupies 10% of the frame width, which may inadvertently limit the processing area or skew the analysis if the model is sensitive to frame geometry changes.
- Solution: Instead of concatenating the legend to the frame, consider displaying it in a separate window or position it in a way that doesn't affect the frame's aspect ratio used for detection.
-
Performance Improvements:
- Issue: Processing high-resolution videos or using complex tracking algorithms can be computationally intensive.
- Solution: Optimize model inference by resizing frames appropriately, leveraging hardware acceleration (like GPU), and ensuring that only necessary computations are performed per frame.
-
Error Handling and Robustness:
- Issue: Ensure that the system gracefully handles unexpected scenarios, such as abrupt video source termination or model inference failures.
- Solution: Implement comprehensive error handling and possibly retry mechanisms for transient failures.
Below is the updated version of your TrafficMonitor class incorporating these enhancements. This version integrates Deep SORT for improved tracking, ensures full-frame analysis, and optimizes the legend placement.
Updated Code:
import sys
import cv2
import logging
from typing import List, Union, Optional, Dict, Tuple
from datetime import datetime
from pathlib import Path
from threading import Thread
import numpy as np
from ultralytics import YOLO
from collections import defaultdict
# Import Deep SORT components
from deep_sort_realtime.deepsort_tracker import DeepSort
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
# Constants for traffic density thresholds
LOW_THRESHOLD: int = 10 # Less than 10 vehicles per frame
MEDIUM_THRESHOLD: int = 30 # 10 to 30 vehicles per frame
# Vehicle classes based on YOLOv8's COCO dataset
VEHICLE_CLASSES: set = {'car', 'truck', 'bus', 'motorbike', 'bicycle'}
class ReportGenerator:
"""
Generates and saves HTML reports with traffic density and vehicle type visualizations.
"""
def __init__(self, output_folder: Path) -> None:
self.output_folder: Path = output_folder
def generate_html_report(
self,
timestamps: List[datetime],
vehicle_counts: List[int],
vehicle_type_counts: List[Dict[str, int]]
) -> None:
"""
Generates an HTML report summarizing traffic metrics and vehicle types.
:param timestamps: List of timestamps corresponding to each frame.
:param vehicle_counts: List of total vehicle counts per frame.
:param vehicle_type_counts: List of vehicle type counts per frame.
"""
try:
if not timestamps or not vehicle_counts:
logging.warning("No data available to generate report.")
return
report_filename: str = f"traffic_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
report_path: Path = self.output_folder / report_filename
with report_path.open('w') as report_file:
report_file.write("<html><head><title>Traffic Report</title></head><body>")
report_file.write("<h1>Traffic Density Over Time</h1>")
report_file.write("<table border='1'>")
report_file.write("<tr><th>Timestamp</th><th>Total Vehicle Count</th>")
for vehicle_type in sorted(VEHICLE_CLASSES):
report_file.write(f"<th>{vehicle_type.capitalize()} Count</th>")
report_file.write("</tr>")
for ts, count, type_counts in zip(timestamps, vehicle_counts, vehicle_type_counts):
report_file.write(f"<tr><td>{ts.strftime('%H:%M:%S')}</td><td>{count}</td>")
for vehicle_type in sorted(VEHICLE_CLASSES):
report_file.write(f"<td>{type_counts.get(vehicle_type, 0)}</td>")
report_file.write("</tr>")
report_file.write("</table></body></html>")
logging.info(f"HTML report generated at: {report_path.resolve()}")
except Exception as e:
logging.error(f"Failed to generate HTML report: {e}")
class TrafficMonitor:
"""
Monitors traffic by processing video streams, detecting vehicles, tracking them, and maintaining traffic metrics.
"""
def __init__(
self,
source: Union[str, int],
model_path: str = 'yolov8n.pt',
output_folder: str = 'traffic_reports'
) -> None:
self.source: Union[str, int] = source
self.output_folder: Path = Path(output_folder)
self.model_path: str = model_path
self.model: Optional[YOLO] = None
self.cap: Optional[cv2.VideoCapture] = None
self.timestamps: List[datetime] = []
self.vehicle_counts: List[int] = []
self.vehicle_type_counts: List[Dict[str, int]] = []
self.report_generator: Optional[ReportGenerator] = None
self.frame_number: int = 0
self.frame_width: int = 0
self.frame_height: int = 0
self.legend_width_ratio: float = 0.25 # 25% of the frame width for legend
self.colors: Dict[str, Tuple[int, int, int]] = {
'Low Traffic': (0, 255, 0),
'Medium Traffic': (0, 165, 255),
'High Traffic': (0, 0, 255)
}
self.tracker = DeepSort(max_age=30) # Initialize Deep SORT tracker
self.lock = False # Simple lock to prevent concurrent access during cleanup
self._initialize()
def _initialize(self) -> None:
"""
Initialize the traffic monitor by setting up the output folder and loading the YOLO model.
"""
self._create_output_folder()
self._load_yolo_model()
self.report_generator = ReportGenerator(self.output_folder)
def _create_output_folder(self) -> None:
"""
Create an output folder if it doesn't exist.
"""
try:
self.output_folder.mkdir(parents=True, exist_ok=True)
logging.info(f"Output folder is set to: {self.output_folder.resolve()}")
except Exception as e:
logging.error(f"Failed to create output folder '{self.output_folder}': {e}")
sys.exit(1)
def _load_yolo_model(self) -> None:
"""
Load the YOLOv8 model.
"""
try:
self.model = YOLO(self.model_path)
logging.info("YOLOv8 model loaded successfully.")
except Exception as e:
logging.error(f"Failed to load YOLOv8 model: {e}")
sys.exit(1)
@staticmethod
def classify_traffic_density(vehicle_count: int) -> str:
"""
Classify traffic density based on the number of vehicles detected.
:param vehicle_count: Number of vehicles detected in the frame.
:return: Traffic density category as a string.
"""
if vehicle_count < LOW_THRESHOLD:
return 'Low Traffic'
elif LOW_THRESHOLD <= vehicle_count < MEDIUM_THRESHOLD:
return 'Medium Traffic'
else:
return 'High Traffic'
def _process_detections(self, detections) -> Tuple[int, Dict[str, int]]:
"""
Process YOLO detections, track vehicles, and count vehicle types.
:param detections: YOLO detections for the current frame.
:return: Tuple containing the number of unique vehicles detected and a dictionary of vehicle types counts.
"""
vehicle_type_count: Dict[str, int] = defaultdict(int)
bbox_xywh = []
confidences = []
class_ids = []
for det in detections:
try:
cls_id: int = int(det.cls[0])
cls_name: str = self.model.names.get(cls_id, '')
if cls_name in VEHICLE_CLASSES:
x1, y1, x2, y2 = det.xyxy[0]
bbox_width = x2 - x1
bbox_height = y2 - y1
bbox_center_x = x1 + bbox_width / 2
bbox_center_y = y1 + bbox_height / 2
bbox_xywh.append([bbox_center_x, bbox_center_y, bbox_width, bbox_height])
confidences.append(float(det.conf[0]))
class_ids.append(cls_id)
except Exception as e:
logging.error(f"Error processing detection: {e}")
# Update tracker with detections
tracks = self.tracker.update_tracks(bbox_xywh, confidences, class_ids, frame=self.frame)
for track in tracks:
if not track.is_confirmed():
continue
track_id = track.track_id
cls_id = track.det_class
cls_name = self.model.names.get(cls_id, '')
if cls_name in VEHICLE_CLASSES:
vehicle_type_count[cls_name] += 1
bbox = track.to_ltrb()
x1, y1, x2, y2 = map(int, bbox)
# Assign a color based on vehicle type
color = self._get_vehicle_color(cls_name)
# Draw bounding box and label
cv2.rectangle(
self.frame, (x1, y1), (x2, y2), color, 2
)
cv2.putText(
self.frame, f"{cls_name} ID:{track_id}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2
)
unique_vehicles = len(tracks)
return unique_vehicles, dict(vehicle_type_count)
def _get_vehicle_color(self, vehicle_type: str) -> Tuple[int, int, int]:
"""
Assign a unique color based on vehicle type.
:param vehicle_type: Type of the vehicle.
:return: BGR color tuple.
"""
color_map = {
'car': (255, 0, 0),
'truck': (0, 255, 0),
'bus': (0, 0, 255),
'motorbike': (255, 255, 0),
'bicycle': (0, 255, 255)
}
return color_map.get(vehicle_type, (255, 255, 255)) # Default to white
def _add_overlay_info(
self,
traffic_density: str,
total_vehicles: int,
vehicle_type_counts: Dict[str, int]
) -> None:
"""
Adds overlay information on the frame including traffic density, total vehicles, and vehicle type counts.
:param traffic_density: The classified traffic density.
:param total_vehicles: Total number of vehicles detected.
:param vehicle_type_counts: Dictionary of vehicle types and their counts.
"""
try:
overlay = self.frame.copy()
alpha = 0.6 # Transparency factor
# Define overlay properties
cv2.rectangle(
overlay, (0, 0), (self.frame_width, int(self.frame_height * 0.2)),
(50, 50, 50), -1
)
cv2.addWeighted(overlay, alpha, self.frame, 1 - alpha, 0, self.frame)
# Display current total vehicle count
cv2.putText(
self.frame, f"Total Vehicles: {total_vehicles}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2
)
# Display traffic density
cv2.putText(
self.frame, f"Traffic Density: {traffic_density}", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, self.colors.get(traffic_density, (255, 255, 255)), 2
)
# Display vehicle type counts
y_offset = 90
for vehicle_type in sorted(VEHICLE_CLASSES):
count = vehicle_type_counts.get(vehicle_type, 0)
text = f"{vehicle_type.capitalize()}: {count}"
cv2.putText(
self.frame, text, (10, y_offset),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2
)
y_offset += 30
except Exception as e:
logging.error(f"Failed to add overlay information: {e}")
def process_stream(self) -> None:
"""
Process the video stream, perform object detection, track vehicles, and collect traffic metrics.
"""
try:
self.cap = cv2.VideoCapture(self.source)
if not self.cap.isOpened():
logging.error(f"Cannot open video source: {self.source}")
sys.exit(1)
else:
logging.info(f"Video source '{self.source}' opened successfully.")
# Retrieve frame dimensions
ret, frame = self.cap.read()
if not ret:
logging.error("Failed to read from video source.")
sys.exit(1)
self.frame_height, self.frame_width = frame.shape[:2]
self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0) # Reset to first frame
while True:
ret, frame = self.cap.read()
if not ret:
logging.warning("No frame received. Exiting...")
break
self.frame_number += 1
self.frame: np.ndarray = frame.copy() # Make a copy to draw annotations
timestamp: datetime = datetime.now()
self.timestamps.append(timestamp)
# Perform object detection with increased confidence threshold for better accuracy
results = self.model.predict(self.frame, conf=0.5, verbose=False)
# Extract detected classes and count vehicles
detections = results[0].boxes
total_vehicles, vehicle_type_count = self._process_detections(detections)
self.vehicle_counts.append(total_vehicles)
self.vehicle_type_counts.append(vehicle_type_count)
traffic_density = self.classify_traffic_density(total_vehicles)
# Add overlay information
self._add_overlay_info(traffic_density, total_vehicles, vehicle_type_count)
# Display the resulting frame with overlay
cv2.imshow('Real-Time Traffic Monitoring', self.frame)
# Break the loop on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
logging.info("Exit signal received. Stopping video processing...")
break
# Logging every 100 frames to avoid excessive log entries
if self.frame_number % 100 == 0:
logging.info(f"Processed {self.frame_number} frames.")
self._cleanup()
except KeyboardInterrupt:
logging.info("Keyboard interrupt received. Exiting gracefully...")
self._cleanup()
except Exception as e:
logging.error(f"An error occurred during video processing: {e}")
self._cleanup()
sys.exit(1)
def _cleanup(self) -> None:
"""
Release video capture and destroy all OpenCV windows. Generate the report.
"""
if self.lock:
return # Prevent re-entrance
self.lock = True
try:
if self.cap and self.cap.isOpened():
self.cap.release()
logging.info("Video capture released.")
cv2.destroyAllWindows()
logging.info("All OpenCV windows destroyed.")
if self.report_generator:
# Generate the HTML report in a separate thread to avoid blocking
report_thread: Thread = Thread(
target=self.report_generator.generate_html_report,
args=(self.timestamps, self.vehicle_counts, self.vehicle_type_counts),
daemon=True
)
report_thread.start()
logging.info("Report generation started in a separate thread.")
except Exception as e:
logging.error(f"Failed during cleanup: {e}")
finally:
self.lock = False
def get_video_source() -> Union[str, int]:
"""
Prompt the user to choose between uploading a video or using the webcam.
:return: Video source (file path or webcam index).
"""
while True:
print("\nSelect Video Source:")
print("1. Upload a video file")
print("2. Use webcam for real-time recording")
choice: str = input("Enter your choice (1 or 2): ").strip()
if choice == '1':
file_path: str = input("Enter the path to the video file: ").strip()
if Path(file_path).is_file():
logging.info(f"Selected video file: {file_path}")
return file_path
else:
logging.error(f"File not found: {file_path}")
elif choice == '2':
logging.info("Selected webcam for real-time recording.")
return 0 # Typically, 0 is the default webcam index
else:
logging.error("Invalid choice. Please enter 1 or 2.")
def main() -> None:
"""
Main function to set up and run the traffic monitoring system based on user choice.
"""
try:
# Get user choice for video source
video_source: Union[str, int] = get_video_source()
# Initialize and start the traffic monitor
traffic_monitor: TrafficMonitor = TrafficMonitor(source=video_source)
traffic_monitor.process_stream()
except Exception as e:
logging.error(f"An unexpected error occurred in the main function: {e}")
sys.exit(1)
if __name__ == '__main__':
main()
Key Enhancements Explained:
-
Integration of Deep SORT for Advanced Tracking:
- Deep SORT is a popular tracking algorithm that provides more robust tracking by using appearance features and motion information.
- Implementation Steps:
- Installation: First, install the
deep_sort_realtime package using pip:
pip install deep_sort_realtime
- Tracker Initialization: Initialize the Deep SORT tracker in the
__init__ method:
self.tracker = DeepSort(max_age=30) # max_age defines how long to keep a track without detections
- Processing Detections: Modify the
_process_detections method to format detections appropriately and update the tracker:
bbox_xywh = []
confidences = []
class_ids = []
for det in detections:
if cls_name in VEHICLE_CLASSES:
# Convert bbox to (x_center, y_center, width, height)
bbox_xywh.append([x_center, y_center, width, height])
confidences.append(confidence_score)
class_ids.append(cls_id)
tracks = self.tracker.update_tracks(bbox_xywh, confidences, class_ids, frame=self.frame)
- Drawing Bounding Boxes: Iterate over the
tracks returned by Deep SORT and draw bounding boxes with unique IDs for each vehicle.
-
Full-Frame Analysis with Overlay Information:
- Issue Addressed: Ensures that the entire frame is processed without any regions being excluded due to overlays or legends.
- Solution: Instead of concatenating a separate legend panel to the frame, use an overlay at the top of the frame to display traffic metrics. This approach maintains the original frame dimensions and ensures full-frame analysis.
- Implementation:
- An overlay is created and blended with the original frame using
cv2.addWeighted for transparency.
- Traffic information like total vehicle count, traffic density, and vehicle type counts are displayed on this overlay.
-
Optimized Legend Placement:
- Original Approach: Legends or overlays might have been taking up a significant portion of the frame, potentially limiting analysis.
- Updated Approach: Legends are repositioned as an overlay at the top of the frame, utilizing a semi-transparent background to avoid obstructing the view.
Additional Recommendations:
-
Hardware Acceleration:
- Utilize GPU acceleration if available to speed up model inference and tracking.
-
Configuration Flexibility:
- Allow configuration of thresholds, colors, and other parameters via a configuration file or command-line arguments for easier adjustments without modifying the code.
-
Scalability:
- Implement multithreading or multiprocessing to handle detection, tracking, and visualization in parallel, enhancing real-time performance.
-
Data Storage:
- Consider storing more detailed logs or metrics in a database or structured files (like CSV) for advanced analytics beyond the HTML report.
-
Visualization Enhancements:
- Incorporate real-time graphs or charts overlaying the video stream to visualize trends dynamically.
Conclusion:
By integrating a more advanced tracking algorithm like Deep SORT and ensuring that the entire video frame is analyzed without unintended restrictions, your traffic monitoring system will become more robust and accurate. The updated code provided addresses these aspects and includes additional enhancements for better performance and visualization. Ensure that all required dependencies (like deep_sort_realtime) are installed and properly configured in your environment.
If you encounter any specific issues or need further customization, feel free to ask!