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

PIL图像转Tensor报错:口罩识别图像分类模型运行异常

口罩识别模型报错解决:PIL.Image转Tensor失败

原代码

import tensorflow as tf
from tensorflow import keras
from keras.models import  load_model
import streamlit as st
import numpy as np 

st.header('Image Classification Model')
model = load_model('C:\\Users\\ajit7\\OneDrive\\Documents\\Major Project\\Image_classify.keras')
data_cat = ['WithMask', 'WithoutMask']
img_height = 224
img_width = 224
image =st.text_input('Enter Image name','C:\\Users\\ajit7\\OneDrive\\Documents\\Major Project\\gayatri-malhotra-26SGAduvONc-unsplash.png')

image_load = tf.keras.utils.load_img(image, target_size=(img_height,img_width))
img_arr = tf.keras.utils.array_to_img(image_load)
img_bat=tf.expand_dims(img_arr,0)

predict = model.predict(img_bat)

score = tf.nn.softmax(predict)
st.image(image, width=200)
st.write(  data_cat[np.argmax(score)])
st.write('With accuracy of ' + str(np.max(score)*100))

触发错误

ValueError: Attempt to convert a value (<PIL.Image.Image image mode=RGB size=224x224 at 0x213D2F9E670>) with an unsupported type (<class 'PIL.Image.Image'>) to a Tensor.
Traceback:
File "C:\ProgramData\anaconda3\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 584, in _run_script
    exec(code, module.__dict__)
File "C:\Users\ajit7\OneDrive\Documents\Major Project\app1.py", line 17, in <module>
    img_bat=tf.expand_dims(img_arr,0)
File "C:\ProgramData\anaconda3\lib\site-packages\tensorflow\python\util\traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
File "C:\ProgramData\anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py", line 102, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)

问题原因

代码误用了tf.keras.utils.array_to_img(image_load)——这个函数的作用是把numpy数组转成PIL图像,但我们需要的是将PIL图像转换为模型可处理的数组/Tensor类型。tf.expand_dims只能处理数组或Tensor,无法直接识别PIL对象,因此触发转换错误。

修复方案

将img_arr = tf.keras.utils.array_to_img(image_load)替换为img_arr = tf.keras.utils.img_to_array(image_load),该函数会将PIL图像转为numpy数组,后续即可正常通过tf.expand_dims添加批量维度供模型预测。

修复后完整代码

import tensorflow as tf
from tensorflow import keras
from keras.models import  load_model
import streamlit as st
import numpy as np 

st.header('Image Classification Model')
model = load_model('C:\\Users\\ajit7\\OneDrive\\Documents\\Major Project\\Image_classify.keras')
data_cat = ['WithMask', 'WithoutMask']
img_height = 224
img_width = 224
image =st.text_input('Enter Image name','C:\\Users\\ajit7\\OneDrive\\Documents\\Major Project\\gayatri-malhotra-26SGAduvONc-unsplash.png')

image_load = tf.keras.utils.load_img(image, target_size=(img_height,img_width))
img_arr = tf.keras.utils.img_to_array(image_load)  # 此处修改函数
img_bat=tf.expand_dims(img_arr,0)

predict = model.predict(img_bat)

score = tf.nn.softmax(predict)
st.image(image, width=200)
st.write(data_cat[np.argmax(score)])
st.write('With accuracy of ' + str(np.max(score)*100))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:22:51