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

调用TensorFlow load_img传入图像时出现utf-8 decode error如何解决?

报错根因

tensorflow.keras.preprocessing.image.load_img 接口的第一个入参仅支持本地图片路径字符串或可读取的文件类对象,你当前直接传入了UploadFile.read()返回的原始二进制字节流,接口会误将字节流识别为文件路径字符串尝试做UTF-8解码,而图片二进制首字节为0xff不符合UTF-8编码规则,因此触发报错。

修复方案

仅需新增io.BytesIO将二进制字节流包装为类文件对象再传入接口即可,修改点如下:

  1. 新增BytesIO导入声明
  2. 修改load_img入参逻辑

修改后的完整代码如下:

from starlette.responses import RedirectResponse
from fastapi import FastAPI, File, UploadFile
from tensorflow.keras import preprocessing
from fastapi.staticfiles import StaticFiles
from keras.models import load_model
import numpy as np
import uvicorn
# 新增导入BytesIO
from io import BytesIO

app = FastAPI()
app.mount("/Templates", StaticFiles(directory="Templates"), name="Templates")

model_dir = 'F:\\Saved-Models\\Dog-Cat-Models\\First_Generation_dog_cat_optuna.h5'
model = load_model(model_dir)


@app.get('/')
async def index():
    return RedirectResponse(url="/Templates/index.html")


@app.post('/prediction_page')
async def prediction_form(dogcat_img: UploadFile = File(...)):
    dogcat_img_bytes = dogcat_img.file.read()
    # 用BytesIO包装字节流为类文件对象
    pp_dogcat_image = preprocessing.image.load_img(BytesIO(dogcat_img_bytes), target_size=(150, 150))
    pp_dogcat_image_arr = preprocessing.image.img_to_array(pp_dogcat_image)
    input_arr = np.array([pp_dogcat_image_arr])
    prediction = np.argmax(model.predict(input_arr), axis=-1)

    print(prediction)


if __name__ == '__main__':
    uvicorn.run(app, host='localhost', port=8000)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:27:03