Search code examples
pythonrestfastapiyolov8

How to upload Images in rest API endpoint?


I am using YOLOv8 model, and creating API for it, I have to pass image in my model, through rest end point.

from fastapi import FastAPI, File, UploadFile
from pydantic import BaseModel
import app.model.model as model

app = FastAPI()


class FileIn(BaseModel):
    file: UploadFile


class PredictionOut(BaseModel):
    result: list


@app.get("/")
def home():
    return {"health_check": "OK", "model_version": 0.01}


@app.post("/predict/")
async def upload_file(file: UploadFile):
    try:
        content = file.file.read()
        print(type(content))
        result = model.load_yolo_v8(content)

        return {"result": result}
    except Exception as e:
        return {"error": str(e)}

It is throwing me error,

{
    "error": "Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict"
}

I have tried my model and given it path as a string, and it works but when I do hit request after making API it fails, it is taking image file type as bytes from postman, yolov8 does not support bytes.


Solution

  • @app.post("/predict/")
    async def upload_file(file: UploadFile):
        try:
            content_byte = file.file.read()
            content_image = Image.open(io.BytesIO(content_byte))
            result = model.predict_result(content_image)
    
            return {"result": result}
        except Exception as e:
            return {"error": str(e)}
    

    here's how I did it:

    content_byte = file.file.read()

    content_image = Image.open(io.BytesIO(content_byte))