Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from ultralytics import YOLO | |
| import shutil | |
| import os | |
| import cv2 | |
| import tempfile | |
| # Charger le modèle YOLOv8 | |
| model = YOLO("yolov8n.pt") | |
| # 🔍 Détection sur image | |
| def detect_objects_image(img): | |
| results = model(img) | |
| return results[0].plot() | |
| # 🎥 Détection sur vidéo | |
| model = YOLO("yolov8n.pt") | |
| def detect_objects_video(video): | |
| # Si l'entrée est une chaîne, utiliser telle quelle. Sinon, utiliser .name (cas Gradio) | |
| video_path = video.name if hasattr(video, 'name') else video | |
| temp_output = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) | |
| cap = cv2.VideoCapture(video_path) | |
| width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
| height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
| fps = cap.get(cv2.CAP_PROP_FPS) | |
| fourcc = cv2.VideoWriter_fourcc(*'mp4v') | |
| out = cv2.VideoWriter(temp_output.name, fourcc, fps, (width, height)) | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| results = model(frame) | |
| annotated_frame = results[0].plot() | |
| out.write(annotated_frame) | |
| cap.release() | |
| out.release() | |
| return temp_output.name | |
| # Lancer l'interface avec deux onglets | |
| with gr.Blocks(theme='shivi/calm_seafoam') as demo: | |
| gr.Markdown("## 📸 Détection d’objets avec YOLOv8 - Image et Vidéo") | |
| with gr.Tab("🖼️ Image"): | |
| image_input = gr.Image(type="numpy", label="Importer une image") | |
| image_output = gr.Image(type="numpy", label="Image avec détection") | |
| image_btn = gr.Button("Analyser l'image") | |
| image_btn.click(fn=detect_objects_image, inputs=image_input, outputs=image_output) | |
| with gr.Tab("🎞️ Vidéo"): | |
| video_input = gr.Video(label="Importer une vidéo (.mp4)") | |
| video_output = gr.Video(label="Vidéo traitée") | |
| video_btn = gr.Button("Analyser la vidéo") | |
| video_btn.click(fn=detect_objects_video, inputs=video_input, outputs=video_output) | |
| demo.launch() | |