【问题标题】:How to load an image into tensorflow to use with a model?如何将图像加载到张量流中以与模型一起使用?
【发布时间】:2019-11-20 23:32:07
【问题描述】:

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

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)导入我的模型以进行预测的分步指南。非常感谢。

【问题讨论】:

    标签: python machine-learning keras tf.keras


    【解决方案1】:
    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) 的图像训练模型,因此必须将图像大小调整为相同。您不能使用不同维度的图像。

    预测需要一批图像,但由于您想对单个图像进行预测,因此您必须为该单个图像添加一个额外的批处理维度。这是由expand_dimreshapeimg[None,:,:] 完成的

    【讨论】:

    • 非常感谢您的回复。我运行了你给我的代码,我可以看到图像已成功加载到 np.array 但是当我运行 model.predict(img) 它仍然抛出错误:@ 987654326@ 据我所知@不应该是这种情况@ 987654327@ 层将我的 28 x 28 数组变成 728 大小的数组。
    • @ArchitKithania 你必须为批次添加一个额外的维度。更新了答案。
    【解决方案2】:

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

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

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

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

    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  
    

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 2021-10-25
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2018-09-29
      相关资源
      最近更新 更多