【问题标题】:How to predict a single image with Keras ImageDataGenerator?如何使用 Keras ImageDataGenerator 预测单个图像?
【发布时间】:2020-09-02 10:07:34
【问题描述】:

我已经训练 CNN 对 3 类图像进行分类。 在训练模型时,我使用了 keras 的 ImageDataGenerator 类对图像应用预处理功能并重新缩放它。 现在我的网络在测试集上得到了很好的训练,但我不知道如何将预处理功能应用于单个图像预测。如果我使用 ImageDataGenerator 它会查找目录。 建议我一些替代方法来执行预处理功能并在单个图像上重新缩放。 请参阅下面的代码

训练集:

train_datagen = ImageDataGenerator(preprocessing_function = tf.keras.applications.vgg16.preprocess_input,
                                   rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)
training_set = train_datagen.flow_from_directory('./training_set',
                                                 target_size = (224, 224),
                                                 batch_size = 10,
                                                 class_mode = 'categorical')

测试集:

test_datagen =ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input,                                                            
                                                         rescale = 1./255)
test_set = test_datagen.flow_from_directory('./test_set',
                                            target_size = (224, 224),
                                            batch_size = 10,
                                            shuffle=False,
                                            class_mode = 'categorical') 

现在,我无法在预测之前对单个图像应用预处理功能和重新缩放。 单一预测:

single_datagen = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input,
                                   rescale = 1./255)
single_test = single_datagen.flow_from_directory('./single_prediction/cc.jpg',
                                            target_size = (224, 224),
                                            batch_size = 1,
                                            class_mode = 'categorical') 

错误: NotADirectoryError:[Errno 20] 不是目录:'./single_prediction/cc.jpg'

【问题讨论】:

  • 您确定该目录可以从程序中访问吗?

标签: python image tensorflow keras conv-neural-network


【解决方案1】:

当您希望预测单个图像时,可以使用以下代码。

它会根据火车数据集中的文件夹(类)的排列方式返回每个类的概率列表。因此,返回列表的第一个索引是火车数据集中的第一个文件夹(或类),依此类推。概率最高的索引是您的预测类别。

from keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator
from keras.applications.vgg16 import preprocess_input

#load the image
my_image = load_img('your_single_image.jpeg', target_size=(224, 224))

#preprocess the image
my_image = img_to_array(my_image)
my_image = my_image.reshape((1, my_image.shape[0], my_image.shape[1], my_image.shape[2]))
my_image = preprocess_input(my_image)

#make the prediction
prediction = model.predict(my_image)

您可以使用下面的列表推导将结果四舍五入为整数,从而返回更清晰的结果。

import numpy as np
[np.round(x) for x in prediction]

索引为 1 的元素是您预测的类。

【讨论】:

  • 嘿,你能解释一下 my_image.reshape(...) 行的目的是什么吗?谢谢
  • 好的。首先,观察 VGGNet 模型用于此预处理。 VGGNet 被构建为期望输入图像数组是 4 维的:样本数、X 像素、y 像素和通道数。
  • 谢谢,当我省略该行并尝试预测单个图像时出现输入错误时,我想通了。不管怎么说,还是要谢谢你!您的解决方案非常简单
【解决方案2】:

图像数据生成器查看您指定的目录并在该目录中搜索指定类的子目录。因此,创建一个名为 './single_prediction 的目录。在该目录中创建一个名为 test 的子目录。在名为 test 的子目录中放置要测试的图像。或者,您可以编写一些 python 代码来生成预处理图像。创建一个名为 test 的目录并将图像放入其中。我还没有测试过,但下面的代码应该可以工作。

import cv2
import numpy as np
import os
data_list=[]
dir=r'c:\test'
test_list=os.listdir(dir) # create a list of the files in the directory
batch_size=len(test_list) # determine number of files to process
for f in test_list:  # iterate through the files
    fpath=os.path.join (dir, f) # create path to the image file
    img=cv2.imread(fpath) # read image using cv2
    img=cv2.resize(img, (224,224)) # resize the image
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # cv2 creates bgr images, convert to rgb images
    img=tf.keras.applications.vgg16.preprocess_input(img)   # apply the Vgg16 preprocess function
    data_list.append(img)  # append processed image to the list
data=np.array(data_list)/255 # convert to an np array and rescale images
print (data.shape, batch_size)
predictions=model.predict(data,batch_size=batch_size, verbose=0 )
trials=len (predictions)
for i in range(0,trials):
    predicted_class=predictions[i].argmax() # get index of highest probability
    print (test_list[i], predicted_class) # print file name and class prediction

    

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2017-08-18
    • 2021-07-03
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多