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

TensorFlow绘图分类模型预测报错:ValueError无法处理PIL.Image输入

解决TensorFlow模型预测时的ValueError:无法处理PIL.Image输入

错误根源

你在测试代码里犯了一个直接的错误——调用model.predict()时传入的是原始的PIL.Image对象test_image,而非你已经预处理好的数组test_image_array。TensorFlow模型仅接受张量或numpy数组作为预测输入,无法直接解析PIL图像对象,这就是报错的核心原因。

修复后的测试代码

修改最后一行的输入参数,替换为处理好的数组即可:

import tensorflow as tf
import os
import numpy as np
model = tf.keras.models.load_model(r'C:\Users\123PC\Desktop\DrawingClassifier\TrainedDrawingModel.h5')
test_image_path = 'face.jpg'
test_image = tf.keras.preprocessing.image.load_img(test_image_path, target_size=(256, 256))
test_image_array = tf.keras.preprocessing.image.img_to_array(test_image)
test_image_array = np.expand_dims(test_image_array, axis=0)
test_image_array /= 255.0
# 传入预处理后的数组而非原始PIL图像
print(model.predict(test_image_array))

额外验证建议

  • 检查输入形状:执行print(test_image_array.shape),输出应为(1, 256, 256, 3),确保和模型定义的输入形状(256,256,3)匹配(第一个维度是批量大小)。
  • 确认图像路径:保证face.jpg在脚本的工作目录下,或直接使用绝对路径避免文件查找失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:32:20