首页 > 解决方案 > 无法以与模型训练的图像形状相同的图像形状运行 model.predict()

问题描述

我正在尝试对我在谷歌 Colab 上设计和训练的 ResNet 模型进行推理,可以在此处找到笔记本的链接。模型训练的图像的维度是 (32, 32, 3)。训练后,我将模型保存为SavedModel格式,以便我可以在我的机器上运行推理。我使用的代码是

import tensorflow as tf
import cv2 as cv
from resize import resize_to_fit

image = cv.imread('extracted_letter_images/001.png')
image_resized = resize_to_fit(image, 32, 32)
model = tf.keras.models.load_model('Model/CAPTCHA-Model')
model.predict(image_resized)

resize_to_fit方法将图像大小调整为 32x32px。返回图像的形状也是 (32, 32, 3)。调用该model.predict()函数时,显示以下错误消息

ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (32, 32, 3)

我已经尝试卸载和重新安装Tensorflow以及tf-nightly多次无济于事。我什至尝试用这个扩展图像的尺寸

image_resized = np.expand_dims(image_resized, axis=0)

这导致图像具有尺寸 (1, 32, 32, 3)。进行上述更改时,将显示以下错误消息

2021-04-07 19:49:11.821261: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:180] None of the MLIR Optimization Passes are enabled (registered 2)

我感到困惑的是,调整大小的图像的尺寸和用于训练模型的图像的尺寸是相同的,但model.predict()似乎不起作用。

标签: python-3.xnumpytensorflowopencvdeep-learning

解决方案


在您的 ImageDataGenerators 中,您使用了预处理函数 tf.image.rgb_to_grayscale。这将图像转换为 32 X 32 X 1。因此,您必须对要预测的图像进行相同的转换。您还将图像重新缩放到 0 到 1 的范围内,因此您还必须重新缩放要预测的图像。代码 image_resized = np.expand_dims(image_resized, axis=0) 是正确的。不确定他是否会成为问题,但请注意 cv2 将图像读取为 BGR 而不是 RGB,因此在应用 tf.image.rgb_to_grayscale 之前,首先使用 image= cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 将图像转换为 RGB。


推荐阅读