Search code examples
pythonimage-processingkerasdata-augmentation

Plot images from Image Generator


I'm trying to plot the images created by my image generator. So far this is the code of my data given to the generator:

train_img_gen = train_img_data_gen.flow_from_directory(os.path.join(training_dir, 'images'),
                                                   target_size=(img_h, img_w),
                                                   batch_size=bs, 
                                                   class_mode=None, # Because we have no class subfolders in this case
                                                   shuffle=True,
                                                   interpolation='bilinear',
                                                   seed=SEED)
#edited part following the already existing answer on stackoverflow
x_batch, y_batch = next(train_img_gen)
for i in range (0,32):
    image = x_batch[i]
    plt.imshow(image.transpose(2,1,0))
    plt.show()

I followed this question: Keras images, but without any success.

How can i plot (for example) the first n images generated by my imageGenerator?

EDIT :

I added the code used in the above mentioned question, but i get this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-1a18ce1c1a76> in <module>
     54 valid_gen = zip(valid_img_gen, valid_mask_gen)
     55 
---> 56 x_batch, y_batch = next(train_img_gen)
     57 for i in range (0,32):
     58     image = x_batch[i]

ValueError: too many values to unpack (expected 2)

Solution

  • In the end i solved the problem, it was a problem with dimensions.

    The working code is:

    x= train_img_gen.next()
    for i in range(0,4):
        image = x[i]
        plt.imshow(image)
        plt.show()
    

    The generator returns for each iteration a matrix with shape (4,256,256,3), which means that we have 4 images of size 256x256 and 3 channels (RGB).

    The ImageDataGenerator works with "blocks" of 4 images at time(at least in this case, i have no official reference about how many images does it loads everytime), since its main purpose is to load images on the fly while training the model (avoiding to pre-load a huge amount of data in memory).