【问题标题】:Keras showing images from data generatorKeras 显示来自数据生成器的图像
【发布时间】:2017-06-01 10:33:32
【问题描述】:

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

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

【问题讨论】:

  • 您也可以显示数据生成的代码吗?例如,有一个选项 channel_shift_range。默认情况下它是 0,但如果你将它设置为其他值,它可能会弄乱颜色。
  • 我认为你应该拆分这个问题。颜色失真是关于 Keras 的。从目录中获取文件名完全是一个不同的问题。这只是 python 标准库。
  • 也就是说:我非常喜欢 glob 模块。 glob.glob("path/*.png") 将返回目录中所有 .png 文件的列表
  • 看看。 @ihk 我想要 datagen 处理的文件名,而不仅仅是目录中的文件
  • 我明白了。我仍然认为这应该是两个独立的问题

标签: python image matplotlib neural-network keras


【解决方案1】:
  1. 至少有三种方法可以拥有这种扭曲的颜色。所以:

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

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

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

【讨论】:

  • 我遵循了这两个建议,但它似乎仍然不起作用:我试过了:for i in range(0,1): image = x[i] # image = image - 255 rgb = np.fliplr(image.reshape(-1,3)).reshape(image.shape) plt.imshow(image.transpose(1,2,0)) print(y[i]) plt.show()
  • 试试 '255 - image'.first.
  • 对不起,我的方程式是错误的。我做了 x = x-255,它应该是 x = 255-x。我看到正常的颜色,但在某些区域我仍然有奇怪的颜色。请查看编辑。
  • 尝试关闭所有图像转换 - 我想这就是奇怪颜色背后的原因
  • 我做了val_generator = ImageDataGenerator().flow_from_directory( path+'/valid', target_size=(224, 224), batch_size=batch_size,) 但我仍然得到同样的奇怪点
【解决方案2】:

颜色问题比较奇怪。 一旦我可以访问我的 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 机器上。可能有一个小的语法错误。

【讨论】:

    【解决方案3】:

    我遇到了与 OP 相同的问题,并通过将像素从 0-255 重新缩放到 0-1 来解决它。

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

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

    【讨论】:

      【解决方案4】:

      你的图像数组的dtype是'float32',只要把它转换成'uint8':

      plt.imshow(image.astype('uint8'))
      

      【讨论】:

        【解决方案5】:
        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)
        

        它对我有用。

        【讨论】:

          【解决方案6】:

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

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

          【讨论】:

            猜你喜欢
            • 2018-02-09
            • 2019-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-05-19
            • 1970-01-01
            • 2018-04-02
            • 1970-01-01
            相关资源
            最近更新 更多