Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,32 +3,37 @@ import torch
|
|
| 3 |
from PIL import Image
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
-
# Cargar
|
| 7 |
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
|
| 8 |
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
| 12 |
inputs = processor(images=image, return_tensors="pt")
|
| 13 |
with torch.no_grad():
|
| 14 |
outputs = model(**inputs)
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
| 18 |
results = processor.post_process_object_detection(
|
| 19 |
outputs, target_sizes=target_sizes, threshold=threshold
|
| 20 |
)[0]
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 24 |
label_name = model.config.id2label[label.item()]
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
)
|
| 28 |
|
| 29 |
-
return "\n".join(
|
| 30 |
|
| 31 |
-
# Interfaz con la API nueva de Gradio
|
| 32 |
demo = gr.Interface(
|
| 33 |
fn=detect_objects,
|
| 34 |
inputs=[gr.Image(type="pil", label="Imagen"), gr.Slider(0, 1, value=0.9, step=0.05, label="Umbral")],
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
+
# Cargar procesador y modelo
|
| 7 |
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
|
| 8 |
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
|
| 9 |
|
| 10 |
+
def detect_objects(image: Image.Image, threshold: float = 0.9):
|
| 11 |
+
if image is None:
|
| 12 |
+
return "Sube una imagen para iniciar."
|
| 13 |
+
|
| 14 |
+
# Preprocesar e inferir
|
| 15 |
inputs = processor(images=image, return_tensors="pt")
|
| 16 |
with torch.no_grad():
|
| 17 |
outputs = model(**inputs)
|
| 18 |
|
| 19 |
+
# (H, W) en enteros; shape (batch, 2)
|
| 20 |
+
h, w = image.size[1], image.size[0]
|
| 21 |
+
target_sizes = torch.tensor([[h, w]], dtype=torch.int64)
|
| 22 |
+
|
| 23 |
+
# Post-proceso
|
| 24 |
results = processor.post_process_object_detection(
|
| 25 |
outputs, target_sizes=target_sizes, threshold=threshold
|
| 26 |
)[0]
|
| 27 |
|
| 28 |
+
# Formatear salida
|
| 29 |
+
lines = []
|
| 30 |
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 31 |
label_name = model.config.id2label[label.item()]
|
| 32 |
+
box_rounded = [round(float(v), 2) for v in box.tolist()]
|
| 33 |
+
lines.append(f"Objeto: {label_name}, Score: {float(score):.2f}, Box: {box_rounded}")
|
|
|
|
| 34 |
|
| 35 |
+
return "\n".join(lines) if lines else "Sin detecciones (prueba bajando el umbral)."
|
| 36 |
|
|
|
|
| 37 |
demo = gr.Interface(
|
| 38 |
fn=detect_objects,
|
| 39 |
inputs=[gr.Image(type="pil", label="Imagen"), gr.Slider(0, 1, value=0.9, step=0.05, label="Umbral")],
|