Extract an array of images and corresponding labels using Keras’ flow_from_directory method

Posted by

Keras: Obtain array of images and labels from flow_from_directory

Keras: Obtain array of images and labels from flow_from_directory

In Keras, the flow_from_directory method is a powerful tool for loading images and their associated labels from a directory. This method is commonly used in deep learning tasks involving image classification and object detection.

Here’s how to use the flow_from_directory method to obtain an array of images and labels:

    
import numpy as np
from keras.preprocessing.image import ImageDataGenerator

# Define the directory containing the images
image_dir = 'path_to_image_directory'

# Create an instance of the ImageDataGenerator
datagen = ImageDataGenerator()

# Use the flow_from_directory method to obtain the array of images and labels
data_flow = datagen.flow_from_directory(directory=image_dir, target_size=(224, 224), batch_size=32)

# Extract the images and labels from the data_flow
images, labels = next(data_flow)

# Normalize the images
images = images / 255.0

# Print the shape of the images and labels array
print('Images shape:', images.shape)
print('Labels shape:', labels.shape)
    
    

In the above code, we first define the directory containing the images. We then create an instance of the ImageDataGenerator class and use the flow_from_directory method to obtain the array of images and labels. We can then normalize the images and print out the shape of the images and labels array.

By using the flow_from_directory method, we can easily load images and their associated labels from a directory, making it convenient for training deep learning models in Keras.

Overall, the flow_from_directory method is an essential tool in the Keras library for working with image data and labels, and provides a straightforward way to obtain arrays of images and labels for use in training deep learning models.