Update app.py
Browse files
app.py
CHANGED
|
@@ -1,329 +1,328 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Vehicle Speed Estimation and Counting - Gradio Interface
|
| 3 |
-
=========================================================
|
| 4 |
-
|
| 5 |
-
A real-time vehicle detection, tracking, counting, and speed estimation system
|
| 6 |
-
using YOLO object detection and perspective transformation techniques.
|
| 7 |
-
|
| 8 |
-
Authors:
|
| 9 |
-
- Abhay Gupta (0205CC221005)
|
| 10 |
-
- Aditi Lakhera (0205CC221011)
|
| 11 |
-
- Balraj Patel (0205CC221049)
|
| 12 |
-
- Bhumika Patel (0205CC221050)
|
| 13 |
-
|
| 14 |
-
This application provides an interactive web interface for analyzing traffic videos
|
| 15 |
-
and estimating vehicle speeds using computer vision techniques.
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
import os
|
| 19 |
-
import sys
|
| 20 |
-
import tempfile
|
| 21 |
-
import logging
|
| 22 |
-
from pathlib import Path
|
| 23 |
-
from typing import Optional, Tuple
|
| 24 |
-
|
| 25 |
-
import gradio as gr
|
| 26 |
-
import cv2
|
| 27 |
-
import numpy as np
|
| 28 |
-
|
| 29 |
-
# Configure logging
|
| 30 |
-
logging.basicConfig(
|
| 31 |
-
level=logging.INFO,
|
| 32 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 33 |
-
)
|
| 34 |
-
logger = logging.getLogger(__name__)
|
| 35 |
-
|
| 36 |
-
# Import application modules
|
| 37 |
-
try:
|
| 38 |
-
from main import process_video
|
| 39 |
-
from config import VehicleDetectionConfig
|
| 40 |
-
except ImportError as e:
|
| 41 |
-
logger.error(f"Failed to import required modules: {e}")
|
| 42 |
-
raise
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def validate_video_file(video_path: str) -> Tuple[bool, str]:
|
| 46 |
-
"""
|
| 47 |
-
Validate uploaded video file.
|
| 48 |
-
|
| 49 |
-
Args:
|
| 50 |
-
video_path: Path to video file
|
| 51 |
-
|
| 52 |
-
Returns:
|
| 53 |
-
Tuple of (is_valid, error_message)
|
| 54 |
-
"""
|
| 55 |
-
if not video_path:
|
| 56 |
-
return False, "No video file provided"
|
| 57 |
-
|
| 58 |
-
if not os.path.exists(video_path):
|
| 59 |
-
return False, f"Video file not found: {video_path}"
|
| 60 |
-
|
| 61 |
-
# Check file size (limit to 100MB for HF Spaces)
|
| 62 |
-
file_size_mb = os.path.getsize(video_path) / (1024 * 1024)
|
| 63 |
-
if file_size_mb > 100:
|
| 64 |
-
return False, f"Video file too large ({file_size_mb:.1f}MB). Maximum size is 100MB"
|
| 65 |
-
|
| 66 |
-
# Validate video can be opened
|
| 67 |
-
try:
|
| 68 |
-
cap = cv2.VideoCapture(video_path)
|
| 69 |
-
if not cap.isOpened():
|
| 70 |
-
return False, "Unable to open video file. Please ensure it's a valid video format"
|
| 71 |
-
|
| 72 |
-
# Check if video has frames
|
| 73 |
-
ret, _ = cap.read()
|
| 74 |
-
cap.release()
|
| 75 |
-
|
| 76 |
-
if not ret:
|
| 77 |
-
return False, "Video file appears to be empty or corrupted"
|
| 78 |
-
|
| 79 |
-
return True, ""
|
| 80 |
-
except Exception as e:
|
| 81 |
-
return False, f"Error validating video: {str(e)}"
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def estimate_vehicle_speed(
|
| 85 |
-
video_file: str,
|
| 86 |
-
model_choice: str,
|
| 87 |
-
line_position: int,
|
| 88 |
-
confidence_threshold: float,
|
| 89 |
-
progress=gr.Progress()
|
| 90 |
-
) -> Tuple[Optional[str], str]:
|
| 91 |
-
"""
|
| 92 |
-
Process video and estimate vehicle speeds.
|
| 93 |
-
|
| 94 |
-
Args:
|
| 95 |
-
video_file: Path to uploaded video
|
| 96 |
-
model_choice: YOLO model selection
|
| 97 |
-
line_position: Y-coordinate for counting line
|
| 98 |
-
confidence_threshold: Detection confidence threshold
|
| 99 |
-
progress: Gradio progress tracker
|
| 100 |
-
|
| 101 |
-
Returns:
|
| 102 |
-
Tuple of (output_video_path, statistics_text)
|
| 103 |
-
"""
|
| 104 |
-
try:
|
| 105 |
-
# Validate input
|
| 106 |
-
progress(0, desc="Validating video file...")
|
| 107 |
-
is_valid, error_msg = validate_video_file(video_file)
|
| 108 |
-
if not is_valid:
|
| 109 |
-
logger.error(f"Video validation failed: {error_msg}")
|
| 110 |
-
return None, f"β Error: {error_msg}"
|
| 111 |
-
|
| 112 |
-
# Create temporary output file
|
| 113 |
-
output_path = tempfile.mktemp(suffix='.mp4')
|
| 114 |
-
|
| 115 |
-
# Configure processing
|
| 116 |
-
progress(0.1, desc="Configuring detection parameters...")
|
| 117 |
-
config = VehicleDetectionConfig(
|
| 118 |
-
input_video=video_file,
|
| 119 |
-
output_video=output_path,
|
| 120 |
-
model_name=model_choice,
|
| 121 |
-
line_y=line_position,
|
| 122 |
-
confidence_threshold=confidence_threshold
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
# Process video
|
| 126 |
-
progress(0.2, desc="Processing video (this may take a few minutes)...")
|
| 127 |
-
logger.info(f"Starting video processing: {video_file}")
|
| 128 |
-
|
| 129 |
-
try:
|
| 130 |
-
stats = process_video(
|
| 131 |
-
config=config,
|
| 132 |
-
progress_callback=lambda p: progress(0.2 + p * 0.7, desc=f"Processing... {int(p*100)}%")
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
progress(0.95, desc="Finalizing output...")
|
| 136 |
-
|
| 137 |
-
# Format statistics
|
| 138 |
-
stats_text = f"""
|
| 139 |
-
## π Processing Results
|
| 140 |
-
|
| 141 |
-
### Vehicle Count Statistics
|
| 142 |
-
- **Total Vehicles Detected:** {stats['total_count']}
|
| 143 |
-
- **Vehicles Entering (In):** {stats['in_count']}
|
| 144 |
-
- **Vehicles Exiting (Out):** {stats['out_count']}
|
| 145 |
-
|
| 146 |
-
### Speed Analysis
|
| 147 |
-
- **Average Speed:** {stats['avg_speed']:.1f} km/h
|
| 148 |
-
- **Maximum Speed:** {stats['max_speed']:.1f} km/h
|
| 149 |
-
- **Minimum Speed:** {stats['min_speed']:.1f} km/h
|
| 150 |
-
|
| 151 |
-
### Processing Information
|
| 152 |
-
- **Frames Processed:** {stats['frames_processed']}
|
| 153 |
-
- **Processing Time:** {stats['processing_time']:.2f} seconds
|
| 154 |
-
- **Model Used:** {model_choice}
|
| 155 |
-
- **Detection Confidence:** {confidence_threshold:.2f}
|
| 156 |
-
|
| 157 |
-
β
**Processing completed successfully!**
|
| 158 |
-
"""
|
| 159 |
-
|
| 160 |
-
progress(1.0, desc="Complete!")
|
| 161 |
-
logger.info("Video processing completed successfully")
|
| 162 |
-
return output_path, stats_text
|
| 163 |
-
|
| 164 |
-
except Exception as e:
|
| 165 |
-
logger.error(f"Error during video processing: {e}", exc_info=True)
|
| 166 |
-
return None, f"β **Processing Error:** {str(e)}\n\nPlease try with different settings or a different video."
|
| 167 |
-
|
| 168 |
-
except Exception as e:
|
| 169 |
-
logger.error(f"Unexpected error in estimate_vehicle_speed: {e}", exc_info=True)
|
| 170 |
-
return None, f"β **Unexpected Error:** {str(e)}"
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
def create_demo_interface() -> gr.Blocks:
|
| 174 |
-
"""
|
| 175 |
-
Create Gradio interface for vehicle speed estimation.
|
| 176 |
-
|
| 177 |
-
Returns:
|
| 178 |
-
Gradio Blocks interface
|
| 179 |
-
"""
|
| 180 |
-
with gr.Blocks(
|
| 181 |
-
title="Vehicle Speed Estimation & Counting"
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
- **
|
| 192 |
-
- **
|
| 193 |
-
- **
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
- **
|
| 198 |
-
- **
|
| 199 |
-
- **
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
"
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
-
|
| 255 |
-
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
],
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
- **
|
| 302 |
-
- **
|
| 303 |
-
- **
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
- [
|
| 308 |
-
- [
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
demo
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
sys.exit(1)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Vehicle Speed Estimation and Counting - Gradio Interface
|
| 3 |
+
=========================================================
|
| 4 |
+
|
| 5 |
+
A real-time vehicle detection, tracking, counting, and speed estimation system
|
| 6 |
+
using YOLO object detection and perspective transformation techniques.
|
| 7 |
+
|
| 8 |
+
Authors:
|
| 9 |
+
- Abhay Gupta (0205CC221005)
|
| 10 |
+
- Aditi Lakhera (0205CC221011)
|
| 11 |
+
- Balraj Patel (0205CC221049)
|
| 12 |
+
- Bhumika Patel (0205CC221050)
|
| 13 |
+
|
| 14 |
+
This application provides an interactive web interface for analyzing traffic videos
|
| 15 |
+
and estimating vehicle speeds using computer vision techniques.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import tempfile
|
| 21 |
+
import logging
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Optional, Tuple
|
| 24 |
+
|
| 25 |
+
import gradio as gr
|
| 26 |
+
import cv2
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
# Configure logging
|
| 30 |
+
logging.basicConfig(
|
| 31 |
+
level=logging.INFO,
|
| 32 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 33 |
+
)
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
# Import application modules
|
| 37 |
+
try:
|
| 38 |
+
from main import process_video
|
| 39 |
+
from config import VehicleDetectionConfig
|
| 40 |
+
except ImportError as e:
|
| 41 |
+
logger.error(f"Failed to import required modules: {e}")
|
| 42 |
+
raise
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def validate_video_file(video_path: str) -> Tuple[bool, str]:
|
| 46 |
+
"""
|
| 47 |
+
Validate uploaded video file.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
video_path: Path to video file
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
Tuple of (is_valid, error_message)
|
| 54 |
+
"""
|
| 55 |
+
if not video_path:
|
| 56 |
+
return False, "No video file provided"
|
| 57 |
+
|
| 58 |
+
if not os.path.exists(video_path):
|
| 59 |
+
return False, f"Video file not found: {video_path}"
|
| 60 |
+
|
| 61 |
+
# Check file size (limit to 100MB for HF Spaces)
|
| 62 |
+
file_size_mb = os.path.getsize(video_path) / (1024 * 1024)
|
| 63 |
+
if file_size_mb > 100:
|
| 64 |
+
return False, f"Video file too large ({file_size_mb:.1f}MB). Maximum size is 100MB"
|
| 65 |
+
|
| 66 |
+
# Validate video can be opened
|
| 67 |
+
try:
|
| 68 |
+
cap = cv2.VideoCapture(video_path)
|
| 69 |
+
if not cap.isOpened():
|
| 70 |
+
return False, "Unable to open video file. Please ensure it's a valid video format"
|
| 71 |
+
|
| 72 |
+
# Check if video has frames
|
| 73 |
+
ret, _ = cap.read()
|
| 74 |
+
cap.release()
|
| 75 |
+
|
| 76 |
+
if not ret:
|
| 77 |
+
return False, "Video file appears to be empty or corrupted"
|
| 78 |
+
|
| 79 |
+
return True, ""
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return False, f"Error validating video: {str(e)}"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def estimate_vehicle_speed(
|
| 85 |
+
video_file: str,
|
| 86 |
+
model_choice: str,
|
| 87 |
+
line_position: int,
|
| 88 |
+
confidence_threshold: float,
|
| 89 |
+
progress=gr.Progress()
|
| 90 |
+
) -> Tuple[Optional[str], str]:
|
| 91 |
+
"""
|
| 92 |
+
Process video and estimate vehicle speeds.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
video_file: Path to uploaded video
|
| 96 |
+
model_choice: YOLO model selection
|
| 97 |
+
line_position: Y-coordinate for counting line
|
| 98 |
+
confidence_threshold: Detection confidence threshold
|
| 99 |
+
progress: Gradio progress tracker
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
Tuple of (output_video_path, statistics_text)
|
| 103 |
+
"""
|
| 104 |
+
try:
|
| 105 |
+
# Validate input
|
| 106 |
+
progress(0, desc="Validating video file...")
|
| 107 |
+
is_valid, error_msg = validate_video_file(video_file)
|
| 108 |
+
if not is_valid:
|
| 109 |
+
logger.error(f"Video validation failed: {error_msg}")
|
| 110 |
+
return None, f"β Error: {error_msg}"
|
| 111 |
+
|
| 112 |
+
# Create temporary output file
|
| 113 |
+
output_path = tempfile.mktemp(suffix='.mp4')
|
| 114 |
+
|
| 115 |
+
# Configure processing
|
| 116 |
+
progress(0.1, desc="Configuring detection parameters...")
|
| 117 |
+
config = VehicleDetectionConfig(
|
| 118 |
+
input_video=video_file,
|
| 119 |
+
output_video=output_path,
|
| 120 |
+
model_name=model_choice,
|
| 121 |
+
line_y=line_position,
|
| 122 |
+
confidence_threshold=confidence_threshold
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Process video
|
| 126 |
+
progress(0.2, desc="Processing video (this may take a few minutes)...")
|
| 127 |
+
logger.info(f"Starting video processing: {video_file}")
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
stats = process_video(
|
| 131 |
+
config=config,
|
| 132 |
+
progress_callback=lambda p: progress(0.2 + p * 0.7, desc=f"Processing... {int(p*100)}%")
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
progress(0.95, desc="Finalizing output...")
|
| 136 |
+
|
| 137 |
+
# Format statistics
|
| 138 |
+
stats_text = f"""
|
| 139 |
+
## π Processing Results
|
| 140 |
+
|
| 141 |
+
### Vehicle Count Statistics
|
| 142 |
+
- **Total Vehicles Detected:** {stats['total_count']}
|
| 143 |
+
- **Vehicles Entering (In):** {stats['in_count']}
|
| 144 |
+
- **Vehicles Exiting (Out):** {stats['out_count']}
|
| 145 |
+
|
| 146 |
+
### Speed Analysis
|
| 147 |
+
- **Average Speed:** {stats['avg_speed']:.1f} km/h
|
| 148 |
+
- **Maximum Speed:** {stats['max_speed']:.1f} km/h
|
| 149 |
+
- **Minimum Speed:** {stats['min_speed']:.1f} km/h
|
| 150 |
+
|
| 151 |
+
### Processing Information
|
| 152 |
+
- **Frames Processed:** {stats['frames_processed']}
|
| 153 |
+
- **Processing Time:** {stats['processing_time']:.2f} seconds
|
| 154 |
+
- **Model Used:** {model_choice}
|
| 155 |
+
- **Detection Confidence:** {confidence_threshold:.2f}
|
| 156 |
+
|
| 157 |
+
β
**Processing completed successfully!**
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
progress(1.0, desc="Complete!")
|
| 161 |
+
logger.info("Video processing completed successfully")
|
| 162 |
+
return output_path, stats_text
|
| 163 |
+
|
| 164 |
+
except Exception as e:
|
| 165 |
+
logger.error(f"Error during video processing: {e}", exc_info=True)
|
| 166 |
+
return None, f"β **Processing Error:** {str(e)}\n\nPlease try with different settings or a different video."
|
| 167 |
+
|
| 168 |
+
except Exception as e:
|
| 169 |
+
logger.error(f"Unexpected error in estimate_vehicle_speed: {e}", exc_info=True)
|
| 170 |
+
return None, f"β **Unexpected Error:** {str(e)}"
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def create_demo_interface() -> gr.Blocks:
|
| 174 |
+
"""
|
| 175 |
+
Create Gradio interface for vehicle speed estimation.
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
Gradio Blocks interface
|
| 179 |
+
"""
|
| 180 |
+
with gr.Blocks(
|
| 181 |
+
title="Vehicle Speed Estimation & Counting"
|
| 182 |
+
) as demo:
|
| 183 |
+
|
| 184 |
+
gr.Markdown("""
|
| 185 |
+
# π Vehicle Speed Estimation & Counting System
|
| 186 |
+
|
| 187 |
+
An intelligent traffic analysis system that detects, tracks, counts, and estimates the speed of vehicles in video footage using advanced computer vision techniques.
|
| 188 |
+
|
| 189 |
+
### π― Features
|
| 190 |
+
- **Real-time Vehicle Detection** using YOLO
|
| 191 |
+
- **Multi-Object Tracking** with ByteTrack
|
| 192 |
+
- **Accurate Speed Estimation** via perspective transformation
|
| 193 |
+
- **Vehicle Counting** with configurable detection zones
|
| 194 |
+
|
| 195 |
+
### π₯ Developed By
|
| 196 |
+
- **Abhay Gupta** (0205CC221005)
|
| 197 |
+
- **Aditi Lakhera** (0205CC221011)
|
| 198 |
+
- **Balraj Patel** (0205CC221049)
|
| 199 |
+
- **Bhumika Patel** (0205CC221050)
|
| 200 |
+
|
| 201 |
+
---
|
| 202 |
+
""")
|
| 203 |
+
|
| 204 |
+
with gr.Row():
|
| 205 |
+
with gr.Column(scale=1):
|
| 206 |
+
gr.Markdown("### π€ Input Configuration")
|
| 207 |
+
|
| 208 |
+
video_input = gr.Video(
|
| 209 |
+
label="Upload Traffic Video",
|
| 210 |
+
format="mp4"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
with gr.Accordion("βοΈ Advanced Settings", open=False):
|
| 214 |
+
model_choice = gr.Dropdown(
|
| 215 |
+
choices=["yolov8n", "yolov8s", "yolov8m", "yolov8l"],
|
| 216 |
+
value="yolov8n",
|
| 217 |
+
label="YOLO Model",
|
| 218 |
+
info="Larger models are more accurate but slower"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
line_position = gr.Slider(
|
| 222 |
+
minimum=100,
|
| 223 |
+
maximum=1000,
|
| 224 |
+
value=480,
|
| 225 |
+
step=10,
|
| 226 |
+
label="Counting Line Position (Y-coordinate)",
|
| 227 |
+
info="Vertical position of the vehicle counting line"
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
confidence_threshold = gr.Slider(
|
| 231 |
+
minimum=0.1,
|
| 232 |
+
maximum=0.9,
|
| 233 |
+
value=0.3,
|
| 234 |
+
step=0.05,
|
| 235 |
+
label="Detection Confidence Threshold",
|
| 236 |
+
info="Higher values reduce false positives"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
process_btn = gr.Button(
|
| 240 |
+
"π Process Video",
|
| 241 |
+
variant="primary",
|
| 242 |
+
size="lg"
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
gr.Markdown("""
|
| 246 |
+
### π Instructions
|
| 247 |
+
1. Upload a traffic video (MP4 format, max 100MB)
|
| 248 |
+
2. Adjust settings if needed (optional)
|
| 249 |
+
3. Click "Process Video" and wait for results
|
| 250 |
+
4. Download the annotated video with speed estimates
|
| 251 |
+
|
| 252 |
+
### π‘ Tips
|
| 253 |
+
- Use videos with clear vehicle visibility
|
| 254 |
+
- Ensure consistent camera angle
|
| 255 |
+
- Better lighting improves detection accuracy
|
| 256 |
+
""")
|
| 257 |
+
|
| 258 |
+
with gr.Column(scale=1):
|
| 259 |
+
gr.Markdown("### π₯ Output Results")
|
| 260 |
+
|
| 261 |
+
video_output = gr.Video(
|
| 262 |
+
label="Processed Video with Annotations"
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
stats_output = gr.Markdown(
|
| 266 |
+
label="Statistics",
|
| 267 |
+
value="*Processing results will appear here...*"
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Example videos section
|
| 271 |
+
gr.Markdown("""
|
| 272 |
+
---
|
| 273 |
+
### π¬ Example Videos
|
| 274 |
+
Upload your own traffic video or use sample footage to test the system.
|
| 275 |
+
""")
|
| 276 |
+
|
| 277 |
+
gr.Examples(
|
| 278 |
+
examples=[
|
| 279 |
+
["./data/vehicles.mp4", "yolov8n", 480, 0.3],
|
| 280 |
+
],
|
| 281 |
+
inputs=[video_input, model_choice, line_position, confidence_threshold],
|
| 282 |
+
outputs=[video_output, stats_output],
|
| 283 |
+
fn=estimate_vehicle_speed,
|
| 284 |
+
cache_examples=False,
|
| 285 |
+
label="Sample Videos"
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# Connect processing function
|
| 289 |
+
process_btn.click(
|
| 290 |
+
fn=estimate_vehicle_speed,
|
| 291 |
+
inputs=[video_input, model_choice, line_position, confidence_threshold],
|
| 292 |
+
outputs=[video_output, stats_output]
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
gr.Markdown("""
|
| 296 |
+
---
|
| 297 |
+
### π¬ Technical Details
|
| 298 |
+
|
| 299 |
+
This system uses:
|
| 300 |
+
- **YOLO (You Only Look Once)** for real-time object detection
|
| 301 |
+
- **ByteTrack** for multi-object tracking across frames
|
| 302 |
+
- **Perspective Transformation** for accurate speed calculation
|
| 303 |
+
- **OpenCV** for video processing and computer vision operations
|
| 304 |
+
|
| 305 |
+
### π References
|
| 306 |
+
- [Ultralytics YOLO](https://github.com/ultralytics/ultralytics)
|
| 307 |
+
- [Supervision Library](https://github.com/roboflow/supervision)
|
| 308 |
+
- [OpenCV](https://opencv.org/)
|
| 309 |
+
|
| 310 |
+
### π License
|
| 311 |
+
MIT License - See LICENSE file for details
|
| 312 |
+
""")
|
| 313 |
+
|
| 314 |
+
return demo
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
if __name__ == "__main__":
|
| 318 |
+
try:
|
| 319 |
+
logger.info("Starting Vehicle Speed Estimation application...")
|
| 320 |
+
demo = create_demo_interface()
|
| 321 |
+
demo.launch(
|
| 322 |
+
server_name="0.0.0.0",
|
| 323 |
+
server_port=7860,
|
| 324 |
+
share=False
|
| 325 |
+
)
|
| 326 |
+
except Exception as e:
|
| 327 |
+
logger.error(f"Failed to launch application: {e}", exc_info=True)
|
| 328 |
+
sys.exit(1)
|
|
|