how do you output images from a Batchdataset of images in keras

Viewed 4305

After creating a dataset of images using image_dataset_from_directory from keras, how do you get the first image out of the dataset in a numpy format that you can display using pyplot.imshow?

import tensorflow as tf
import matplotlib.pyplot as plt

test_data = tf.keras.preprocessing.image_dataset_from_directory(
    "C:\\Users\\Admin\\Downloads\\kagglecatsanddogs_3367a",
    validation_split=.1,
    subset='validation',
    seed=123)
for e in test_data.as_numpy_iterator():
    print(e[1:])
2 Answers

In the above code e is not an image but rather a tuple containing image and labels.
Code:

plt.figure(figsize=(10, 10))
class_names = test_data.class_names
for images, labels in test_data.take(1):
    for i in range(32):
        ax = plt.subplot(6, 6, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        plt.axis("off")

You can use test_data.take(1) to take a single batch from your test_data and visualize it.

Your output will look something like this: enter image description here

Code: if you are using tensorflow preprocessing image dataset from directory function.

batch_size = 32
img_height = 180
img_width = 180
seed = 123
    
train_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir_train, 
                                                                   labels='inferred', 
                                                                   seed=seed, 
                                                                   batch_size=batch_size, 
                                                                   image_size=(img_width, img_height),
                                                                   label_mode='categorical',
                                                                   subset="training",
                                                                   validation_split=0.2)

class_names = train_ds.class_names

import matplotlib.pyplot as plt

### To visualize the images
plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
  for i in range(batch_size):
    ax = plt.subplot(6, 6, i + 1)
    plt.imshow(images[i].numpy().astype("uint8"))
    plt.title(class_names[np.argmax(labels[i])])
    plt.axis("off")

# Plotting the images
plt.show()
Related