繁体   English   中英

如何将图像加载到张量流以与模型一起使用?

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

我刚刚开始学习机器学习并且正在使用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()方法中?

我看了看文档 ,他们的方法对我造成了错误。 我特别尝试了以下方法:

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

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

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

您也可以选择将图像转换为黑白图像以减少计算量,我使用的是枕头库,这里是一个常见的图像预处理库,可以应用黑白滤镜

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)的图像训练了模型,因此必须将图像调整为相同大小。 您不能使用其他尺寸的图像。

预测需要一批图像,但是由于要对单个图像进行预测,因此必须为该单个图像添加批次的其他尺寸。 这可以通过expand_dimreshapeimg[None,:,:]

暂无
暂无

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

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