Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK : Problem Statement:
Develop a real-time object detection system using the YOLOv8 model to analyze traffic flow. The system should be able to categorize traffic into three levels:
Low Traffic
Medium Traffic
High Traffic
Requirements:
Real-Time Video Reading:
Capture and process live video feed from a camera or video stream.
Object Detection Using YOLOv8:
Use YOLOv8 to detect vehicles (cars, trucks, bikes, buses, etc.) in real-time.
Traffic Metrics Calculation:
Calculate the density of vehicles to classify traffic into three categories:
Low Traffic: Less than a certain threshold of vehicles per frame.
Medium Traffic: A moderate number of vehicles detected per frame.
High Traffic: A high number of vehicles detected in the frame.
Visualization Using Plotly:
Use the plotly module to visualize the traffic metrics.
Generate an HTML report that includes plots for traffic density over time.
Save the report in a separate folder.
Output:
Real-time object detection on the video stream.
HTML file in a specified folder with traffic visualization using plotly.
Additional Considerations:
Optimize for performance, ensuring real-time processing even on low-end hardware.
Properly manage the folder structure for storing output HTML files.
Handle different camera resolutions and frame rates.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a Python script that implements a real-time object detection system using the YOLOv8 model to analyze traffic flow. The script captures live video from a camera, performs object detection, calculates traffic density, categorizes it into low, medium, or high traffic, and visualizes the results using Plotly. The final HTML report is saved in a specified folder.
python
import os
import sys
from typing import List, Tuple
import cv2
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from ultralytics import YOLO
import numpy as np
import time
import threading
from datetime import datetime
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Constants for traffic levels
LOW_TRAFFIC_THRESHOLD = 5
MEDIUM_TRAFFIC_THRESHOLD = 15
def create_output_directory(directory_name: str) -> str:
"""
Creates an output directory if it doesn't exist.
"""
try:
os.makedirs(directory_name, exist_ok=True)
logging.info(f"Output directory created at: {directory_name}")
return directory_name
except Exception as e:
logging.error(f"Error creating directory {directory_name}: {e}")
sys.exit(1)
def get_traffic_level(vehicle_count: int) -> str:
"""
Determines the traffic level based on the vehicle count.
"""
if vehicle_count < LOW_TRAFFIC_THRESHOLD:
return 'Low Traffic'
elif LOW_TRAFFIC_THRESHOLD <= vehicle_count < MEDIUM_TRAFFIC_THRESHOLD:
return 'Medium Traffic'
else:
return 'High Traffic'
def process_frame(frame: np.ndarray, model: YOLO) -> Tuple[np.ndarray, int]:
"""
Processes a single frame: performs object detection and annotates the frame.
"""
results = model(frame, verbose=False)[0]
vehicle_count = 0
for result in results.boxes.data.tolist():
x1, y1, x2, y2, score, class_id = result
class_id = int(class_id)
if class_id in model.model.names and model.model.names[class_id] in ['car', 'truck', 'bus', 'motorbike', 'bicycle']:
vehicle_count += 1
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
cv2.putText(frame, model.model.names[class_id], (int(x1), int(y1) - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
return frame, vehicle_count
def generate_report(times: List[str], vehicle_counts: List[int], traffic_levels: List[str], output_dir: str) -> None:
"""
Generates an HTML report using Plotly.
"""
try:
fig = make_subplots(rows=2, cols=1, subplot_titles=("Vehicle Count Over Time", "Traffic Level Over Time"))
# Vehicle count line plot
fig.add_trace(go.Scatter(x=times, y=vehicle_counts, mode='lines+markers', name='Vehicle Count'), row=1, col=1)
# Traffic level bar plot
level_colors = {'Low Traffic': 'green', 'Medium Traffic': 'orange', 'High Traffic': 'red'}
colors = [level_colors[level] for level in traffic_levels]
fig.add_trace(go.Bar(x=times, y=vehicle_counts, marker_color=colors, name='Traffic Level'), row=2, col=1)
fig.update_layout(height=700, width=1000, title_text="Traffic Analysis Report")
report_path = os.path.join(output_dir, 'traffic_report.html')
fig.write_html(report_path)
logging.info(f"Report generated at: {report_path}")
except Exception as e:
logging.error(f"Error generating report: {e}")
def process_video_stream(video_source: int, output_dir: str) -> None:
"""
Captures video from the source, performs real-time object detection,
and collects data for the report.
"""
try:
cap = cv2.VideoCapture(video_source)
# Adjust camera resolution and frame rate if needed
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FPS, 30)
model = YOLO('yolov8n.pt') # Using the smallest YOLOv8 model for performance
times = []
vehicle_counts = []
traffic_levels = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
logging.warning("Failed to grab frame")
break
processed_frame, vehicle_count = process_frame(frame, model)
traffic_level = get_traffic_level(vehicle_count)
# Collect data
current_time = datetime.now().strftime('%H:%M:%S')
times.append(current_time)
vehicle_counts.append(vehicle_count)
traffic_levels.append(traffic_level)
# Display the frame with annotations
cv2.putText(processed_frame, f'Traffic Level: {traffic_level}', (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('Traffic Detection', processed_frame)
if cv2.waitKey(1) == 27: # ESC key to break
logging.info("ESC pressed. Exiting.")
break
# Limit the size of data for visualization
if len(times) > 1000:
times.pop(0)
vehicle_counts.pop(0)
traffic_levels.pop(0)
cap.release()
cv2.destroyAllWindows()
# Generate the report
generate_report(times, vehicle_counts, traffic_levels, output_dir)
except Exception as e:
logging.error(f"Error processing video stream: {e}")
sys.exit(1)
def main() -> None:
"""
Main function to run the traffic analysis system.
"""
output_dir = create_output_directory('traffic_reports')
video_source = 0 # Change this to your video source if needed
video_thread = threading.Thread(target=process_video_stream, args=(video_source, output_dir))
video_thread.start()
if __name__ == '__main__':
main()
Explanation:
Imports and Logging: The script starts by importing necessary modules and setting up basic logging for debugging and information purposes.
Constants: Thresholds for traffic levels are defined (LOW_TRAFFIC_THRESHOLD, MEDIUM_TRAFFIC_THRESHOLD).
create_output_directory: A function to create the output directory if it doesn't exist, handling any potential errors.
get_traffic_level: Determines the traffic level based on the number of vehicles detected in a frame.
process_frame: Processes each frame from the video stream:
Performs object detection using the YOLOv8 model.
Counts vehicles by checking if detected objects are among the vehicle classes.
Draws bounding boxes and labels on detected vehicles.
generate_report: Uses Plotly to create an HTML report:
Plots vehicle counts over time.
Visualizes traffic levels with color-coded bars.
Saves the report as an HTML file in the specified output directory.
process_video_stream: Captures the video stream and processes each frame in real-time:
Configures camera settings for resolution and frame rate.
Initializes the YOLOv8 model.
Processes frames in a loop until the user presses the ESC key.
Collects data for the report.
Handles exceptions and ensures resources are released properly.
main: Entry point of the script:
Creates the output directory.
Starts the video processing in a separate thread to keep the main thread responsive.
You can change the video_source to a file path or another video source as needed.
Requirements:
Python Libraries:
opencv-python: For video capture and image processing.
ultralytics: To use the YOLOv8 model.
plotly: For creating interactive visualizations.
numpy: For numerical operations.
logging: For logging information and errors.
YOLOv8 Model:
Install the ultralytics package which includes the YOLOv8 implementation.