【问题标题】:Unable to run model.predict() with image shape same as that which the model was trained on无法以与训练模型相同的图像形状运行 model.predict()
【发布时间】:2021-07-03 09:18:47
【问题描述】:

我正在尝试对我在谷歌 Colab 上设计和训练的 ResNet 模型进行推理,可以找到笔记本的链接here。模型训练的图像维度为 (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)

我已尝试多次卸载并重新安装Tensorflowtf-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() 似乎不起作用。

【问题讨论】:

  • '2021-04-07 19:49:11.821261: I ...' 不是错误,它只是信息性消息。您扩展维度起到了作用,因为 tensorflow predict 需要向量输入。

标签: python-3.x numpy tensorflow opencv deep-learning


【解决方案1】:

在您的 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。

【讨论】:

  • 我已经尝试了您提供的建议,现在错误消息为ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 32, 32) 我认为在这种情况下,openCV 读取图像的方式并不重要,因为所有图像都是黑白的。
猜你喜欢
  • 2018-08-15
  • 1970-01-01
  • 2021-07-03
  • 2015-02-10
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2021-08-05
相关资源
最近更新 更多