简体   繁体   English

将图像馈送到预训练的 keras model

[英]feeding an image to a pretrained keras model

I trained this model (straight up copy paste from the website) and saved it with model.save() .我训练了这个model (直接从网站复制粘贴)并用model.save()保存它。 I now want to use it to classify images that I generate so I save them and reshape them to 28x28 pixels and then attempt to feed them to the model like so:我现在想用它来分类我生成的图像,所以我保存它们并将它们重塑为 28x28 像素,然后尝试将它们提供给 model,如下所示:

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))

But when I run this i get a bunch of errors:但是当我运行它时,我得到了一堆错误:

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).警告:tensorflow:Model 是用形状 (None, 28, 28, 1) 构造的,用于输入张量 ("input_1:0", shape=(None, 28, 28, 1), dtype=float), but it was called2 on),形状不兼容的输入 (None, 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]`

I've done some digging around and it seems there's an issue with the shape of the input, according to this line: 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)我已经做了一些挖掘,似乎输入的形状存在问题,根据这一行: 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)

How do I convert my image into the correct shape?如何将我的图像转换为正确的形状?

So i managed to fix it, embarassingly easy but i will leave this here in case anyone else has an issue:所以我设法修复它,非常容易,但我会把它留在这里,以防其他人有问题:

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)

this changed the shape of my image to (1, 28, 28, 1) which is what was needed to feed to the model这将我的图像的形状更改为(1, 28, 28, 1) ,这是输入 model 所需的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM