ModuMLTECH commited on
Commit
39dcce6
·
verified ·
1 Parent(s): af73c1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -111
app.py CHANGED
@@ -1,111 +1,111 @@
1
- import streamlit as st
2
- import cv2
3
- import tempfile
4
- import os
5
- import time
6
- import numpy as np
7
- from ultralytics import YOLO
8
- import threading
9
- from PIL import Image
10
- import torch
11
- import queue
12
- from streamlit.runtime.scriptrunner import add_script_run_ctx
13
-
14
- # --- FONCTIONS UTILES ---
15
- def draw_text_with_background(image, text, position, font=cv2.FONT_HERSHEY_SIMPLEX,
16
- font_scale=1, font_thickness=2, text_color=(255, 255, 255), bg_color=(0, 0, 0), padding=5):
17
- """Ajoute du texte avec un fond sur une image OpenCV."""
18
- text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
19
- text_width, text_height = text_size
20
-
21
- x, y = position
22
- top_left = (x, y - text_height - padding)
23
- bottom_right = (x + text_width + padding * 2, y + padding)
24
-
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, tracker_method="bot"):
31
- self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
32
- self.frame_skip = 2
33
- self.downsample_factor = 0.5
34
- self.img_size = 640
35
- self.conf_threshold = 0.35
36
- self.model = YOLO(model_path, task="detect").to(self.device)
37
- self.tracker_method = tracker_method
38
- self.stop_processing = False
39
-
40
- def process_webcam(self, camera_id=0, display_placeholder=None):
41
- cap = cv2.VideoCapture(camera_id)
42
- cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
43
- cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
44
- if not cap.isOpened():
45
- st.error("⚠️ Erreur : Impossible d'ouvrir la webcam.")
46
- return
47
- self.stop_processing = False
48
-
49
- while not self.stop_processing:
50
- success, frame = cap.read()
51
- if not success:
52
- break
53
- display_placeholder.image(frame, channels="BGR", use_column_width=True)
54
- cap.release()
55
- st.success("✅ Flux vidéo arrêté.")
56
-
57
- # --- INTERFACE STREAMLIT ---
58
- def main():
59
- st.set_page_config(page_title="Détecteur de Véhicules", page_icon="🚗", layout="wide")
60
- st.title("🚗 Détection et comptage de Véhicules sur l'Autoroute de l'Avenir")
61
-
62
- model_path = "best.pt"
63
- if not os.path.exists(model_path):
64
- st.error("❌ Modèle YOLO introuvable!")
65
- return
66
-
67
- tab1, tab2 = st.tabs(["🎥 Détection en Temps Réel", "📹 Analyse de Vidéo"])
68
-
69
- with st.sidebar:
70
- st.header("🔹 Paramètres")
71
- tracker_method = st.selectbox("Méthode de tracking", ["bot", "byte"], index=0)
72
- frame_skip = st.slider("Frames Skip", 1, 5, 2)
73
- downsample = st.slider("Facteur d'échelle", 0.3, 1.0, 0.5, 0.1)
74
- conf_threshold = st.slider("Seuil de confiance", 0.1, 0.9, 0.35, 0.05)
75
-
76
- with tab1:
77
- st.header("Détection en Temps Réel avec Webcam")
78
- camera_id = 0
79
- video_placeholder = st.empty()
80
-
81
- start_detection = st.button("▶️ Lancer la détection en temps réel")
82
- stop_detection = st.button("⏹️ Arrêter la détection")
83
-
84
- if start_detection:
85
- processor = YOLOVideoProcessor(model_path, tracker_method)
86
- processor.frame_skip = frame_skip
87
- processor.downsample_factor = downsample
88
- processor.conf_threshold = conf_threshold
89
- processing_thread = threading.Thread(
90
- target=processor.process_webcam, args=(camera_id, video_placeholder))
91
- processing_thread.daemon = True
92
- add_script_run_ctx(processing_thread)
93
- processing_thread.start()
94
- st.success("✅ Détection en cours...")
95
-
96
- if stop_detection:
97
- st.success("✅ Détection arrêtée.")
98
-
99
- with tab2:
100
- st.header("Analyse de Vidéo")
101
- uploaded_file = st.file_uploader("📂 Upload une vidéo", type=["mp4", "avi", "mov"])
102
- if uploaded_file is not None:
103
- temp_dir = tempfile.mkdtemp()
104
- input_video_path = os.path.join(temp_dir, "input_video.mp4")
105
- with open(input_video_path, "wb") as f:
106
- f.write(uploaded_file.getbuffer())
107
- st.video(input_video_path)
108
- st.success("Vidéo chargée avec succès.")
109
-
110
- if __name__ == "__main__":
111
- main()
 
