Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,102 +1,218 @@
|
|
| 1 |
-
import matplotlib
|
| 2 |
-
matplotlib.use('Agg')
|
| 3 |
-
|
| 4 |
import streamlit as st
|
| 5 |
import cv2
|
| 6 |
-
import numpy as np
|
| 7 |
-
from yolov5 import YOLOv5
|
| 8 |
-
from sort.sort import Sort
|
| 9 |
import tempfile
|
| 10 |
-
import shutil
|
| 11 |
-
from moviepy.editor import VideoFileClip, concatenate_videoclips, ImageSequenceClip
|
| 12 |
import os
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
if
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
cv2.
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 4 |
import os
|
| 5 |
+
import time
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from ultralytics import YOLO
|
| 10 |
+
|
| 11 |
+
# --- FONCTIONS UTILES ---
|
| 12 |
+
def draw_text_with_background(image, text, position, font=cv2.FONT_HERSHEY_SIMPLEX,
|
| 13 |
+
font_scale=1, font_thickness=2, text_color=(255, 255, 255), bg_color=(0, 0, 0), padding=5):
|
| 14 |
+
"""Ajoute du texte avec un fond sur une image OpenCV."""
|
| 15 |
+
text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
|
| 16 |
+
text_width, text_height = text_size
|
| 17 |
+
|
| 18 |
+
x, y = position
|
| 19 |
+
top_left = (x, y - text_height - padding)
|
| 20 |
+
bottom_right = (x + text_width + padding * 2, y + padding)
|
| 21 |
+
|
| 22 |
+
cv2.rectangle(image, top_left, bottom_right, bg_color, -1)
|
| 23 |
+
cv2.putText(image, text, (x + padding, y), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
|
| 24 |
+
|
| 25 |
+
# --- CLASSE YOLO ---
|
| 26 |
+
class YOLOVideoProcessor:
|
| 27 |
+
def __init__(self, model_path, video_path, output_path, poly1, poly2, tracker_method="bot"):
|
| 28 |
+
self.model = YOLO(model_path, task="detect")
|
| 29 |
+
self.tracker_method = tracker_method
|
| 30 |
+
self.video_path = video_path
|
| 31 |
+
self.output_path = output_path
|
| 32 |
+
|
| 33 |
+
self.unique_region1_ids = set()
|
| 34 |
+
self.unique_region2_ids = set()
|
| 35 |
+
self.poly1 = poly1
|
| 36 |
+
self.poly2 = poly2
|
| 37 |
+
|
| 38 |
+
def is_in_region(self, center, poly):
|
| 39 |
+
poly_np = np.array(poly, dtype=np.int32)
|
| 40 |
+
return cv2.pointPolygonTest(poly_np, center, False) >= 0
|
| 41 |
+
|
| 42 |
+
def process_video(self, progress_bar=None):
|
| 43 |
+
cap = cv2.VideoCapture(self.video_path)
|
| 44 |
+
if not cap.isOpened():
|
| 45 |
+
st.error("⚠️ Erreur : Impossible d'ouvrir la vidéo.")
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 49 |
+
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 50 |
+
fps = int(cap.get(cv2.CAP_PROP_FPS))
|
| 51 |
+
|
| 52 |
+
if fps == 0:
|
| 53 |
+
fps = 30 # Valeur par défaut si FPS est invalide
|
| 54 |
+
|
| 55 |
+
# Utiliser XVID qui est généralement mieux supporté
|
| 56 |
+
fourcc = cv2.VideoWriter_fourcc(*'XVID')
|
| 57 |
+
out = cv2.VideoWriter(self.output_path, fourcc, fps, (frame_width, frame_height))
|
| 58 |
+
|
| 59 |
+
processed_frames = 0
|
| 60 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 61 |
+
|
| 62 |
+
while cap.isOpened():
|
| 63 |
+
success, frame = cap.read()
|
| 64 |
+
if not success:
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
# Mise à jour de la barre de progression
|
| 68 |
+
if progress_bar is not None:
|
| 69 |
+
progress_bar.progress(processed_frames / total_frames)
|
| 70 |
+
|
| 71 |
+
tracker = "botsort.yaml" if self.tracker_method.lower() == "bot" else "bytetrack.yaml"
|
| 72 |
+
results = self.model.track(frame, persist=True, tracker=tracker, conf=0.25)
|
| 73 |
+
|
| 74 |
+
track_ids = []
|
| 75 |
+
if results and len(results) > 0 and len(results[0].boxes) > 0:
|
| 76 |
+
try:
|
| 77 |
+
track_ids = results[0].boxes.id.int().cpu().tolist()
|
| 78 |
+
except AttributeError:
|
| 79 |
+
track_ids = [i for i in range(len(results[0].boxes.xywh.cpu().numpy()))]
|
| 80 |
+
|
| 81 |
+
# Dessiner les polygones
|
| 82 |
+
cv2.polylines(frame, [np.array(self.poly1, np.int32)], isClosed=True, color=(0, 255, 0), thickness=2)
|
| 83 |
+
cv2.polylines(frame, [np.array(self.poly2, np.int32)], isClosed=True, color=(255, 0, 0), thickness=2)
|
| 84 |
+
|
| 85 |
+
for box, track_id in zip(results[0].boxes.xywh.cpu().numpy(), track_ids):
|
| 86 |
+
x, y, w, h = box
|
| 87 |
+
center_point = (int(x), int(y))
|
| 88 |
+
|
| 89 |
+
if self.is_in_region(center_point, self.poly1):
|
| 90 |
+
self.unique_region1_ids.add(track_id)
|
| 91 |
+
if self.is_in_region(center_point, self.poly2):
|
| 92 |
+
self.unique_region2_ids.add(track_id)
|
| 93 |
+
|
| 94 |
+
# Affichage du comptage des véhicules
|
| 95 |
+
draw_text_with_background(frame, f'Total Sens 1: {len(self.unique_region1_ids)}', (10, frame_height - 50))
|
| 96 |
+
draw_text_with_background(frame, f'Total Sens 2: {len(self.unique_region2_ids)}', (frame_width - 300, frame_height - 50))
|
| 97 |
+
|
| 98 |
+
out.write(frame)
|
| 99 |
+
processed_frames += 1
|
| 100 |
+
|
| 101 |
+
cap.release()
|
| 102 |
+
out.release()
|
| 103 |
+
cv2.destroyAllWindows()
|
| 104 |
+
|
| 105 |
+
if processed_frames == 0:
|
| 106 |
+
st.error("⚠️ Aucune image n'a été écrite dans la vidéo de sortie !")
|
| 107 |
+
|
| 108 |
+
return len(self.unique_region1_ids), len(self.unique_region2_ids)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# --- INTERFACE STREAMLIT ---
|
| 112 |
def main():
|
| 113 |
+
st.set_page_config(
|
| 114 |
+
page_title="Détecteur de Véhicules",
|
| 115 |
+
page_icon="🚗",
|
| 116 |
+
layout="wide"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
st.title("🚗 Détection et comptage de Véhicules sur l'Autoroute de l'Avenir")
|
| 120 |
+
|
| 121 |
+
# Vérifier si le modèle existe déjà ou doit être téléchargé
|
| 122 |
+
model_path = "best.pt"
|
| 123 |
+
if not os.path.exists(model_path):
|
| 124 |
+
with st.spinner("📥 Chargement du modèle YOLO... Cela peut prendre un moment."):
|
| 125 |
+
# Utilisez hub.load pour télécharger le modèle depuis Hugging Face Hub
|
| 126 |
+
try:
|
| 127 |
+
from huggingface_hub import hf_hub_download
|
| 128 |
+
model_path = hf_hub_download(repo_id="ModuMLTECH/projet_trafic_2", filename="best.pt")
|
| 129 |
+
st.success("✅ Modèle chargé avec succès!")
|
| 130 |
+
except Exception as e:
|
| 131 |
+
st.error(f"❌ Erreur lors du chargement du modèle: {e}")
|
| 132 |
+
# Fallback: utiliser un modèle YOLO standard
|
| 133 |
+
st.warning("⚠️ Utilisation du modèle YOLO standard à la place")
|
| 134 |
+
model_path = "yolov8n.pt"
|
| 135 |
+
|
| 136 |
+
# Colonnes pour l'organisation de l'interface
|
| 137 |
+
col1, col2 = st.columns([3, 1])
|
| 138 |
+
|
| 139 |
+
with col2:
|
| 140 |
+
st.header("🔹 Paramètres")
|
| 141 |
+
|
| 142 |
+
# Entrée utilisateur pour les polygones
|
| 143 |
+
st.subheader("📍 Polygone 1 (vert)")
|
| 144 |
+
poly1_input = st.text_area("Entrez 4 points (x,y) séparés par des espaces", "465,350 609,350 520,630 3,630")
|
| 145 |
+
|
| 146 |
+
st.subheader("📍 Polygone 2 (rouge)")
|
| 147 |
+
poly2_input = st.text_area("Entrez 4 points (x,y) séparés par des espaces", "678,350 815,350 1203,630 743,630")
|
| 148 |
+
|
| 149 |
+
tracker_method = st.selectbox("Méthode de tracking", ["bot", "byte"], index=0)
|
| 150 |
+
|
| 151 |
+
with col1:
|
| 152 |
+
uploaded_file = st.file_uploader("📂 Upload une vidéo", type=["mp4", "avi", "mov"])
|
| 153 |
+
|
| 154 |
+
def parse_polygon(input_text):
|
| 155 |
+
try:
|
| 156 |
+
return [tuple(map(int, point.split(','))) for point in input_text.split()]
|
| 157 |
+
except:
|
| 158 |
+
return []
|
| 159 |
+
|
| 160 |
+
poly1 = parse_polygon(poly1_input)
|
| 161 |
+
poly2 = parse_polygon(poly2_input)
|
| 162 |
+
|
| 163 |
+
if uploaded_file is not None:
|
| 164 |
+
# Créer un dossier temporaire si nécessaire
|
| 165 |
+
temp_dir = tempfile.mkdtemp()
|
| 166 |
+
input_video_path = os.path.join(temp_dir, "input_video.mp4")
|
| 167 |
+
output_video_path = os.path.join(temp_dir, "output_video.mp4")
|
| 168 |
+
|
| 169 |
+
# Écrire le fichier téléchargé dans un fichier temporaire
|
| 170 |
+
with open(input_video_path, "wb") as f:
|
| 171 |
+
f.write(uploaded_file.getbuffer())
|
| 172 |
+
|
| 173 |
+
st.video(input_video_path) # Afficher la vidéo d'entrée
|
| 174 |
+
|
| 175 |
+
if st.button("▶️ Lancer la détection"):
|
| 176 |
+
if len(poly1) == 4 and len(poly2) == 4:
|
| 177 |
+
# Afficher la barre de progression
|
| 178 |
+
progress_text = "🔄 Traitement de la vidéo en cours..."
|
| 179 |
+
progress_bar = st.progress(0)
|
| 180 |
+
|
| 181 |
+
# Traitement de la vidéo
|
| 182 |
+
processor = YOLOVideoProcessor(model_path, input_video_path, output_video_path, poly1, poly2, tracker_method)
|
| 183 |
+
|
| 184 |
+
# Démarrer le traitement
|
| 185 |
+
start_time = time.time()
|
| 186 |
+
count1, count2 = processor.process_video(progress_bar=progress_bar)
|
| 187 |
+
end_time = time.time()
|
| 188 |
+
|
| 189 |
+
# Calcul du temps de traitement
|
| 190 |
+
processing_time = end_time - start_time
|
| 191 |
+
|
| 192 |
+
progress_bar.progress(1.0) # Compléter la barre de progression
|
| 193 |
+
st.success(f"✅ Traitement terminé en {processing_time:.2f} secondes!")
|
| 194 |
+
|
| 195 |
+
# Afficher les résultats
|
| 196 |
+
col_result1, col_result2 = st.columns(2)
|
| 197 |
+
with col_result1:
|
| 198 |
+
st.metric("Véhicules Sens 1 (Vert)", count1)
|
| 199 |
+
with col_result2:
|
| 200 |
+
st.metric("Véhicules Sens 2 (Rouge)", count2)
|
| 201 |
+
|
| 202 |
+
# Afficher la vidéo traitée
|
| 203 |
+
st.subheader("Vidéo traitée")
|
| 204 |
+
st.video(output_video_path)
|
| 205 |
+
|
| 206 |
+
# Option de téléchargement
|
| 207 |
+
with open(output_video_path, "rb") as file:
|
| 208 |
+
st.download_button(
|
| 209 |
+
label="⬇️ Télécharger la vidéo",
|
| 210 |
+
data=file,
|
| 211 |
+
file_name="video_traitee.mp4",
|
| 212 |
+
mime="video/mp4"
|
| 213 |
+
)
|
| 214 |
+
else:
|
| 215 |
+
st.error("❌ Les coordonnées des polygones doivent contenir **exactement 4 points**.")
|
| 216 |
|
| 217 |
if __name__ == "__main__":
|
| 218 |
+
main()
|