python-3.x - 无法以与模型训练的图像形状相同的图像形状运行 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()
似乎不起作用。
解决方案
在您的 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。
推荐阅读
- android - 失败 INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
在 Android 上运行 cordova 应用程序时权限为空 - python - QGIS / GDAL / Python:QgsVectorLayer光栅化期间的TypeError
- python - Python,获取特定日期的股票数据
- react-native - fetch API (Error) 得到相同的结果
- spring - 启动tomcat服务器spring boot时出现错误
- c++ - 使用什么设计模式或编程技术将数据流与控制流分开?
- javascript - 将字符串转换为数组 JavaScript 中的数字
- firebase - 带有 VueJS 2 数据的 Firestore where 子句
- java - 在测试范围内验证微服务有多糟糕?[JAVA]
- loops - 如何根据参与者的反应选择例程是否继续?