Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import cv2
|
| 4 |
-
import tempfile
|
| 5 |
-
import os
|
| 6 |
-
import time
|
| 7 |
-
import numpy as np
|
| 8 |
-
import pandas as pd
|
| 9 |
-
from collections import defaultdict
|
| 10 |
-
from ultralytics import YOLO
|
| 11 |
-
|
| 12 |
-
# --- FONCTIONS UTILES ---
|
| 13 |
-
def draw_text_with_background(image, text, position, font=cv2.FONT_HERSHEY_SIMPLEX,
|
| 14 |
-
font_scale=1, font_thickness=2, text_color=(255, 255, 255), bg_color=(0, 0, 0), padding=5):
|
| 15 |
-
"""Ajoute du texte avec un fond sur une image OpenCV."""
|
| 16 |
-
text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
|
| 17 |
-
text_width, text_height = text_size
|
| 18 |
-
|
| 19 |
-
x, y = position
|
| 20 |
-
top_left = (x, y - text_height - padding)
|
| 21 |
-
bottom_right = (x + text_width + padding * 2, y + padding)
|
| 22 |
-
|
| 23 |
-
cv2.rectangle(image, top_left, bottom_right, bg_color, -1)
|
| 24 |
-
cv2.putText(image, text, (x + padding, y), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
|
| 25 |
-
|
| 26 |
-
# --- CLASSE YOLO ---
|
| 27 |
-
class YOLOVideoProcessor:
|
| 28 |
-
def __init__(self, model_path, video_path, output_path, poly1, poly2, tracker_method="bot"):
|
| 29 |
-
self.model = YOLO(model_path, task="detect")
|
| 30 |
-
self.tracker_method = tracker_method
|
| 31 |
-
self.video_path = video_path
|
| 32 |
-
self.output_path = output_path
|
| 33 |
-
|
| 34 |
-
self.unique_region1_ids = set()
|
| 35 |
-
self.unique_region2_ids = set()
|
| 36 |
-
self.poly1 = poly1
|
| 37 |
-
self.poly2 = poly2
|
| 38 |
-
|
| 39 |
-
def is_in_region(self, center, poly):
|
| 40 |
-
poly_np = np.array(poly, dtype=np.int32)
|
| 41 |
-
return cv2.pointPolygonTest(poly_np, center, False) >= 0
|
| 42 |
-
|
| 43 |
-
def process_video(self, progress_bar):
|
| 44 |
-
cap = cv2.VideoCapture(self.video_path)
|
| 45 |
-
if not cap.isOpened():
|
| 46 |
-
st.error("⚠️ Erreur : Impossible d'ouvrir la vidéo.")
|
| 47 |
-
return
|
| 48 |
-
|
| 49 |
-
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 50 |
-
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 51 |
-
fps = int(cap.get(cv2.CAP_PROP_FPS))
|
| 52 |
-
|
| 53 |
-
if fps == 0:
|
| 54 |
-
fps = 30 # Valeur par défaut si FPS est invalide
|
| 55 |
-
|
| 56 |
-
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 57 |
-
out = cv2.VideoWriter(self.output_path, fourcc, fps, (frame_width, frame_height))
|
| 58 |
-
|
| 59 |
-
frame_count = 0
|
| 60 |
-
processed_frames = 0
|
| 61 |
-
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 62 |
-
|
| 63 |
-
while cap.isOpened():
|
| 64 |
-
success, frame = cap.read()
|
| 65 |
-
if not success:
|
| 66 |
-
break
|
| 67 |
-
|
| 68 |
-
tracker = "botsort.yaml" if self.tracker_method.lower() == "bot" else "bytetrack.yaml"
|
| 69 |
-
results = self.model.track(frame, persist=True, tracker=tracker, conf=0.25)
|
| 70 |
-
|
| 71 |
-
track_ids = []
|
| 72 |
-
if len(results[0].boxes) > 0:
|
| 73 |
-
try:
|
| 74 |
-
track_ids = results[0].boxes.id.int().cpu().tolist()
|
| 75 |
-
except AttributeError:
|
| 76 |
-
track_ids = [i for i in range(len(results[0].boxes.xywh.cpu().numpy()))]
|
| 77 |
-
|
| 78 |
-
# Dessiner les polygones
|
| 79 |
-
cv2.polylines(frame, [np.array(self.poly1, np.int32)], isClosed=True, color=(0, 255, 0), thickness=2)
|
| 80 |
-
cv2.polylines(frame, [np.array(self.poly2, np.int32)], isClosed=True, color=(255, 0, 0), thickness=2)
|
| 81 |
-
|
| 82 |
-
for box, track_id in zip(results[0].boxes.xywh.cpu().numpy(), track_ids):
|
| 83 |
-
x, y, w, h = box
|
| 84 |
-
center_point = (int(x), int(y))
|
| 85 |
-
|
| 86 |
-
if self.is_in_region(center_point, self.poly1):
|
| 87 |
-
self.unique_region1_ids.add(track_id)
|
| 88 |
-
if self.is_in_region(center_point, self.poly2):
|
| 89 |
-
self.unique_region2_ids.add(track_id)
|
| 90 |
-
|
| 91 |
-
# Affichage du comptage des véhicules
|
| 92 |
-
draw_text_with_background(frame, f'Total Sens 1: {len(self.unique_region1_ids)}', (10, frame_height - 50))
|
| 93 |
-
draw_text_with_background(frame, f'Total Sens 2: {len(self.unique_region2_ids)}', (880, frame_height - 50))
|
| 94 |
-
|
| 95 |
-
out.write(frame)
|
| 96 |
-
processed_frames += 1
|
| 97 |
-
|
| 98 |
-
# Mise à jour de la barre de progression
|
| 99 |
-
progress_bar.progress(min(int((processed_frames / total_frames) * 100), 100))
|
| 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 |
-
# --- INTERFACE STREAMLIT ---
|
| 109 |
-
st.title("🚗 Détection de Véhicules avec Polygones")
|
| 110 |
-
|
| 111 |
-
uploaded_file = st.file_uploader("📂 Upload une vidéo", type=["mp4", "avi", "mov"])
|
| 112 |
-
|
| 113 |
-
# Entrée utilisateur pour les polygones
|
| 114 |
-
st.sidebar.header("🔹 Saisie des polygones")
|
| 115 |
-
|
| 116 |
-
st.sidebar.subheader("📍 Polygone 1 (vert)")
|
| 117 |
-
poly1_input = st.sidebar.text_area("Entrez 4 points (x,y) séparés par des espaces", "465,350 609,350 520,630 3,630")
|
| 118 |
-
|
| 119 |
-
st.sidebar.subheader("📍 Polygone 2 (rouge)")
|
| 120 |
-
poly2_input = st.sidebar.text_area("Entrez 4 points (x,y) séparés par des espaces", "678,350 815,350 1203,630 743,630")
|
| 121 |
-
|
| 122 |
-
def parse_polygon(input_text):
|
| 123 |
-
try:
|
| 124 |
-
return [tuple(map(int, point.split(','))) for point in input_text.split()]
|
| 125 |
-
except:
|
| 126 |
-
return []
|
| 127 |
-
|
| 128 |
-
poly1 = parse_polygon(poly1_input)
|
| 129 |
-
poly2 = parse_polygon(poly2_input)
|
| 130 |
-
|
| 131 |
-
if uploaded_file is not None:
|
| 132 |
-
tfile = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
|
| 133 |
-
tfile.write(uploaded_file.read())
|
| 134 |
-
|
| 135 |
-
st.video(tfile.name)
|
| 136 |
-
|
| 137 |
-
model_path = "best.pt" # Assurez-vous que le modèle est bien disponible
|
| 138 |
-
output_path = os.path.join(tempfile.gettempdir(), "output_video.mp4")
|
| 139 |
-
|
| 140 |
-
if st.button("▶️ Lancer la détection"):
|
| 141 |
-
if len(poly1) == 4 and len(poly2) == 4:
|
| 142 |
-
progress_bar = st.progress(0)
|
| 143 |
-
processor = YOLOVideoProcessor(model_path, tfile.name, output_path, poly1, poly2)
|
| 144 |
-
processor.process_video(progress_bar)
|
| 145 |
-
st.success("✅ Traitement terminé !")
|
| 146 |
-
st.video(output_path)
|
| 147 |
-
else:
|
| 148 |
-
st.error("❌ Les coordonnées des polygones doivent contenir **exactement 4 points**.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|