在keras中使用predict_generator()时如何获取关联的图像名称

时间:2018-04-23 04:20:49

标签: python machine-learning neural-network deep-learning keras

test_batches = ImageDataGenerator(
    preprocessing_function=preprocess_input
).flow_from_directory(test_path,target_size=(224,224),batch_size=1,class_mode=None,shuffle = "false")
prediction = model.predict_generator(test_batches, steps=1, verbose=1)
np.argmax(prediction)

所以我在这里使用step_size = 1和steps = 1来测试一个图像。每当我运行这个时,我会得到不同的预测,这意味着每次都不会选择相同的图像。如何查看图像名称?

编辑:这是解释我所面临问题的另一种尝试:

test_batches = ImageDataGenerator(
    preprocessing_function=preprocess_input
).flow_from_directory(test_path,target_size=(224,224),batch_size=2,class_mode=None,shuffle = "false")
prediction = model.predict_generator(test_batches, steps=1, verbose=2)

预测变量具有两个预测概率阵列。我怎么知道这些预测的图像是什么?

2 个答案:

答案 0 :(得分:1)

  • 如果你的目标是熟悉keras ImageDataGenerators:

如果您希望您的生成器始终返回相同的图像(为了可重复性):

from keras.preprocessing.image import ImageDataGenerator
import numpy as np

data_dir = 'path/to/image/directory'  # path to the directory where the images are stored
index = 0  # select a number here

ig = ImageDataGenerator()
gen = ig.flow_from_directory(data_dir, batch_size=1)  # if you want batch_size > 1 you need to
                                                      # add as many indices as your batch_size.
image, label = gen._get_batches_of_transformed_samples(np.array([index]))
image_name = gen.filenames[index]
# do whatever you want with your image and label

如果您希望您的生成器始终返回随机图片,但知道它是哪一个我建议您执行以下操作:

index = next(gen.index_generator)
image, label = gen._get_batches_of_transformed_samples(index)
image_name = gen.filenames[index]
  • 如果您想了解predict_generator的工作原理,那么这些方法都无法帮到您。我唯一能想到的就是编辑DirectoryIterator code

例如,您可以添加一行来打印您传递的图像的名称。我建议在line 1434之后添加以下语句:

print(fname)

答案 1 :(得分:0)

您可以使用generator.filename属性

CRUD