使用Keras的ImageDataGenerator预测单个图像 [英] Predicting a single image with Keras' ImageDataGenerator

查看:112
本文介绍了使用Keras的ImageDataGenerator预测单个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对深度学习还很陌生,所以请原谅我这个可能很简单的问题.

I'm very new to deep learning so please forgive me for this probably simple question.

我训练了一个网络来对进行分类.为了简化图像生成和拟合过程,我使用了 ImageDataGenerator fit_generator 函数,如下所示:

I trained a network to classify between positive and negative. To simplify the image generation and fitting process I used a ImageDataGenerator and the fit_generator function, as shown below:

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# Simplified model
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(12, 12, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

# Image import, for 'validation_generator' equally
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    './training/',
    target_size=(12, 12),
    batch_size=128,
    class_mode='binary')

# Compiling
model.compile(loss='binary_crossentropy',
             optimizer='adam',
             metrics=['acc'])

# Fitting, for Tensorboard 'history = model.fit_gen...'
model.fit_generator(train_generator,
                    steps_per_epoch=8,
                    epochs=50,
                    verbose=1,
                    validation_data = validation_generator,
                    validation_steps=8,
                    callbacks=[tb]) # Standard Tensorboard

我想用我的模型预测单个图像(导入为 numpy array ),如下所示:

I want to use my model to predict a single image (imported as numpy array) as shown below:

image = 'single imported image with shape (12, 12, 3)'
model.predict(image)

但是,我唯一得到的是一条错误消息,指出了 Matrix size-incompatible .我已经在我的 validation_generator 上尝试过 model.predict_generator()了,但是可以使用,但是不是一张图片.

However, the only thing I get is an error message stating the Matrix size-incompatible. I have tried model.predict_generator() on my validation_generator which works, but that isn't a single image.

谢谢.

推荐答案

如果要对单个图像进行预测,请执行以下操作:

If you want to do a prediction on a single image, do the following:

image = np.random.rand(12, 12, 3) # single imported image with shape (12, 12, 3)
image = np.expand_dims(image, axis=0) # image shape is (1, 12, 12, 3)
model.predict(image)

换句话说,您的模型仍然期望输入形状为(无,12、12、3).因此,在进行预测之前,请将图像的尺寸扩展为单个图像的批处理.

In other words, your model still expects input shape of (None, 12, 12, 3). So, before doing the prediction, expand the dimensions of the image to be a batch of a single image.

这篇关于使用Keras的ImageDataGenerator预测单个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