python-kerasHow can I use Python and Keras to create an image dataset from a directory?
Creating an image dataset from a directory with Python and Keras is a relatively straightforward process. The following example code block can be used to achieve this:
from keras.preprocessing.image import ImageDataGenerator
# Set the directory where the images are stored
data_dir = 'data/'
# Create the data generator
datagen = ImageDataGenerator(rescale=1./255)
# Load the images from the directory
data_generator = datagen.flow_from_directory(
data_dir,
target_size=(150, 150),
batch_size=32,
class_mode='categorical')
The code above will load the images from the directory specified by data_dir. The images will be resized to 150x150 pixels. The images will also be rescaled to a range of 0-1. The data_generator variable will contain the dataset.
Code explanation
from keras.preprocessing.image import ImageDataGenerator- imports theImageDataGeneratorclass from thekeras.preprocessing.imagemodule.data_dir = 'data/'- sets the directory where the images are stored.datagen = ImageDataGenerator(rescale=1./255)- creates the data generator, with the images rescaled to a range of 0-1.data_generator = datagen.flow_from_directory(data_dir, target_size=(150, 150), batch_size=32, class_mode='categorical')- loads the images from the directory, resizing them to 150x150 pixels, and returns the dataset in thedata_generatorvariable.
Helpful links
More of Python Keras
- How do I check which version of Keras I am using in Python?
- How do I use Python Keras to create a regression example?
- How do I use Python Keras to zip a file?
- How do I use zero padding in Python Keras?
- How can I use Python Keras to create a neural network with zero hidden layers?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I save weights in a Python Keras model?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I install the python module tensorflow.keras in R?
- How do I install Keras on Windows using Python?
See more codes...