如何将图像加载到 tensorflow 中以与模型一起使用?

How to load an image into tensorflow to use with a model?

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

import tensorflow as tf
from tensorflow import keras

mnist = 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 / 255

model.fit(x_train, y_train, epochs=10, callbacks=[Stopper()])

现在模型已经训练完毕,我可以将 x_test 图像输入 model.predict() 并且效果很好。但我想知道如何将我自己的图像(JPG 和 PNG)输入模型的 predict() 方法?

我查看了 documentation,他们的方法对我来说是错误的。特别是我尝试了以下方法:

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])
^^^ This line throws error 'ValueError: 'images' contains no shape.'

请提供将图像(JPG 和 PNG)导入我的模型进行预测的分步指南。非常感谢。

每个图像基本上都是由像素组成的,您可以将这些像素值传递给您的神经网络。

要将图像转换为像素数组,您可以使用 skimage 等库,如下所示。

from skimage.io import imread
imagedata=imread(imagepath)
#you can pass this image to the model

要读取一组图像,请将它们循环并将该数据存储在一个数组中。 此外,您还必须调整大小以标准化所有图片以将它们加载到您的神经网络中。

resized_image = imagedata.resize(preferred_width, preferred_height, Image.ANTIALIAS)     

你也可以选择将图像转为黑白以减少计算量,我这里使用的是常用的图像预处理库pillow库来应用黑白滤镜

from PIL import Image
# load the image
image = Image.open('opera_house.jpg')
# convert the image to grayscale
gs_image = image.convert(mode='L')

预处理的顺序可以是

1. convert images to black and white 
2. resize the images
3. convert them into numpy array using imread  
from PIL import Image
img = 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,:,:]

完成的