1
+ import streamlit as st
2
+ import cv2
3
+ import tempfile
4
+ import os
5
+ import time
6
+ import numpy as np
7
+ from ultralytics import YOLO
8
+ import threading
9
+ from PIL import Image
10
+ import torch
11
+ import queue
12
+ from streamlit.runtime.scriptrunner import add_script_run_ctx
13
+
14
+ # --- FONCTIONS UTILES ---
15
+ def draw_text_with_background(image, text, position, font=cv2.FONT_HERSHEY_SIMPLEX,
16
+ font_scale=1, font_thickness=2, text_color=(255, 255, 255), bg_color=(0, 0, 0), padding=5):
17
+ """Ajoute du texte avec un fond sur une image OpenCV."""
18
+ text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
19
+ text_width, text_height = text_size
20
+
21
+ x, y = position
22
+ top_left = (x, y - text_height - padding)
23
+ bottom_right = (x + text_width + padding * 2, y + padding)
24
+
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, tracker_method="bot"):
31
+ self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
32
+ self.frame_skip = 2
33
+ self.downsample_factor = 0.5
34
+ self.img_size = 640
35
+ self.conf_threshold = 0.35
36
+ self.model = YOLO(model_path, task="detect").to(self.device)
37
+ self.tracker_method = tracker_method
38
+ self.stop_processing = False
39
+
40
+ def process_webcam(self, camera_id=0, display_placeholder=None):
41
+ cap = cv2.VideoCapture(camera_id)
42
+ cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
43
+ cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
44
+ if not cap.isOpened():
45
+ st.error("⚠️ Erreur : Impossible d'ouvrir la webcam.")
46
+ return
47
+ self.stop_processing = False
48
+
49
+ while not self.stop_processing:
50
+ success, frame = cap.read()
51
+ if not success:
52
+ break
53
+ display_placeholder.image(frame, channels="BGR", use_column_width=True)
54
+ cap.release()
55
+ st.success("✅ Flux vidéo arrêté.")
56
+
57
+ # --- INTERFACE STREAMLIT ---
58
+ def main():
59
+ st.set_page_config(page_title="Détecteur de Véhicules", page_icon="🚗", layout="wide")
60
+ st.title("🚗 Détection et comptage de Véhicules sur l'Autoroute de l'Avenir")
61
+
62
+ model_path = hf_hub_download(repo_id="ModuMLTECH/Trafic_congestion", filename="best.pt")
63
+ if not os.path.exists(model_path):
64
+ st.error("❌ Modèle YOLO introuvable!")
65
+ return
66
+
67
+ tab1, tab2 = st.tabs(["🎥 Détection en Temps Réel", "📹 Analyse de Vidéo"])
68
+
69
+ with st.sidebar:
70
+ st.header("🔹 Paramètres")
71
+ tracker_method = st.selectbox("Méthode de tracking", ["bot", "byte"], index=0)
72
+ frame_skip = st.slider("Frames Skip", 1, 5, 2)
73
+ downsample = st.slider("Facteur d'échelle", 0.3, 1.0, 0.5, 0.1)
74
+ conf_threshold = st.slider("Seuil de confiance", 0.1, 0.9, 0.35, 0.05)
75
+
76
+ with tab1:
77
+ st.header("Détection en Temps Réel avec Webcam")
78
+ camera_id = 0
79
+ video_placeholder = st.empty()
80
+
81
+ start_detection = st.button("▶️ Lancer la détection en temps réel")
82
+ stop_detection = st.button("⏹️ Arrêter la détection")
83
+
84
+ if start_detection:
85
+ processor = YOLOVideoProcessor(model_path, tracker_method)
86
+ processor.frame_skip = frame_skip
87
+ processor.downsample_factor = downsample
88
+ processor.conf_threshold = conf_threshold
89
+ processing_thread = threading.Thread(
90
+ target=processor.process_webcam, args=(camera_id, video_placeholder))
91
+ processing_thread.daemon = True
92
+ add_script_run_ctx(processing_thread)
93
+ processing_thread.start()
94
+ st.success("✅ Détection en cours...")
95
+
96
+ if stop_detection:
97
+ st.success("✅ Détection arrêtée.")
98
+
99
+ with tab2:
100
+ st.header("Analyse de Vidéo")
101
+ uploaded_file = st.file_uploader("📂 Upload une vidéo", type=["mp4", "avi", "mov"])
102
+ if uploaded_file is not None:
103
+ temp_dir = tempfile.mkdtemp()
104
+ input_video_path = os.path.join(temp_dir, "input_video.mp4")
105
+ with open(input_video_path, "wb") as f:
106
+ f.write(uploaded_file.getbuffer())
107
+ st.video(input_video_path)
108
+ st.success("Vidéo chargée avec succès.")
109
+
110
+ if __name__ == "__main__":
111
+ main()