Keras显示来自数据生成器的图像

har*_*ash 7 python image matplotlib neural-network keras

我正在使用像这样的keras图像生成器:

val_generator = datagen.flow_from_directory(
        path+'/valid',
        target_size=(224, 224),
        batch_size=batch_size,)

x,y = val_generator.next()
for i in range(0,1):
    image = x[i]
    plt.imshow(image.transpose(2,1,0))
    plt.show()
Run Code Online (Sandbox Code Playgroud)

这显示错误的颜色: 在此输入图像描述

我有两个问题.

  1. 如何解决问题

  2. 如何获取文件的文件名(以便我可以自己从matplotlib这样的东西读取)

编辑:这就是我的datagen的样子

datagen = ImageDataGenerator(
    rotation_range=3,
#     featurewise_std_normalization=True,
    fill_mode='nearest',
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True
)
Run Code Online (Sandbox Code Playgroud)

编辑2:

遵循Marcin的回答后:

image = 255 - image
Run Code Online (Sandbox Code Playgroud)

我得到正常的颜色,但仍然有一些奇怪的颜色:

在此输入图像描述

小智 6

图像数组的dtype为'float32',只需将其转换为'uint8'即可:

plt.imshow(image.astype('uint8'))
Run Code Online (Sandbox Code Playgroud)


Mar*_*jko 3

  1. 至少有三种方法可以实现这种扭曲的颜色。所以:

    • 一种选择是您需要像这个问题一样切换颜色顺序。
    • 其次,您可能会将图片制作为负片(每个通道都会通过255 - x变换进行变换),在使用某些 GIS 库时有时会发生这种情况。
    • 您还可以使用score/255转换。

    您需要检查您的情况会出现哪些选项。

  2. 为了自己获取图像,我通常使用(当你的文件夹具有适合 Keras 的格式时)我通常使用和byflow_from_directory的组合:os.listdiros.path.join

    list_of_labels = os.listdir(path_to_dir_with_label_dirs)
    for label in list_of_labels:
        current_label_dir_path = os.path.join(path_to_dir_with_label_dirs, label
        list_of_images = os.listdir(current_label_dir_path)
        for image in list_of_images:
            current_image_path = os.path.join(current_label_dir_path, image)
            image = open(current_image_path) # use the function which you want.
    
    Run Code Online (Sandbox Code Playgroud)