python-kerasHow do I use the Python Keras preprocessing image module?
The Python Keras preprocessing image module is a library for preprocessing images in Keras. It enables you to prepare images for deep learning models.
To use the module, you first need to import it:
from keras.preprocessing import image
The module can be used to load images from the file system, to convert them to numpy arrays, and to resize them.
For example, to load an image from the file system and convert it to a numpy array, you can use the following code:
img = image.load_img('example.jpg', target_size=(224, 224))
x = image.img_to_array(img)
The module also provides functions for image augmentation, such as random rotations, shifts, zoom, and flips. For example, to randomly rotate an image by 90 degrees, you can use the following code:
from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(rotation_range=90)
datagen.fit(x)
The module also provides functions for saving images to the file system. For example, to save an image to the file system, you can use the following code:
image.save_img('example_rotated.jpg', x)
Code explanation
from keras.preprocessing import image
: imports the moduleimg = image.load_img('example.jpg', target_size=(224, 224))
: loads an image from the file system and resizes itx = image.img_to_array(img)
: converts the image to a numpy arrayfrom keras.preprocessing.image import ImageDataGenerator
: imports the ImageDataGenerator classdatagen = ImageDataGenerator(rotation_range=90)
: creates a new ImageDataGenerator object with a rotation range of 90 degreesdatagen.fit(x)
: fits the ImageDataGenerator object to the imageimage.save_img('example_rotated.jpg', x)
: saves the image to the file system
Helpful links
More of Python Keras
- How do I use Python Keras to zip a file?
- How do I use Python and Keras to create a VGG16 model?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I use zero padding in Python Keras?
- How can I use YOLO with Python and Keras?
- 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 can I resolve the issue of Python module Tensorflow.keras not being found?
- How do I install the Python Keras .whl file?
- How do I use a webcam with Python and Keras?
See more codes...