将图像输入已经训练好的TensorFlow CNN



我对Python有些陌生,对TensorFlow也很陌生。我已经遵循了几个教程,我被这个colab和这个视频卡住了。训练进行得很完美,我保存了一个模型。现在我想加载该模型,并将我自己的一张图像输入其中

import tensorflow as tf
import cv2
from tensorflow import keras
model = tf.keras.models.load_model('rps.h5')
model.summary()
img = cv2.imread('my_hand_paper.png')
print(model.predict_classes(img))

但我得到以下错误:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 300, 3]

我的图像是300x300,就像训练图像一样。我想问题是我必须以与训练数据类似的方式准备图像,但我不确定如何准备。训练数据就是这样准备的:

training_datagen = ImageDataGenerator(
rescale = 1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
train_generator = training_datagen.flow_from_directory(
TRAINING_DIR,
target_size=(150,150),
class_mode='categorical',
batch_size=126)

summary((的输出:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 148, 148, 64)      1792      
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 74, 74, 64)        0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 72, 72, 64)        36928     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 36, 36, 64)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 34, 34, 128)       73856     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 17, 17, 128)       0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 15, 15, 128)       147584    
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 7, 7, 128)         0         
_________________________________________________________________
flatten (Flatten)            (None, 6272)              0         
_________________________________________________________________
dropout (Dropout)            (None, 6272)              0         
_________________________________________________________________
dense (Dense)                (None, 512)               3211776   
_________________________________________________________________
dense_1 (Dense)              (None, 3)                 1539      
=================================================================
Total params: 3,473,475
Trainable params: 3,473,475
Non-trainable params: 0
_________________________________________________________________

当您想在推理中使用网络时,您仍然需要使用批量大小。在您的情况下,批量大小为1。

您可以使用以下代码添加批次:

img = cv2.resize(img, (150,150))    
img = tf.expand_dims(img , 0)

最新更新