【问题标题】:Keras.ImageDataGenerator result display [flow()]Keras.ImageDataGenerator 结果显示 [flow()]
【发布时间】:2020-08-11 09:12:06
【问题描述】:

我正在尝试显示由 Imagedatagenerator.flow() 生成的图像,但我无法这样做。

我正在使用单个图像并将其传递给 .flow(img_path) 以生成增强图像,直到总数符合我们的要求:

total = 0
for image in imageGen:
total += 1
if total == 10:
    break

.flow()

imageGen = aug.flow(image_path, batch_size=1,
                      save_to_dir="/path/to/save_dir",
                      save_prefix="", save_format='png')

如何接收在循环中生成的图像,以便在运行时显示它?

【问题讨论】:

    标签: python-3.x tensorflow keras tensorflow2.0


    【解决方案1】:

    如果要使用图片路径可以使用flow_from_directory,并传递包含单个图片的图片文件夹。要从生成器获取图像,请使用dir_It.next() 并访问第一个元素,因为此函数的返回是:

    一个 DirectoryIterator 产生 (x, y) 的元组,其中 x 是一个 numpy 数组,其中包含一批形状为 (batch_size, *target_size, channels) 的图像,y 是一个对应标签的 numpy 数组。

    要显示图像,您可以使用matplotlib 中的plt.imshow 传递批次plt.imshow(img[0]) 的第一个(也是唯一一个)图像。

    目录结构

    ├── data
    │   └── smile
    │       └── smile_8.jpg
    
    # smile_8.jpg shape (256,256,3)
    
    import tensorflow as tf
    from tensorflow import keras
    import matplotlib.pyplot as plt
    
    datagen = keras.preprocessing.image.ImageDataGenerator(
        rescale=1./255,
        rotation_range=180,
        width_shift_range=0.2,
        height_shift_range=0.2,
    )
    
    dir_It = datagen.flow_from_directory(
        "data/",
        batch_size=1,
        save_to_dir="output/",
        save_prefix="",
        save_format='png',
    )
    
    for _ in range(5):
        img, label = dir_It.next()
        print(img.shape)   #  (1,256,256,3)
        plt.imshow(img[0])
        plt.show()
    

    【讨论】:

    • 我确实只想使用 flow() 方法。感谢您提供此解释,但我设法通过放置一个简单的 for 循环并在我的 GUI 上显示相同的图像来使其工作。
    • 很棒的文章@n1colas.m。谢谢!
    • 谢谢@Dicer,我很感激。
    猜你喜欢
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多