Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将图像输入已经训练好的TensorFlow CNN_Python_Tensorflow_Conv Neural Network - Fatal编程技术网

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

Python 将图像输入已经训练好的TensorFlow CNN,python,tensorflow,conv-neural-network,Python,Tensorflow,Conv Neural Network,我对Python有些陌生,对TensorFlow也很陌生。我已经学习了几本教程,我一直坚持着这一点。训练进行得很好,我有一个保存的模型。现在我想加载该模型,并将我自己的一幅图像输入其中。以下是我的尝试: import tensorflow as tf import cv2 from tensorflow import keras model = tf.keras.models.load_model('rps.h5') model.summary() img = cv2.imread('my_h

我对Python有些陌生,对TensorFlow也很陌生。我已经学习了几本教程,我一直坚持着这一点。训练进行得很好,我有一个保存的模型。现在我想加载该模型,并将我自己的一幅图像输入其中。以下是我的尝试:

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()的输出:


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

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

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

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

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

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

将图像重塑为[1300,300,3](批量大小为1)将图像重塑为[1300,300,3](批量大小为1)感谢您的回复!在读取图像后放置该行之后,我得到以下错误。ValueError:layer dense的输入0与层不兼容:输入形状的轴-1应具有值6272,但从colab和ImageDataGenerator接收到形状为[None,32768]的输入,网络的输入为150x150,而不是300x300。另外,你能在你的文章描述中添加摘要输出吗?是的,这让我很困惑,因为训练图像的大小实际上是300x300。你网络的输入大小是150x150。ImageDataGenerator将所有图像的大小调整为150x150。因此,为了使事情顺利进行,您可以在展开dims之前使用img=cv2.resize(img,(150150))。感谢您的回复!在读取图像后放置该行之后,我得到以下错误。ValueError:layer dense的输入0与层不兼容:输入形状的轴-1应具有值6272,但从colab和ImageDataGenerator接收到形状为[None,32768]的输入,网络的输入为150x150,而不是300x300。另外,你能在你的文章描述中添加摘要输出吗?是的,这让我很困惑,因为训练图像的大小实际上是300x300。你网络的输入大小是150x150。ImageDataGenerator将所有图像的大小调整为150x150。因此,为了使事情顺利进行,可以在展开DIM之前使用img=cv2.resize(img,(150150))。