'Plot random image from the ImageDataGenerator

I'm trying to plot an image according to the generated random number from ImageDataGenerator and I was not able to plot the image due to errors.

test_datagen = ImageDataGenerator(
    preprocessing_function=preprocess_input)

test_gen = test_datagen.flow_from_directory(test_path,
                                            target_size = (SIZE, SIZE),
                                            batch_size = 32, shuffle=False )    

i = random.randint(0,800)
    
batch=next(test_gen)  
print(batch[0].shape) 
img=batch[0][i]   
print (img.shape)
plt.imshow(img) 

I've tried the solution from here, which is used above, however it gives me error when the randomly generated number is high.

IndexError: index 523 is out of bounds for axis 0 with size 32

Note:

  • I don't want the image to be plotted randomly by changing the shuffle=True, I want to plot the image according to the randomly generated number.
  • I don't want to change the range of the generating random number and it needs to be the given value.(0,800)


Solution 1:[1]

You are using a batch size of 32.

So, when you are generating a random number with i = random.randint(0,800), you are generating an integer between [0,800], which exceeded your batch of images (This is what the error said basically, you generated 523 and it is out of bounds for the batch where there are only 32 images)

Try to write i = random.randint(0,31)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Toby