File size: 1,930 Bytes
a2b6456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
53
54
55
56
57
58
59
60
61
62
63
import gradio as gr
from ultralytics import YOLO
import cv2
import numpy as np
import tempfile
import os

# Charger le modèle YOLOv8 pré-entraîné
model = YOLO("yolov8n.pt")

# Fonction pour la détection sur image
def detect_objects_image(img):
    results = model(img)  # Détection
    annotated_frame = results[0].plot()  # Annoter les résultats
    return annotated_frame

# Fonction pour la détection sur vidéo
def detect_objects_video(video):
    # Lire la vidéo uploadée
    cap = cv2.VideoCapture(video)
    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)

    # Créer un fichier temporaire pour enregistrer la sortie
    temp_output = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
    output_path = temp_output.name

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

    while cap.isOpened():
        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 output_path

# Interface Gradio
with gr.Blocks() as demo:
    gr.Markdown("## Détection d'objets avec YOLOv8")

    with gr.Tab("Image"):
        image_input = gr.Image(type="numpy", label="Image à analyser")
        image_output = gr.Image(type="numpy", label="Image annotée")
        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="Vidéo à analyser")
        video_output = gr.Video(label="Vidéo annotée")
        video_btn = gr.Button("Analyser la vidéo")
        video_btn.click(fn=detect_objects_video, inputs=video_input, outputs=video_output)

demo.launch()