Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -25,6 +25,19 @@ def draw_text_with_background(image, text, position, font=cv2.FONT_HERSHEY_SIMPL
|
|
| 25 |
cv2.rectangle(image, top_left, bottom_right, bg_color, -1)
|
| 26 |
cv2.putText(image, text, (x + padding, y), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
# --- CLASSE YOLO OPTIMISÉE ---
|
| 29 |
class YOLOVideoProcessor:
|
| 30 |
def __init__(self, model_path, poly1, poly2, tracker_method="bot"):
|
|
@@ -228,19 +241,35 @@ class YOLOVideoProcessor:
|
|
| 228 |
|
| 229 |
def process_webcam(self, camera_id=0, display_placeholder=None, count_placeholders=None):
|
| 230 |
"""Traite la vidéo en temps réel depuis une webcam avec multi-threading"""
|
| 231 |
-
#
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
try:
|
| 234 |
-
|
| 235 |
-
cap = cv2.VideoCapture(camera_id, backend_pref)
|
| 236 |
if cap.isOpened():
|
|
|
|
|
|
|
| 237 |
break
|
| 238 |
-
except:
|
|
|
|
|
|
|
| 239 |
continue
|
| 240 |
|
| 241 |
-
# Si aucun backend n'a fonctionné, essayer une dernière fois
|
| 242 |
-
if not cap.isOpened():
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
# Vérifier si la caméra est ouverte
|
| 246 |
if not cap.isOpened():
|
|
@@ -414,12 +443,12 @@ def main():
|
|
| 414 |
downsample = st.slider("Facteur d'échelle (plus petit = plus rapide)", 0.3, 1.0, 0.5, 0.1)
|
| 415 |
conf_threshold = st.slider("Seuil de confiance", 0.1, 0.9, 0.35, 0.05)
|
| 416 |
|
| 417 |
-
#
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
|
| 424 |
def parse_polygon(input_text):
|
| 425 |
try:
|
|
@@ -498,14 +527,31 @@ def main():
|
|
| 498 |
with tab2:
|
| 499 |
st.header("Détection en Temps Réel avec Webcam")
|
| 500 |
|
| 501 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
camera_options = {"Webcam par défaut (0)": 0}
|
| 503 |
-
|
| 504 |
-
|
|
|
|
| 505 |
camera_options[f"Caméra alternative ({i})"] = i
|
| 506 |
-
|
|
|
|
|
|
|
|
|
|
| 507 |
selected_camera = st.selectbox("Sélectionnez la source vidéo", list(camera_options.keys()))
|
| 508 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
|
| 510 |
# Paramètres d'affichage
|
| 511 |
display_quality = st.select_slider(
|
|
@@ -534,40 +580,33 @@ def main():
|
|
| 534 |
elif st.session_state.webcam_active:
|
| 535 |
st.warning("⚠️ La webcam est déjà active !")
|
| 536 |
else:
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
processing_thread.
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
try:
|
| 565 |
-
processing_thread.start()
|
| 566 |
-
st.session_state.processing_thread = processing_thread
|
| 567 |
-
st.success("✅ Webcam démarrée avec succès!")
|
| 568 |
-
except Exception as e:
|
| 569 |
-
st.error(f"Erreur au démarrage du thread: {e}")
|
| 570 |
-
st.session_state.webcam_active = False
|
| 571 |
|
| 572 |
if col_stop.button("⏹️ Arrêter la détection"):
|
| 573 |
if st.session_state.webcam_active and st.session_state.processor:
|
|
|
|
| 25 |
cv2.rectangle(image, top_left, bottom_right, bg_color, -1)
|
| 26 |
cv2.putText(image, text, (x + padding, y), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
|
| 27 |
|
| 28 |
+
def check_camera_availability():
|
| 29 |
+
"""Fonction de diagnostic pour vérifier les caméras disponibles"""
|
| 30 |
+
available_cameras = []
|
| 31 |
+
for i in range(10): # Vérifier les 10 premiers indices de caméra
|
| 32 |
+
cap = cv2.VideoCapture(i)
|
| 33 |
+
if cap.isOpened():
|
| 34 |
+
ret, frame = cap.read()
|
| 35 |
+
if ret:
|
| 36 |
+
available_cameras.append(i)
|
| 37 |
+
cap.release()
|
| 38 |
+
|
| 39 |
+
return available_cameras
|
| 40 |
+
|
| 41 |
# --- CLASSE YOLO OPTIMISÉE ---
|
| 42 |
class YOLOVideoProcessor:
|
| 43 |
def __init__(self, model_path, poly1, poly2, tracker_method="bot"):
|
|
|
|
| 241 |
|
| 242 |
def process_webcam(self, camera_id=0, display_placeholder=None, count_placeholders=None):
|
| 243 |
"""Traite la vidéo en temps réel depuis une webcam avec multi-threading"""
|
| 244 |
+
# Essayer différentes méthodes d'initialisation de la webcam
|
| 245 |
+
cap = None
|
| 246 |
+
backends_to_try = [
|
| 247 |
+
cv2.CAP_ANY, # Essayer le backend par défaut d'abord
|
| 248 |
+
cv2.CAP_DSHOW, # DirectShow (Windows)
|
| 249 |
+
cv2.CAP_MSMF, # Media Foundation (Windows)
|
| 250 |
+
cv2.CAP_V4L2, # Video4Linux (Linux)
|
| 251 |
+
cv2.CAP_AVFOUNDATION # AVFoundation (macOS)
|
| 252 |
+
]
|
| 253 |
+
|
| 254 |
+
for backend in backends_to_try:
|
| 255 |
try:
|
| 256 |
+
cap = cv2.VideoCapture(camera_id, backend)
|
|
|
|
| 257 |
if cap.isOpened():
|
| 258 |
+
if display_placeholder:
|
| 259 |
+
display_placeholder.success(f"✅ Webcam connectée avec succès (backend: {backend})")
|
| 260 |
break
|
| 261 |
+
except Exception as e:
|
| 262 |
+
if display_placeholder:
|
| 263 |
+
display_placeholder.warning(f"Échec avec backend {backend}: {e}")
|
| 264 |
continue
|
| 265 |
|
| 266 |
+
# Si aucun backend n'a fonctionné, essayer une dernière fois sans spécifier de backend
|
| 267 |
+
if cap is None or not cap.isOpened():
|
| 268 |
+
try:
|
| 269 |
+
cap = cv2.VideoCapture(camera_id)
|
| 270 |
+
except Exception as e:
|
| 271 |
+
if display_placeholder:
|
| 272 |
+
display_placeholder.error(f"Erreur finale: {e}")
|
| 273 |
|
| 274 |
# Vérifier si la caméra est ouverte
|
| 275 |
if not cap.isOpened():
|
|
|
|
| 443 |
downsample = st.slider("Facteur d'échelle (plus petit = plus rapide)", 0.3, 1.0, 0.5, 0.1)
|
| 444 |
conf_threshold = st.slider("Seuil de confiance", 0.1, 0.9, 0.35, 0.05)
|
| 445 |
|
| 446 |
+
# Informations système
|
| 447 |
+
st.subheader("💻 Informations système")
|
| 448 |
+
device_info = f"GPU: {'Disponible' if torch.cuda.is_available() else 'Non disponible'}"
|
| 449 |
+
if torch.cuda.is_available():
|
| 450 |
+
device_info += f" ({torch.cuda.get_device_name(0)})"
|
| 451 |
+
st.info(device_info)
|
| 452 |
|
| 453 |
def parse_polygon(input_text):
|
| 454 |
try:
|
|
|
|
| 527 |
with tab2:
|
| 528 |
st.header("Détection en Temps Réel avec Webcam")
|
| 529 |
|
| 530 |
+
# Vérifier les caméras disponibles
|
| 531 |
+
available_cameras = check_camera_availability()
|
| 532 |
+
if not available_cameras:
|
| 533 |
+
st.warning("⚠️ Aucune caméra détectée automatiquement sur votre système. Vous pouvez toujours essayer les options ci-dessous.")
|
| 534 |
+
else:
|
| 535 |
+
st.success(f"✅ Caméras détectées aux indices: {available_cameras}")
|
| 536 |
+
|
| 537 |
+
# Méthode améliorée de sélection de caméra
|
| 538 |
camera_options = {"Webcam par défaut (0)": 0}
|
| 539 |
+
|
| 540 |
+
# Ajouter plus d'options pour les caméras alternatives
|
| 541 |
+
for i in range(1, 8): # Essayer jusqu'à 8 caméras différentes
|
| 542 |
camera_options[f"Caméra alternative ({i})"] = i
|
| 543 |
+
|
| 544 |
+
# Ajouter aussi des options pour les caméras virtuelles ou IP
|
| 545 |
+
camera_options["Caméra IP (entrez l'URL)"] = "ip"
|
| 546 |
+
|
| 547 |
selected_camera = st.selectbox("Sélectionnez la source vidéo", list(camera_options.keys()))
|
| 548 |
+
|
| 549 |
+
# Permettre d'entrer une URL de caméra IP
|
| 550 |
+
if camera_options[selected_camera] == "ip":
|
| 551 |
+
ip_camera_url = st.text_input("URL de la caméra IP (RTSP, HTTP)", "http://adresse-ip:port/video")
|
| 552 |
+
camera_id = ip_camera_url
|
| 553 |
+
else:
|
| 554 |
+
camera_id = camera_options[selected_camera]
|
| 555 |
|
| 556 |
# Paramètres d'affichage
|
| 557 |
display_quality = st.select_slider(
|
|
|
|
| 580 |
elif st.session_state.webcam_active:
|
| 581 |
st.warning("⚠️ La webcam est déjà active !")
|
| 582 |
else:
|
| 583 |
+
video_placeholder.info("🔄 Tentative de connexion à la caméra... Veuillez patienter.")
|
| 584 |
+
|
| 585 |
+
# Créer le processeur YOLO avec les paramètres d'optimisation
|
| 586 |
+
processor = YOLOVideoProcessor(model_path, poly1, poly2, tracker_method)
|
| 587 |
+
processor.frame_skip = frame_skip
|
| 588 |
+
processor.downsample_factor = downsample
|
| 589 |
+
processor.conf_threshold = conf_threshold
|
| 590 |
+
|
| 591 |
+
st.session_state.processor = processor
|
| 592 |
+
st.session_state.webcam_active = True
|
| 593 |
+
|
| 594 |
+
# Démarrer le traitement dans un thread séparé
|
| 595 |
+
processing_thread = threading.Thread(
|
| 596 |
+
target=st.session_state.processor.process_webcam,
|
| 597 |
+
args=(camera_id, video_placeholder, count_placeholders)
|
| 598 |
+
)
|
| 599 |
+
processing_thread.daemon = True
|
| 600 |
+
|
| 601 |
+
# Ajouter le contexte Streamlit au thread pour éviter les erreurs
|
| 602 |
+
add_script_run_ctx(processing_thread)
|
| 603 |
+
|
| 604 |
+
try:
|
| 605 |
+
processing_thread.start()
|
| 606 |
+
st.session_state.processing_thread = processing_thread
|
| 607 |
+
except Exception as e:
|
| 608 |
+
st.error(f"Erreur au démarrage du thread: {e}")
|
| 609 |
+
st.session_state.webcam_active = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
|
| 611 |
if col_stop.button("⏹️ Arrêter la détection"):
|
| 612 |
if st.session_state.webcam_active and st.session_state.processor:
|