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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Real-time Object Detection with YOLO - Streamlit Application
|
| 3 |
+
Main application file for the web interface.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
import streamlit as st
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
import time
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import sys
|
| 12 |
+
import os
|
| 13 |
|
| 14 |
+
# Add src directory to path
|
| 15 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
|
| 16 |
|
| 17 |
+
from detection.yolo_detector import YOLODetector
|
| 18 |
+
from detection.webcam_capture import WebcamCapture, get_available_cameras
|
| 19 |
+
from utils.config import app_config
|
| 20 |
+
from utils.helpers import format_detection_info, log_detection_summary
|
| 21 |
|
| 22 |
+
# Page configuration
|
| 23 |
+
st.set_page_config(
|
| 24 |
+
page_title=app_config.ui.page_title,
|
| 25 |
+
page_icon="๐ฏ",
|
| 26 |
+
layout="wide",
|
| 27 |
+
initial_sidebar_state="expanded"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# Initialize session state
|
| 31 |
+
if 'detector' not in st.session_state:
|
| 32 |
+
st.session_state.detector = None
|
| 33 |
+
if 'webcam' not in st.session_state:
|
| 34 |
+
st.session_state.webcam = None
|
| 35 |
+
if 'is_running' not in st.session_state:
|
| 36 |
+
st.session_state.is_running = False
|
| 37 |
+
if 'frame_count' not in st.session_state:
|
| 38 |
+
st.session_state.frame_count = 0
|
| 39 |
+
if 'detection_stats' not in st.session_state:
|
| 40 |
+
st.session_state.detection_stats = {}
|
| 41 |
+
|
| 42 |
+
def initialize_detector(model_name: str, confidence_threshold: float):
|
| 43 |
+
"""Initialize the YOLO detector."""
|
| 44 |
+
try:
|
| 45 |
+
with st.spinner(f"Loading {model_name} model..."):
|
| 46 |
+
detector = YOLODetector(model_name, confidence_threshold)
|
| 47 |
+
if detector.model is not None:
|
| 48 |
+
st.session_state.detector = detector
|
| 49 |
+
st.success(f"โ
Model {model_name} loaded successfully!")
|
| 50 |
+
return True
|
| 51 |
+
else:
|
| 52 |
+
st.error(f"โ Failed to load model {model_name}")
|
| 53 |
+
return False
|
| 54 |
+
except Exception as e:
|
| 55 |
+
st.error(f"โ Error loading model: {str(e)}")
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
def initialize_webcam(camera_index: int):
|
| 59 |
+
"""Initialize the webcam."""
|
| 60 |
+
try:
|
| 61 |
+
webcam = WebcamCapture(
|
| 62 |
+
camera_index=camera_index,
|
| 63 |
+
width=app_config.camera.frame_width,
|
| 64 |
+
height=app_config.camera.frame_height
|
| 65 |
+
)
|
| 66 |
+
if webcam.start_capture():
|
| 67 |
+
st.session_state.webcam = webcam
|
| 68 |
+
st.success(f"โ
Camera {camera_index} initialized successfully!")
|
| 69 |
+
return True
|
| 70 |
+
else:
|
| 71 |
+
st.error(f"โ Failed to initialize camera {camera_index}")
|
| 72 |
+
return False
|
| 73 |
+
except Exception as e:
|
| 74 |
+
st.error(f"โ Error initializing camera: {str(e)}")
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
def main():
|
| 78 |
+
"""Main application function."""
|
| 79 |
+
|
| 80 |
+
# Title and description
|
| 81 |
+
st.title("๐ฏ Real-time Object Detection with YOLO")
|
| 82 |
+
st.markdown("Detect objects in real-time using your webcam and YOLO models.")
|
| 83 |
+
|
| 84 |
+
# Sidebar for controls
|
| 85 |
+
with st.sidebar:
|
| 86 |
+
st.header("โ๏ธ Settings")
|
| 87 |
+
|
| 88 |
+
# Model selection
|
| 89 |
+
st.subheader("๐ค Model Configuration")
|
| 90 |
+
selected_model = st.selectbox(
|
| 91 |
+
"Select YOLO Model",
|
| 92 |
+
app_config.available_models,
|
| 93 |
+
index=app_config.available_models.index(app_config.detection.model_name),
|
| 94 |
+
help="Choose the YOLO model variant. Nano is fastest, X is most accurate."
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# Show model description
|
| 98 |
+
model_info = app_config.get_model_info(selected_model)
|
| 99 |
+
st.info(model_info['description'])
|
| 100 |
+
|
| 101 |
+
# Confidence threshold
|
| 102 |
+
confidence_threshold = st.slider(
|
| 103 |
+
"Confidence Threshold",
|
| 104 |
+
min_value=0.1,
|
| 105 |
+
max_value=1.0,
|
| 106 |
+
value=app_config.detection.confidence_threshold,
|
| 107 |
+
step=0.05,
|
| 108 |
+
help="Minimum confidence score for detections"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Camera selection
|
| 112 |
+
st.subheader("๐น Camera Configuration")
|
| 113 |
+
available_cameras = get_available_cameras()
|
| 114 |
+
|
| 115 |
+
if available_cameras:
|
| 116 |
+
camera_index = st.selectbox(
|
| 117 |
+
"Select Camera",
|
| 118 |
+
available_cameras,
|
| 119 |
+
index=0,
|
| 120 |
+
help="Choose the camera to use for detection"
|
| 121 |
+
)
|
| 122 |
+
else:
|
| 123 |
+
st.error("โ No cameras detected!")
|
| 124 |
+
camera_index = 0
|
| 125 |
+
|
| 126 |
+
# Performance settings
|
| 127 |
+
st.subheader("โก Performance")
|
| 128 |
+
detection_interval = st.slider(
|
| 129 |
+
"Detection Interval",
|
| 130 |
+
min_value=1,
|
| 131 |
+
max_value=10,
|
| 132 |
+
value=app_config.performance.detection_interval,
|
| 133 |
+
help="Process every N frames (higher = faster but less frequent detection)"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
# Display settings
|
| 137 |
+
st.subheader("๐จ Display Options")
|
| 138 |
+
show_fps = st.checkbox("Show FPS", value=app_config.ui.show_fps)
|
| 139 |
+
show_stats = st.checkbox("Show Statistics", value=app_config.ui.show_stats)
|
| 140 |
+
show_confidence = st.checkbox("Show Confidence Scores", value=app_config.ui.show_confidence)
|
| 141 |
+
|
| 142 |
+
# Control buttons
|
| 143 |
+
st.subheader("๐ฎ Controls")
|
| 144 |
+
|
| 145 |
+
col1, col2 = st.columns(2)
|
| 146 |
+
|
| 147 |
+
with col1:
|
| 148 |
+
if st.button("๐ Start Detection", disabled=st.session_state.is_running):
|
| 149 |
+
# Initialize detector if needed
|
| 150 |
+
if (st.session_state.detector is None or
|
| 151 |
+
st.session_state.detector.model_name != selected_model or
|
| 152 |
+
st.session_state.detector.confidence_threshold != confidence_threshold):
|
| 153 |
+
|
| 154 |
+
if initialize_detector(selected_model, confidence_threshold):
|
| 155 |
+
st.session_state.detector.update_confidence_threshold(confidence_threshold)
|
| 156 |
+
else:
|
| 157 |
+
st.stop()
|
| 158 |
+
|
| 159 |
+
# Initialize webcam if needed
|
| 160 |
+
if (st.session_state.webcam is None or
|
| 161 |
+
not st.session_state.webcam.is_camera_available()):
|
| 162 |
+
|
| 163 |
+
if not initialize_webcam(camera_index):
|
| 164 |
+
st.stop()
|
| 165 |
+
|
| 166 |
+
st.session_state.is_running = True
|
| 167 |
+
st.session_state.frame_count = 0
|
| 168 |
+
st.rerun()
|
| 169 |
+
|
| 170 |
+
with col2:
|
| 171 |
+
if st.button("โน๏ธ Stop Detection", disabled=not st.session_state.is_running):
|
| 172 |
+
st.session_state.is_running = False
|
| 173 |
+
if st.session_state.webcam:
|
| 174 |
+
st.session_state.webcam.stop_capture()
|
| 175 |
+
st.session_state.webcam = None
|
| 176 |
+
st.rerun()
|
| 177 |
+
|
| 178 |
+
# Main content area
|
| 179 |
+
if st.session_state.is_running and st.session_state.webcam and st.session_state.detector:
|
| 180 |
+
# Create columns for video and stats
|
| 181 |
+
col1, col2 = st.columns([3, 1])
|
| 182 |
+
|
| 183 |
+
with col1:
|
| 184 |
+
st.subheader("๐น Live Video Feed")
|
| 185 |
+
video_placeholder = st.empty()
|
| 186 |
+
|
| 187 |
+
with col2:
|
| 188 |
+
if show_stats:
|
| 189 |
+
st.subheader("๐ Statistics")
|
| 190 |
+
stats_placeholder = st.empty()
|
| 191 |
+
|
| 192 |
+
# Performance metrics placeholders
|
| 193 |
+
if show_fps:
|
| 194 |
+
fps_placeholder = st.empty()
|
| 195 |
+
|
| 196 |
+
# Detection loop
|
| 197 |
+
while st.session_state.is_running:
|
| 198 |
+
frame = st.session_state.webcam.get_frame()
|
| 199 |
+
|
| 200 |
+
if frame is not None:
|
| 201 |
+
st.session_state.frame_count += 1
|
| 202 |
+
|
| 203 |
+
# Process frame for detection
|
| 204 |
+
if st.session_state.frame_count % detection_interval == 0:
|
| 205 |
+
detections = st.session_state.detector.detect_objects(frame)
|
| 206 |
+
annotated_frame = st.session_state.detector.draw_detections(frame, detections)
|
| 207 |
+
|
| 208 |
+
# Update detection stats
|
| 209 |
+
st.session_state.detection_stats = st.session_state.detector.get_detection_stats(detections)
|
| 210 |
+
else:
|
| 211 |
+
annotated_frame = frame
|
| 212 |
+
detections = []
|
| 213 |
+
|
| 214 |
+
# Convert BGR to RGB for display
|
| 215 |
+
display_frame = cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)
|
| 216 |
+
|
| 217 |
+
# Display video
|
| 218 |
+
with video_placeholder.container():
|
| 219 |
+
st.image(display_frame, channels="RGB", use_column_width=True)
|
| 220 |
+
|
| 221 |
+
# Display FPS
|
| 222 |
+
if show_fps:
|
| 223 |
+
current_fps = st.session_state.webcam.get_fps()
|
| 224 |
+
fps_placeholder.metric("๐ฏ FPS", f"{current_fps:.1f}")
|
| 225 |
+
|
| 226 |
+
# Display statistics
|
| 227 |
+
if show_stats and st.session_state.detection_stats:
|
| 228 |
+
with stats_placeholder.container():
|
| 229 |
+
stats = st.session_state.detection_stats
|
| 230 |
+
|
| 231 |
+
st.metric("๐ฏ Objects Detected", stats['total_objects'])
|
| 232 |
+
|
| 233 |
+
if stats['total_objects'] > 0:
|
| 234 |
+
st.metric("๐ Avg Confidence", f"{stats['avg_confidence']:.2f}")
|
| 235 |
+
st.metric("๐ Max Confidence", f"{stats['max_confidence']:.2f}")
|
| 236 |
+
|
| 237 |
+
# Class breakdown
|
| 238 |
+
st.write("**Object Classes:**")
|
| 239 |
+
for class_name, count in stats['class_counts'].items():
|
| 240 |
+
st.write(f"โข {class_name}: {count}")
|
| 241 |
+
|
| 242 |
+
# Small delay to prevent overwhelming the interface
|
| 243 |
+
time.sleep(0.01)
|
| 244 |
+
|
| 245 |
+
else:
|
| 246 |
+
st.warning("โ ๏ธ No frame received from camera")
|
| 247 |
+
time.sleep(0.1)
|
| 248 |
+
|
| 249 |
+
else:
|
| 250 |
+
# Show instructions when not running
|
| 251 |
+
st.info("๐ Configure your settings in the sidebar and click 'Start Detection' to begin!")
|
| 252 |
+
|
| 253 |
+
# Show system information
|
| 254 |
+
st.subheader("โน๏ธ System Information")
|
| 255 |
+
|
| 256 |
+
col1, col2, col3 = st.columns(3)
|
| 257 |
+
|
| 258 |
+
with col1:
|
| 259 |
+
st.write("**Available Cameras:**")
|
| 260 |
+
cameras = get_available_cameras()
|
| 261 |
+
if cameras:
|
| 262 |
+
for cam in cameras:
|
| 263 |
+
st.write(f"โข Camera {cam}")
|
| 264 |
+
else:
|
| 265 |
+
st.write("โข No cameras detected")
|
| 266 |
+
|
| 267 |
+
with col2:
|
| 268 |
+
st.write("**Available Models:**")
|
| 269 |
+
for model in app_config.available_models:
|
| 270 |
+
st.write(f"โข {model}")
|
| 271 |
+
|
| 272 |
+
with col3:
|
| 273 |
+
st.write("**Current Configuration:**")
|
| 274 |
+
st.write(f"โข Model: {app_config.detection.model_name}")
|
| 275 |
+
st.write(f"โข Confidence: {app_config.detection.confidence_threshold}")
|
| 276 |
+
st.write(f"โข Camera: {app_config.camera.camera_index}")
|
| 277 |
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|