File size: 1,318 Bytes
6eb397b
853ac47
6eb397b
 
 
853ac47
 
6eb397b
 
 
 
 
 
 
8695168
6eb397b
 
 
 
 
 
 
 
 
38243ec
 
 
 
 
 
 
 
 
 
 
853ac47
38243ec
 
 
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
import gradio as gr
from transformers import AutoImageProcessor, AutoModelForObjectDetection
import torch
from PIL import Image, ImageDraw

processor = AutoImageProcessor.from_pretrained("joortif/practica_2_detr")
model = AutoModelForObjectDetection.from_pretrained("joortif/practica_2_detr")

def detect_objects(img: Image.Image):
    inputs = processor(images=img, return_tensors="pt")
    outputs = model(**inputs)

    target_sizes = torch.tensor([img.size[::-1]])  #
    results = processor.post_process_object_detection(
        outputs, target_sizes=target_sizes, threshold=0.3
    )[0]

    draw = ImageDraw.Draw(img)
    for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
        box = [round(i, 2) for i in box.tolist()]
        draw.rectangle(box, outline="red", width=3)
        draw.text((box[0], box[1]), f"{model.config.id2label[label.item()]}: {score:.2f}", fill="red")
    
    return img

example_images = [
    "https://huggingface.co/joortif/practica_2/resolve/main/00111.jpg",
    "https://huggingface.co/joortif/practica_2/resolve/main/00148.jpg"
]

demo = gr.Interface(
    fn=detect_objects,
    inputs=gr.Image(type="pil"),
    outputs=gr.Image(type="pil"),
    title="Detección de Objetos - joortif/practica_2",
    examples=example_images
)

demo.launch()