Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 📷 Object Detection Demo | CPU-only HF Space
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
from PIL import Image, ImageDraw
|
| 6 |
+
|
| 7 |
+
# Load the DETR object-detection pipeline (CPU)
|
| 8 |
+
detector = pipeline("object-detection", model="facebook/detr-resnet-50", device=-1)
|
| 9 |
+
|
| 10 |
+
def detect_objects(image: Image.Image):
|
| 11 |
+
# Run object detection
|
| 12 |
+
outputs = detector(image)
|
| 13 |
+
|
| 14 |
+
# Draw bounding boxes
|
| 15 |
+
annotated = image.convert("RGB")
|
| 16 |
+
draw = ImageDraw.Draw(annotated)
|
| 17 |
+
table = []
|
| 18 |
+
for obj in outputs:
|
| 19 |
+
# DETR returns box as [xmin, ymin, xmax, ymax]
|
| 20 |
+
xmin, ymin, xmax, ymax = obj["box"]
|
| 21 |
+
label = obj["label"]
|
| 22 |
+
score = round(obj["score"], 3)
|
| 23 |
+
|
| 24 |
+
# draw box and label
|
| 25 |
+
draw.rectangle([xmin, ymin, xmax, ymax], outline="red", width=2)
|
| 26 |
+
draw.text((xmin, ymin - 10), f"{label} ({score})", fill="red")
|
| 27 |
+
|
| 28 |
+
table.append([label, score])
|
| 29 |
+
|
| 30 |
+
# Return the annotated image and a table of detections
|
| 31 |
+
return annotated, table
|
| 32 |
+
|
| 33 |
+
with gr.Blocks(title="📷✨ Object Detection Demo") as demo:
|
| 34 |
+
gr.Markdown(
|
| 35 |
+
"""
|
| 36 |
+
# 📷✨ Object Detection
|
| 37 |
+
Upload an image and let DETR (a Transformer-based model) identify objects in real time.
|
| 38 |
+
"""
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
with gr.Row():
|
| 42 |
+
img_in = gr.Image(type="pil", label="Upload Image")
|
| 43 |
+
detect_btn = gr.Button("Detect Objects 🔍", variant="primary")
|
| 44 |
+
img_out = gr.Image(label="Annotated Image")
|
| 45 |
+
table_out = gr.Dataframe(
|
| 46 |
+
headers=["Label", "Score"],
|
| 47 |
+
datatype=["str", "number"],
|
| 48 |
+
wrap=True,
|
| 49 |
+
interactive=False,
|
| 50 |
+
label="Detections"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
detect_btn.click(detect_objects, inputs=img_in, outputs=[img_out, table_out])
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
demo.launch(server_name="0.0.0.0")
|