File size: 3,027 Bytes
7d1ac51
 
 
a2562c0
de9232e
 
27e96af
 
7d1ac51
 
 
de9232e
 
 
7d1ac51
 
 
de9232e
 
 
 
 
 
7d1ac51
de9232e
 
 
 
 
27e96af
de9232e
 
7d1ac51
27e96af
de9232e
 
 
7d1ac51
 
 
 
 
27e96af
7d1ac51
a2562c0
 
de9232e
a2562c0
7d1ac51
de9232e
7d1ac51
de9232e
7d1ac51
de9232e
 
 
27e96af
de9232e
27e96af
 
 
 
de9232e
 
 
 
 
7d1ac51
de9232e
 
7d1ac51
 
de9232e
 
7d1ac51
 
 
 
de9232e
 
27e96af
7d1ac51
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import cv2
import gradio as gr
from transformers import pipeline
from PIL import Image
import tempfile

# Cargar el modelo de detecci贸n de objetos usando CPU
detector = pipeline("object-detection", model="facebook/detr-resnet-50", device=-1)

def process_video(video_path):
    """
    Procesa un video, detecta objetos y dibuja cuadros y etiquetas sobre ellos.
    Solo se procesar谩n las detecciones de personas, bicicletas y motos.
    Devuelve el video anotado.
    """
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return None

    # Obtener propiedades del 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)
    
    # Crear un archivo temporal para guardar el video de salida
    tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
    output_path = tmp_file.name
    tmp_file.close()  # Se cierra para que VideoWriter pueda escribir en 茅l

    # Configurar VideoWriter (usamos el c贸dec mp4v)
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
    
    # Definir las clases de inter茅s
    valid_labels = {"person", "bicycle", "motorcycle"}
    threshold = 0.7  # Umbral de confianza

    while True:
        ret, frame = cap.read()
        if not ret:
            break
        
        # Convertir el frame de BGR a RGB y a imagen PIL
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        pil_image = Image.fromarray(frame_rgb)
        
        # Obtener detecciones con el pipeline
        results = detector(pil_image)
        
        # Dibujar cada detecci贸n v谩lida en el frame
        for detection in results:
            score = detection["score"]
            label = detection["label"].lower()
            if score < threshold or label not in valid_labels:
                continue
            
            # Extraer la caja del objeto (dado que es un diccionario)
            box = detection["box"]
            xmin = box["xmin"]
            ymin = box["ymin"]
            xmax = box["xmax"]
            ymax = box["ymax"]

            # Dibujar el rect谩ngulo y la etiqueta en el frame
            cv2.rectangle(frame, (int(xmin), int(ymin)), (int(xmax), int(ymax)), color=(0, 255, 0), thickness=2)
            text = f"{label}: {score:.2f}"
            cv2.putText(frame, text, (int(xmin), int(ymin)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        
        # Escribir el frame anotado en el video de salida
        out.write(frame)
    
    cap.release()
    out.release()
    return output_path

iface = gr.Interface(
    fn=process_video,
    inputs=gr.Video(label="Sube tu video"),
    outputs=gr.Video(label="Video procesado"),
    title="Detecci贸n y Visualizaci贸n de Objetos en Video",
    description="Carga un video y se detectan personas, bicicletas y motos. Los objetos se enmarcan y etiquetan en tiempo real."
)

if __name__ == "__main__":
    iface.launch()