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

Keras showing images from data generator

我正在像这样使用 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()

这显示了错误的颜色:

我有两个问题。

  1. 如何解决问题

  2. 如何获取文件的文件名(以便我可以自己从 matplotlib 之类的东西中读取它)

编辑:这是我的数据生成器的样子

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
)

编辑 2:

按照 Marcin 的回答:

image = 255 - image

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

  1. 至少有三种方法可以使颜色扭曲。所以:

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

    您需要检查您的情况会发生哪些选项。

  2. 为了自己获取图像,我通常使用(当你的文件夹具有适合 Keras 的格式时 flow_from_directory)我通常使用 os.listdir 的混合os.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.
    

颜色问题比较奇怪。 一旦我可以访问我的 linux 机器,我将尝试重现它。

对于问题的文件名部分,我想对 Keras 源代码提出一个小改动:

您可能想看看这个文件: https://github.com/fchollet/keras/blob/master/keras/preprocessing/image.py 它包含图像预处理例程。

查看第 820 行,DirectoryIteratornext() 函数:调用此函数以从目录中获取新图像。

在那个函数里面,看第838行,如果save_to_dir已经被设置为一个路径,生成器会将增强后的图像输出到这个路径,用于调试目的。 增强图像的名称是索引和哈希的混合。对你没用。

但是您可以很容易地更改代码:

filenames=[] #<-------------------------------------------- new code
for i, j in enumerate(index_array):
    fname = self.filenames[j]
    img = load_img(os.path.join(self.directory, fname),
                   grayscale=grayscale,
                   target_size=self.target_size)
    x = img_to_array(img, dim_ordering=self.dim_ordering)
    x = self.image_data_generator.random_transform(x)
    x = self.image_data_generator.standardize(x)

    filenames.append(fname) # <-----------------------------store the used image's name
    batch_x[i] = x
# optionally save augmented images to disk for debugging purposes
if self.save_to_dir:
    for i in range(current_batch_size):
        img = array_to_img(batch_x[i], self.dim_ordering, scale=True)
        #fname = '{prefix}_{index}_{hash}.{format}'.format(prefix=self.save_prefix,
        #                                                  index=current_index + i,
        #                                                  hash=np.random.randint(1e4),
        #                                                  format=self.save_format)
        fname=filenames[i] # <------------------------------ use the stored code instead
        img.save(os.path.join(self.save_to_dir, fname))

现在增强图像以原始文件名保存。

这应该允许您以原始文件名保存图像。 好的,您实际上如何将其注入 Keras 源代码?

这样做:

  1. 克隆 Keras:git clone https://github.com/fchollet/keras
  2. 转到我上面链接的源文件。做出改变。
  3. 欺骗您的 python 代码以导入更改的代码而不是 pip 安装的版本。

.

# this is the path to the cloned repository
# if you cloned it next to your script
# then just use keras/
# if it's one folder above
# then use ../keras/
sys.path.insert(0, os.getcwd() + "/path/to/keras/")

import keras

现在 DirectoryIterator 是你的补丁版本。

我希望这能奏效,我目前在 windows。我的 python 堆栈仅在 linux 机器上。可能有一个小的语法错误。

我遇到了与 OP 相同的问题,通过将像素从 0-255 重新调整为 0-1 解决了这个问题。

Keras 的 ImageDataGenerator 采用 'rescale' 参数,我将其设置为 (1/255)。这产生了具有预期颜色的图像

image_gen = ImageDataGenerator(rescale=(1/255))

你的图像数组的数据类型是'float32',只需将它转换成'uint8':

plt.imshow(image.astype('uint8'))
from skimage import io

def imshow(image_RGB):
  io.imshow(image_RGB)
  io.show()

x,y = train_generator.next()

for i in range(0,11):
    image = x[i]
    imshow(image)

对我有用。

如果您使用目录中的 test_batches=Imagedatagenerator().flow,请提供一些建议。如果您使用它来提供预测生成器,请确保设置 shuffle=false 以保持文件与相关预测之间的相关性。如果目录中有数字标记的文件,例如 1.jpg2.jpg 等。不会获取图像正如你所想的。它们按以下顺序获取: 1.jpg, 10.jpg, 2.jpg, 20.jpg 等。这使得很难将预测与特定文件相匹配。您可以通过使用 0 的填充来解决这个问题,例如 01.jpg02.jpg 等。在第二部分问题“我怎样才能得到生成器生成的文件你可以得到这些文件如下:

for file in datagen.filenames:
        file_names.append(file)