将图像提供给预先训练的keras模型

时间:2020-07-09 20:00:53

标签: python tensorflow keras

我训练了this模型(从网站上直接粘贴副本)并用model.save()保存了它。 现在,我想用它来对生成的图像进行分类,因此我将它们保存并调整为28x28像素的形状,然后尝试将它们馈送到模型中,如下所示:

from matplotlib import image
img = image.imread('img.png')[:,:,:1] #so that the shape ends up being (28,28,1)
print(self.model.predict(img))

但是当我运行它时,我会遇到很多错误:

警告:tensorflow:为输入Tensor(“ input_1:0”,shape =(None,28,28,1),dtype = float32)构造了形状为(None,28,28,1)的模型,但是它在形状不兼容的输入(无,28、1、1)上被调用。 ...

ValueError: Input 0 of layer dense_12 is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 28]`

我已经做了一些深入的研究,根据这条线,看来输入的形状存在问题:WARNING:tensorflow:Model was constructed with shape (None, 28, 28, 1) for input Tensor("input_1:0", shape=(None, 28, 28, 1), dtype=float32), but it was called on an input with incompatible shape (None, 28, 1, 1)

如何将图像转换为正确的形状?

1 个答案:

答案 0 :(得分:0)

所以我设法修复它,非常简单,但是如果有人遇到问题,我会把它留在这里:

from keras.preprocessing.image import load_img, img_to_array

img = load_img('img.png')
img = img_to_array(img)[:,:,:1]
img = np.expand_dims(img ,axis=0)

这将我的图片的形状更改为(1, 28, 28, 1),这是馈入模型的必要条件