Spaces:
Sleeping
Sleeping
Initial YOLOv8 measurement Space
Browse files- app.py +47 -0
- requirements.txt +7 -0
app.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr, numpy as np, cv2
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from ultralytics import YOLO
|
| 4 |
+
|
| 5 |
+
# 1) Use Ultralytics' built-in small model (22 MB) – no extra download
|
| 6 |
+
model = YOLO("yolov8s.pt") # auto-downloads first run
|
| 7 |
+
|
| 8 |
+
REF_WIDTH_CM = 10.0 # width of calibration card
|
| 9 |
+
|
| 10 |
+
def measure(image: Image.Image) -> Image.Image:
|
| 11 |
+
frame = np.array(image)
|
| 12 |
+
res = model(frame, verbose=False)[0]
|
| 13 |
+
boxes = res.boxes.xyxy.cpu().numpy()
|
| 14 |
+
|
| 15 |
+
if len(boxes) < 2: # need statue + card
|
| 16 |
+
return image
|
| 17 |
+
|
| 18 |
+
areas = (boxes[:,2]-boxes[:,0]) * (boxes[:,3]-boxes[:,1])
|
| 19 |
+
ref_idx = int(np.argmin(areas)) # smallest = card
|
| 20 |
+
obj_idx = int(np.argmax(areas)) # largest = statue
|
| 21 |
+
|
| 22 |
+
x1r,y1r,x2r,y2r = boxes[ref_idx]
|
| 23 |
+
x1o,y1o,x2o,y2o = boxes[obj_idx]
|
| 24 |
+
|
| 25 |
+
px_per_cm = (x2r - x1r) / REF_WIDTH_CM
|
| 26 |
+
w_cm = round((x2o - x1o) / px_per_cm, 2)
|
| 27 |
+
h_cm = round((y2o - y1o) / px_per_cm, 2)
|
| 28 |
+
|
| 29 |
+
canvas = frame.copy()
|
| 30 |
+
cv2.rectangle(canvas, (int(x1o),int(y1o)), (int(x2o),int(y2o)), (0,255,0), 2)
|
| 31 |
+
cv2.rectangle(canvas, (int(x1r),int(y1r)), (int(x2r),int(y2r)), (0,0,255), 1)
|
| 32 |
+
cv2.putText(canvas,
|
| 33 |
+
f"{w_cm} × {h_cm} cm",
|
| 34 |
+
(int(x1o), int(max(y1o-10,0))),
|
| 35 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,255,0), 2, cv2.LINE_AA)
|
| 36 |
+
return Image.fromarray(canvas)
|
| 37 |
+
|
| 38 |
+
demo = gr.Interface(
|
| 39 |
+
measure,
|
| 40 |
+
gr.Image(type="pil", label="Upload studio photo (10 cm card bottom-left)"),
|
| 41 |
+
gr.Image(type="pil", label="BBox + cm overlay"),
|
| 42 |
+
title="SmartDimension – YOLOv8 demo",
|
| 43 |
+
description="Detects gilded statues, finds 10 cm reference card, outputs real-world dimensions."
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if __name__ == "__main__":
|
| 47 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
torch
|
| 3 |
+
torchvision
|
| 4 |
+
ultralytics
|
| 5 |
+
opencv-python
|
| 6 |
+
Pillow
|
| 7 |
+
huggingface-hub
|