Python Pillow – Flipping and Rotating Images
Python Pillow – Flipping and Rotating Images
Python Pillow, or PIL, is a Python library that provides image editing and manipulation capabilities. The image module provides functions for flipping and rotating images. image.transpose() is a function that rotates and flips an image, and its argument is a required keyword.
Syntax:
image.transpose(appropriate keyword)
In the following example, we will use an appropriate keyword to explore all possible rotations.
Images used:
Flipping an Image
- Counterclockwise: To flip an image counterclockwise, pass the Image.TRANSPOSE keyword.
Syntax:img.transpose(Image.TRANSPOSE)
Example:
from PIL import Image
img = Image.open('geek.jpg')
# flip anti-clockwise
flip_img = img.transpose(Image.TRANSPOSE)
flip_img.show()
Output:
Clockwise: To flip an image clockwise, pass the keyword Image.TRANSVERSE..
Syntax:img.transpose(Image.TRANSVERSE)
Example:
from PIL import Image
img = Image.open('geek.jpg')
# flip clockwise
flip_img = img.transpose(Image.TRANSVERSE)
flip_img.show()
Output:
Horizontal Flip: For horizontal flipping, pass Image.FLIP_LEFT_RIGHT as the key.
Syntax: img.transpose(Image.FLIP_LEFT_RIGHT)
Example:
from PIL import Image
img = Image.open('geek.jpg')
# flip horizontal
flip_img = img.transpose(Image.FLIP_LEFT_RIGHT)
flip_img.show()
Output:
Vertical Flip: Use image.FLIP_TOP_BOTTOM as the keyword to perform a vertical flip.
Syntax:img.transpose(Image.FLIP_TOP_BOTTOM)
Example:
from PIL import Image
img = Image.open('geek.jpg')
# flip vertically
flip_img = img.transpose(Image.FLIP_TOP_BOTTOM)
flip_img.show()
Output:
from PIL import Image
img = Image.open('geek.jpg')
# Rotate by 90 degrees
rot_img = img.transpose(Image.ROTATE_90)
rot_img.show()
Output:
Rotate 180 degrees: The keyword for rotating 180 degrees is Image.ROTATE_180.
Syntax: img.transpose(Image.ROTATE_180)
Example:
from PIL import Image
img = Image.open('geek.jpg')
# Rotate by 180 degrees
rot_img = img.transpose(Image.ROTATE_180)
rot_img.show()
Output:
Rotate 270 degrees: To rotate 270 degrees, use the keyword Image.ROTATE_270.
Syntax: img.transpose(Image.ROTATE_270)
Example:
from PIL import Image
img = Image.open('geek.jpg')
# Rotate by 270 degrees
rot_img = img.transpose(Image.ROTATE_270)
rot_img.show()
Output: