Keras.ImageDataGenerator result display [flow()]

Viewed 7738

I am trying to display images generated by the Imagedatagenerator.flow() but I am unable to do so.

I am using a single image and passing that to the .flow(img_path) to generate augmented images by until the total matches our requirement:

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

the .flow()

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

How do I receive the images as they were generating in the loop so that I can display it during the runtime?

1 Answers

If you want to use the image path you can use flow_from_directory, and pass the image folder containing the single image. To obtain the images from the generator use dir_It.next() and access the first element, since the return of this function is:

A DirectoryIterator yielding tuples of (x, y) where x is a numpy array containing a batch of images with shape (batch_size, *target_size, channels) and y is a numpy array of corresponding labels.

To diplay the image you can use plt.imshow from matplotlib passing the first (and only) image of the batch plt.imshow(img[0]).

Foder structure

├── 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()

smile_gen_hstack

Related