Python Pillow flip and rotate images
Flipping and Rotating Images with Python Pillow
When processing images using the Python image processing library, there are cases where you need to flip an existing image to gain more insight, improve its visibility, or for other specific requirements.
The Pillow library’s image module allows us to flip images very easily. We will use the transpose() method in the image module to flip an image. Transpose() “Some of the most commonly used methods supported are
- Image.FLIP_LEFT_RIGHT – Flips an image horizontally.
-
Image.FLIP_TOP_BOTTOM – Flips an image vertically.
-
Image.ROTATE_90 – Rotates an image by a specified number of degrees.
Example 1: Horizontally Flipped Image
The following Python example reads an image, flips it horizontally, and displays both the original and flipped images using standard PNG display tools.
# import required image module
from PIL import Image
# Open an already existing image
imageObject = Image.open("images/spiderman.jpg")
# Do a left and right flip
hori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT)
# Show the original image
imageObject.show()
# Show the horizontally flipped image
hori_flippedImage.show()
Output
Original image
Flipped image
Example 2: Vertically Flipped Image
The following Python example reads an image, flips it vertically, and displays both the original and flipped images using standard PNG display utilities.
# Import the required image module
from PIL import Image
# Open an already existing image
imageObject = Image.open("images/spiderman.jpg")
# Do a left and right flip
hori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT)
# Show the original image
imageObject.show()
# Show the vertically flipped image
Vert_flippedImage = imageObject.transpose(Image.FLIP_TOP_BOTTOM)
Vert_flippedImage.show()
Output
Original Image
Flipped Image
# Import the required image module
from PIL import Image
# Open an already existing image
imageObject = Image.open("images/spiderman.jpg")
# Do a left and right flip
hori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT)
# Show the original image
imageObject.show()
# Show the 90-degree flipped image
degree_flippedImage = imageObject.transpose(Image.ROTATE_90)
degree_flippedImage.show()
Output
Original Image
Rotated Image