|
from fastapi import FastAPI, File, UploadFile |
|
from fastapi.responses import HTMLResponse |
|
from fastapi.staticfiles import StaticFiles |
|
from fastapi.templating import Jinja2Templates |
|
from ultralytics import YOLO |
|
import requests |
|
from PIL import Image |
|
import numpy as np |
|
import cv2 |
|
import io |
|
import os |
|
|
|
app = FastAPI() |
|
|
|
|
|
app.mount("/tmp", StaticFiles(directory="/tmp"), name="static") |
|
|
|
|
|
templates = Jinja2Templates(directory="templates") |
|
|
|
|
|
def predict_yolo(image_path): |
|
|
|
model = YOLO('yolov8n.pt') |
|
|
|
|
|
results = model(image_path) |
|
|
|
|
|
for result in results: |
|
boxes = result.boxes |
|
|
|
|
|
|
|
predictions = boxes.json() |
|
return predictions |
|
|
|
|
|
def draw_boxes(image, boxes): |
|
for box in boxes: |
|
x, y, w, h = box["bbox"] |
|
cv2.rectangle(image, (int(x), int(y)), (int(x + w), int(y + h)), (0, 255, 0), 2) |
|
return image |
|
|
|
|
|
@app.post("/uploadfile/") |
|
async def create_upload_file(file: UploadFile = File(...)): |
|
contents = await file.read() |
|
image = Image.open(io.BytesIO(contents)) |
|
|
|
|
|
save_path = f"/tmp/{file.filename}" |
|
image.save(save_path) |
|
|
|
|
|
predictions = predict_yolo(save_path) |
|
|
|
|
|
image_np = np.array(image) |
|
image_with_boxes = draw_boxes(image_np, predictions) |
|
|
|
|
|
image_with_boxes_path = f"/tmp/{file.filename.split('.')[0]}_with_boxes.jpg" |
|
cv2.imwrite(image_with_boxes_path, cv2.cvtColor(image_with_boxes, cv2.COLOR_RGB2BGR)) |
|
|
|
|
|
return templates.TemplateResponse("prediction.html", {"request": file, "image_path": image_with_boxes_path}) |
|
|
|
@app.get("/test") |
|
async def read_root(): |
|
return {"message": "TEST"} |
|
|
|
|
|
@app.get("/") |
|
async def read_root(): |
|
return {"message": "Hello, this is a YOLO prediction API using FastAPI!"} |