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

如何将Streamlit上传图片转为numpy数组 解决load_img的UploadedFile类型报错

报错解决方案

错误原因

tf.keras.preprocessing.image.load_img 仅支持字符串路径、字节流、os.PathLike 类型的输入,而 Streamlit 的 st.file_uploader 返回的是封装后的 UploadedFile 类,类型不匹配导致报错。

修复后的完整代码

from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.image import img_to_array
import numpy as np
from PIL import Image
import streamlit as st


st.write("这是一个识别车辆的简单图像分类网页应用")
file = st.file_uploader("请上传图片文件", type=["jpg", "png"])

# 请替换为你自己的模型加载逻辑,原代码缺失该部分
# 示例:model = load_model("你的模型文件路径.h5")

def import_and_predict(image_data, model):
        # 直接读取UploadedFile对象
        image = Image.open(image_data).convert('RGB')
        # 缩放到模型要求的输入尺寸
        image = image.resize((64,64))
        # 转换为numpy数组
        img = img_to_array(image)
        # 像素归一化
        img = img / 255.0
        # 增加batch维度适配模型输入
        img = img.reshape(1,64,64,3)
        # 预测(TensorFlow 2.6及以上版本废弃了predict_classes,可替换为下行代码)
        # label = np.argmax(model.predict(img, verbose=0), axis=-1)
        label = model.predict_classes(img)
    
        prediction = label[0][0]
        return f"预测结果:{prediction}" 

if file is None:
    st.text("请上传一张图片文件")
else:
    res = import_and_predict(file, model)
    st.write(res)
    # 可选:展示用户上传的原图
    st.image(file, caption="上传的图片")

主要修改点

  • 移除了load_img调用,直接用PIL.Image.open读取UploadedFile对象,无需额外转格式
  • 修复了原代码中重复转数组、resize逻辑错误的问题,预处理逻辑更简洁
  • 补充了模型加载提示和预测结果展示逻辑,原代码执行后不会输出预测结果
  • 补充了高版本TensorFlow的预测写法兼容提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:39:04