Spaces:
Sleeping
Sleeping
File size: 1,908 Bytes
191e493 5326b4f 191e493 45c3701 191e493 5326b4f 191e493 5326b4f 191e493 45c3701 191e493 45c3701 191e493 45c3701 191e493 | 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 | import io
import base64
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from ultralytics import YOLO
from PIL import Image
# Load model at startup
MODEL_PATH = "yolov8x.pt" # 🔹 Change this to "best.pt" later when you download
model = YOLO(MODEL_PATH)
print("✅ Model loaded with classes:", model.names)
# Create FastAPI app
app = FastAPI(
title="WeedCrop Detection API",
description="YOLOv8 API for detecting weeds and crops",
version="1.0"
)
# ---------- Single endpoint: JSON + Annotated Image ----------
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
try:
# Read image
image_bytes = await file.read()
img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# Run inference
results = model.predict(img, conf=0.25, imgsz=640)
# Draw bounding boxes
annotated_frame = results[0].plot() # numpy (BGR)
annotated_img = Image.fromarray(annotated_frame[..., ::-1]) # Convert BGR → RGB
# Encode as base64
buf = io.BytesIO()
annotated_img.save(buf, format="PNG")
img_bytes = buf.getvalue()
img_base64 = base64.b64encode(img_bytes).decode("utf-8")
# Collect detections
detections = []
for r in results[0].boxes:
cls_id = int(r.cls[0])
label = model.names[cls_id]
conf = float(r.conf[0])
bbox = [float(x) for x in r.xyxy[0].tolist()]
detections.append({
"class_id": cls_id,
"label": label,
"confidence": conf,
"bbox": bbox
})
return JSONResponse(content={
"detections": detections,
"image_base64": img_base64
})
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500)
|