TensorFlow单图推理问题:批量转单图推理无结果
问题分析与解决方案
核心问题
你的单张图片推理代码存在三个关键问题:
- Resize操作未生效:PIL的
resize()方法返回新的图像对象,原对象不会被修改,你没有将结果赋值给变量,导致裁剪后的图片尺寸还是原始大小。 - 缺少批量维度:Keras模型的
predict()方法要求输入数据包含批量维度(即形状为(batch_size, height, width, channels)),而单张图片转成数组后是(96,96,3),不符合输入要求。 - 预处理不一致:批量推理时
image_dataset_from_directory默认会将像素值缩放到[0,1]范围,你的单张图片代码没有做同样的归一化,导致模型输入分布不匹配。
修正后的完整代码
import numpy as np from PIL import Image import tensorflow as tf from tensorflow.keras.utils import img_to_array size = 96 # 从数据库获取参数 image_path = "你的图片路径" xmin, ymin, xmax, ymax = 0, 0, 100, 100 # 替换为实际数据库查询值 # 图片预处理流程 img = Image.open(image_path) img_crop = img.crop((xmin, ymin, xmax, ymax)) # 接收resize返回的新对象,确保尺寸生效 img_resized = img_crop.resize((size, size)) # 转数组+归一化(和批量推理预处理对齐)+添加批量维度 img_array = img_to_array(img_resized) / 255.0 img_array = np.expand_dims(img_array, axis=0) # 形状变为(1,96,96,3) # 加载模型并推理 model_path = '/Volumes/trained_models/classification/exported-models/mobilenet2_mu_classifier_V0.02' loaded_model = tf.keras.models.load_model(model_path) try: prediction_logit = loaded_model.predict(img_array, batch_size=1, verbose=1) # 沿用批量推理的后处理逻辑 probabilities = tf.nn.sigmoid(prediction_logit).numpy().flatten() predictions = tf.where(probabilities < 0.5, 0, 1).numpy() print(f"预测概率: {probabilities[0]}, 预测类别: {predictions[0]}") except tf.errors.ValueError as e: print(f'TF错误详情: {e}')
关键修正点说明
- 生效Resize:将
img_crop.resize((size,size))改为img_resized = img_crop.resize((size, size)),确保图片尺寸被正确调整。 - 添加批量维度:用
np.expand_dims()给数组增加第一个维度,满足模型输入要求。 - 对齐预处理:将像素值除以255.0,和
image_dataset_from_directory的默认行为一致(该API会自动将像素从[0,255]缩放到[0,1])。 - 完善后处理:沿用批量推理时的sigmoid转换和阈值判断,得到最终的类别预测结果。
内容的提问来源于stack exchange,提问作者Tim Fraser
相关产品推荐
相关产品推荐

