ModuMLTECH commited on
Commit
cec7d60
·
verified ·
1 Parent(s): 7bb70f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -30
app.py CHANGED
@@ -1,12 +1,4 @@
1
  # -*- coding: utf-8 -*-
2
- """Untitled8.ipynb
3
-
4
- Automatically generated by Colab.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/17hKCetX4b9rOVZK9WPeKXBDYONdYYktD
8
- """
9
-
10
  import streamlit as st
11
  import cv2
12
  import tempfile
@@ -18,14 +10,9 @@ from collections import defaultdict
18
  from ultralytics import YOLO
19
 
20
  # --- FONCTIONS UTILES ---
21
-
22
- def get_color_for_id(track_id):
23
- np.random.seed(track_id)
24
- return tuple(np.random.randint(0, 255, size=3).tolist())
25
-
26
  def draw_text_with_background(image, text, position, font=cv2.FONT_HERSHEY_SIMPLEX,
27
  font_scale=1, font_thickness=2, text_color=(255, 255, 255), bg_color=(0, 0, 0), padding=5):
28
-
29
  text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
30
  text_width, text_height = text_size
31
 
@@ -36,20 +23,42 @@ def draw_text_with_background(image, text, position, font=cv2.FONT_HERSHEY_SIMPL
36
  cv2.rectangle(image, top_left, bottom_right, bg_color, -1)
37
  cv2.putText(image, text, (x + padding, y), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
38
 
39
- # --- CLASSE DE TRAITEMENT YOLO ---
40
  class YOLOVideoProcessor:
41
- def __init__(self, model_path, video_path, output_path, tracker_method="bot"):
42
  self.model = YOLO(model_path, task="detect")
43
  self.tracker_method = tracker_method
44
  self.video_path = video_path
45
- self.output_path = output_path
46
 
47
- def process_video(self):
 
 
 
 
 
 
 
 
 
48
  cap = cv2.VideoCapture(self.video_path)
 
 
 
 
49
  frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
50
  frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
51
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
52
- out = cv2.VideoWriter(self.output_path, fourcc, 30, (frame_width, frame_height))
 
 
 
 
 
 
 
 
 
53
 
54
  while cap.isOpened():
55
  success, frame = cap.read()
@@ -59,30 +68,81 @@ class YOLOVideoProcessor:
59
  tracker = "botsort.yaml" if self.tracker_method.lower() == "bot" else "bytetrack.yaml"
60
  results = self.model.track(frame, persist=True, tracker=tracker, conf=0.25)
61
 
62
- draw_text_with_background(frame, "Processing...", (7, 30))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  out.write(frame)
 
 
 
 
65
 
66
  cap.release()
67
  out.release()
68
  cv2.destroyAllWindows()
69
 
 
 
 
70
  # --- INTERFACE STREAMLIT ---
71
- st.title("🚗 Détection de Véhicules avec YOLO")
72
 
73
  uploaded_file = st.file_uploader("📂 Upload une vidéo", type=["mp4", "avi", "mov"])
74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  if uploaded_file is not None:
76
  tfile = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
77
  tfile.write(uploaded_file.read())
78
 
79
  st.video(tfile.name)
80
 
81
- model_path = "best.pt" # Mettre le bon chemin du modèle
82
- output_path = "output_video.mp4"
83
-
84
- if st.button("▶️ Lancer l'analyse"):
85
- processor = YOLOVideoProcessor(model_path, tfile.name, output_path)
86
- processor.process_video()
87
- st.success("✅ Traitement terminé !")
88
- st.video(output_path)
 
 
 
 
 
1
  # -*- coding: utf-8 -*-
 
 
 
 
 
 
 
 
2
  import streamlit as st
3
  import cv2
4
  import tempfile
 
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
 
 
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()
 
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**.")