File size: 2,015 Bytes
92d6fec f87b5b3 92d6fec f87b5b3 92d6fec f87b5b3 92d6fec f87b5b3 92d6fec f87b5b3 92d6fec f87b5b3 92d6fec f87b5b3 92d6fec f87b5b3 92d6fec f87b5b3 |
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 |
# 📷 Object Detection Demo | CPU-only HF Space
import gradio as gr
from transformers import pipeline
from PIL import Image, ImageDraw
# Load DETR object‐detection pipeline (requires timm in requirements)
detector = pipeline("object-detection", model="facebook/detr-resnet-50", device=-1)
def detect_objects(image: Image.Image):
outputs = detector(image)
annotated = image.convert("RGB")
draw = ImageDraw.Draw(annotated)
table = []
for obj in outputs:
box = obj["box"]
# DETR pipeline may return box as dict or list
if isinstance(box, dict):
xmin = int(box.get("xmin", box.get("x", 0)))
ymin = int(box.get("ymin", box.get("y", 0)))
xmax = int(box.get("xmax", xmin))
ymax = int(box.get("ymax", ymin))
else:
# assume [x, y, w, h]
x, y, w, h = box
xmin, ymin = int(x), int(y)
xmax, ymax = int(x + w), int(y + h)
label = obj["label"]
score = round(obj["score"], 3)
# draw box & label
draw.rectangle([xmin, ymin, xmax, ymax], outline="red", width=2)
draw.text((xmin, max(ymin - 10, 0)), f"{label} ({score})", fill="red")
table.append([label, score])
return annotated, table
with gr.Blocks(title="📷✨ Object Detection Demo") as demo:
gr.Markdown(
"""
# 📷✨ Object Detection
Upload an image and let DETR identify objects on CPU.
"""
)
with gr.Row():
img_in = gr.Image(type="pil", label="Upload Image")
btn = gr.Button("Detect Objects 🔍", variant="primary")
img_out = gr.Image(label="Annotated Image")
table_out = gr.Dataframe(
headers=["Label", "Score"],
datatype=["str", "number"],
wrap=True,
interactive=False,
label="Detections"
)
btn.click(detect_objects, inputs=img_in, outputs=[img_out, table_out])
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0")
|