You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

REST API端点传图至YOLOv8模型报错:不支持字节类型

解决YOLOv8 FastAPI接口传入字节图片报错问题

问题场景

使用FastAPI开发YOLOv8推理API时,通过UploadFile接收图片并读取字节内容传给模型,触发如下错误:

{
"error": "Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict"
}
此前直接传入图片路径字符串时模型可正常推理,因YOLOv8不直接支持字节类型输入导致接口调用失败。

解决方案

方案1:将字节内容转为PIL Image对象(推荐)

YOLOv8原生支持PIL Image作为输入,无需磁盘IO,效率更高。

  1. 新增依赖导入:
from PIL import Image
import io
  1. 修改/predict/接口代码:
@app.post("/predict/")
async def upload_file(file: UploadFile):
    try:
        content = await file.read()
        # 将字节流转为PIL Image对象
        image = Image.open(io.BytesIO(content))
        result = model.load_yolo_v8(image)
        return {"result": result}
    except Exception as e:
        return {"error": str(e)}
  1. 适配模型推理函数(app/model/model.py):
    YOLOv8的model()方法直接兼容路径字符串和Image对象,只需处理输出格式即可:
from ultralytics import YOLO

model = YOLO("your-model-path.pt")

def load_yolo_v8(input_data):
    results = model(input_data)
    # 处理推理结果为所需的列表格式(示例)
    output = []
    for res in results:
        for box in res.boxes:
            output.append({
                "bbox": box.xyxy[0].tolist(),
                "confidence": box.conf[0].item(),
                "class_id": int(box.cls[0].item())
            })
    return output

方案2:将字节内容保存为临时文件(兼容仅支持路径的模型逻辑)

若模型函数仅接受路径字符串,可将字节内容写入临时文件后传路径:

  1. 新增依赖导入:
import tempfile
import os
  1. 修改/predict/接口代码:
@app.post("/predict/")
async def upload_file(file: UploadFile):
    try:
        content = await file.read()
        # 创建带原文件后缀的临时文件
        ext = os.path.splitext(file.filename)[1]
        with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp_file:
            tmp_file.write(content)
            tmp_path = tmp_file.name
        
        result = model.load_yolo_v8(tmp_path)
        # 推理完成后删除临时文件
        os.unlink(tmp_path)
        
        return {"result": result}
    except Exception as e:
        return {"error": str(e)}

内容的提问来源于stack exchange,提问作者Ahmad Mujtaba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:33:40