python-kerasHow do I use the Python Keras ImageDataGenerator to create batches of image data?
The Python Keras ImageDataGenerator is a powerful tool for creating batches of image data. It can be used to read images from a directory and generate batches of augmented images.
Example code
# Import the ImageDataGenerator
from keras.preprocessing.image import ImageDataGenerator
# Create an ImageDataGenerator and set parameters
datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
# Load images from the directory
generator = datagen.flow_from_directory(
'data/train',
target_size=(150, 150),
batch_size=32,
class_mode='binary'
)
# Generate batches of augmented images
for data_batch, labels_batch in generator:
print('data batch shape:', data_batch.shape)
print('labels batch shape:', labels_batch.shape)
break
Output example
data batch shape: (32, 150, 150, 3)
labels batch shape: (32,)
The code above shows how to use the ImageDataGenerator to create batches of image data:
- Import the ImageDataGenerator from keras.preprocessing.image.
- Create an ImageDataGenerator and set parameters such as rescale, rotation_range, width_shift_range, height_shift_range, shear_range, zoom_range, and horizontal_flip.
- Load images from the directory using the flow_from_directory method.
- Generate batches of augmented images using a for loop.
Helpful links
More of Python Keras
- How do I use Python Keras to zip a file?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How can I install the python module tensorflow.keras in R?
- How can I resolve the issue of Python module Tensorflow.keras not being found?
- How can I use Python and Keras together?
- How do I use zero padding in Python Keras?
- How do I save weights in a Python Keras model?
- How can I use YOLO with Python and Keras?
- How can I use Python with Keras to build a deep learning model?
See more codes...