File size: 1,453 Bytes
3a555e5 |
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 |
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from ultralytics import YOLO
from PIL import Image
import io
import base64
app = FastAPI()
# Load the YOLO model
model = YOLO(r'best.pt')
class ImageData(BaseModel):
image_base64: str
@app.post("/process_image/")
async def process_image(data: ImageData):
try:
# Decode the base64 string to an image
image_data = base64.b64decode(data.image_base64)
image = Image.open(io.BytesIO(image_data))
# Process the image with YOLO
results = model(image)
result = results[0]
# Extract bounding boxes and confidence scores
boxes = result.boxes.xyxy # Bounding box coordinates
scores = result.boxes.conf # Confidence scores
if len(boxes) > 0:
# Get the index of the bounding box with the highest score
highest_score_idx = scores.argmax()
# Extract the bounding box with the highest score
highest_score_box = boxes[highest_score_idx].tolist()
x1, y1, x2, y2 = map(int, highest_score_box) # Convert to integers
else:
# If no boxes, return the whole image dimensions
x1, y1, x2, y2 = 0, 0, image.width, image.height
return {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
|