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 validation_data when creating a Keras model in Python?
- How do I use Python Keras to create a Zoom application?
- How do I use Python Keras to perform Optical Character Recognition (OCR)?
- How do I use Python Keras to zip a file?
- How can I use YOLO with Python and Keras?
- How can I improve the validation accuracy of my Keras model using Python?
- How do I check which version of Keras I am using in Python?
- 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 do I use Python's tf.keras.utils.get_file to retrieve a file?
See more codes...