如何将图像加载到TensorFlow中以用于模型?

我刚刚开始学习机器学习,并在使用TensorFlow 1.14。我刚刚使用内置的tensorflow.keras.datasets.mnist数据集创建了我的第一个模型。以下是我的模型代码:

import tensorflow as tffrom tensorflow import kerasmnist = keras.datasets.mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()class Stopper(keras.callbacks.Callback):    def on_epoch_end(self, epoch, log={}):        if log.get('acc') >= 0.99:            self.model.stop_training = True            print('\nReached 99% Accuracy. Stopping Training...')model = keras.Sequential([    keras.layers.Flatten(),    keras.layers.Dense(1024, activation=tf.nn.relu),    keras.layers.Dense(10, activation=tf.nn.softmax)])model.compile(    optimizer=tf.train.AdamOptimizer(),    loss='sparse_categorical_crossentropy',    metrics=['accuracy'])x_train, x_test = x_train / 255, x_test / 255model.fit(x_train, y_train, epochs=10, callbacks=[Stopper()])

现在模型已经训练好了,我可以将x_test图像输入到model.predict()中,这一切运行正常。但我想知道如何将我自己的图像(JPG和PNG)输入到我的模型的predict()方法中?

我查看了文档,但他们的方法对我来说会导致错误。特别是我尝试了以下方法:

img_raw = tf.read_file(<my file path>)img_tensor = tf.image.decode_image(img_raw)img_final = tf.image.resize(img_tensor, [192, 192])^^^ 这一行会抛出错误 'ValueError: 'images' contains no shape.'

请提供一个逐步指南,介绍如何将图像(JPG和PNG)加载到我的模型中进行预测。非常感谢。


回答:

from PIL import Imageimg = Image.open("image_file_path").convert('L').resize((28, 28), Image.ANTIALIAS)img = np.array(img)model.predict(img[None,:,:])

您已经用大小为(28 x 28)的图像训练了模型,因此必须将您的图像调整到相同的大小。您不能使用不同尺寸的图像。

Predict方法需要一批图像,但由于您想对单个图像进行预测,您必须为这张单个图像添加一个额外的批次维度。这可以通过expand_dimreshapeimg[None,:,:]来实现。

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注