Flipping and rotating images are common operations in image manipulation, often used to correct orientation or create visually appealing effects.
With Python's Pillow library, these tasks are straightforward and efficient.
In this tutorial, we will cover:
1. Installing Pillow
Install the Pillow library using pip:
pip install pillow
2. Flipping Images
Flipping an image mirrors it along a specified axis, either horizontally or vertically.
2.1 Horizontal Flip
The transpose() method with Image.FLIP_LEFT_RIGHT flips the image horizontally.
from PIL import Image # Open an image image = Image.open("example.jpg") # Flip horizontally flipped_horizontal = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) # Save and display the result flipped_horizontal.save("flipped_horizontal.jpg") flipped_horizontal.show()
2.2 Vertical Flip
The transpose() method with Image.FLIP_TOP_BOTTOM flips the image vertically.
# Flip vertically flipped_vertical = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) # Save and display the result flipped_vertical.save("flipped_vertical.jpg") flipped_vertical.show()
3. Rotating Images
Pillow allows rotation using both fixed angles and arbitrary angles.
3.1 Rotating at Fixed Angles
The transpose() method provides predefined options for 90°, 180°, and 270° rotations.
# Rotate 90 degrees rotated_90 = image.transpose(Image.Transpose.ROTATE_90) rotated_90.save("rotated_90.jpg") rotated_90.show() # Rotate 180 degrees rotated_180 = image.transpose(Image.Transpose.ROTATE_180) rotated_180.save("rotated_180.jpg") rotated_180.show() # Rotate 270 degrees (or -90 degrees) rotated_270 = image.transpose(Image.Transpose.ROTATE_270) rotated_270.save("rotated_270.jpg") rotated_270.show()
3.2 Rotating by Arbitrary Angles
For arbitrary rotations, use the rotate() method. It rotates the image counterclockwise by a specified angle.
# Rotate by 45 degrees rotated_45 = image.rotate(45, expand=True) # Save and display the result rotated_45.save("rotated_45.jpg") rotated_45.show()
Options for rotate()
- expand=True: Ensures the entire rotated image is included in the output canvas.
- resample: Allows applying filters like Image.Resampling.BILINEAR for smoother results.
rotated_smooth = image.rotate(45, expand=True, resample=Image.Resampling.BILINEAR) rotated_smooth.save("rotated_smooth.jpg") rotated_smooth.show()
4. Combining Flip and Rotate
You can combine flipping and rotating for more complex transformations.
Example: Flip Horizontally and Rotate 90 Degrees
# Flip horizontally flipped = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) # Rotate 90 degrees flipped_and_rotated = flipped.transpose(Image.Transpose.ROTATE_90) # Save and display the result flipped_and_rotated.save("flipped_and_rotated.jpg") flipped_and_rotated.show()
5. Batch Processing
Process multiple images in a directory, flipping or rotating them.
Example: Batch Rotate and Save
import os from PIL import Image def batch_rotate(input_folder, output_folder, angle): os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith((".jpg", ".png", ".jpeg")): img = Image.open(os.path.join(input_folder, filename)) # Rotate the image rotated_img = img.rotate(angle, expand=True) # Save the rotated image rotated_img.save(os.path.join(output_folder, filename)) print(f"Rotated and saved: {filename}") # Rotate all images in 'input_images' folder by 45 degrees batch_rotate("input_images", "output_images", 45)
6. Practical Examples
6.1 Flipping and Rotating for Image Augmentation
Image augmentation is useful in machine learning to increase dataset variety.
import random def augment_image(image_path, output_folder): os.makedirs(output_folder, exist_ok=True) image = Image.open(image_path) # Randomly flip and rotate if random.choice([True, False]): image = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) if random.choice([True, False]): image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) angle = random.randint(0, 360) augmented_image = image.rotate(angle, expand=True) # Save the augmented image augmented_image.save(os.path.join(output_folder, "augmented_image.jpg")) augmented_image.show() # Example usage augment_image("example.jpg", "augmented_images")
6.2 Rotating an Image with a Background Color
When rotating with expand=True, the empty space is transparent. Add a background color to fill the space.
def rotate_with_background(image_path, angle, background_color): image = Image.open(image_path) rotated_image = image.rotate(angle, expand=True, fillcolor=background_color) rotated_image.save("rotated_with_background.jpg") rotated_image.show() # Example usage rotate_with_background("example.jpg", 45, "white")
7. Summary
Key Methods
- Flipping:
- Image.Transpose.FLIP_LEFT_RIGHT
- Image.Transpose.FLIP_TOP_BOTTOM
- Rotating:
- Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, Image.Transpose.ROTATE_270
- rotate(angle, expand=True)
Common Use Cases
- Correcting image orientation.
- Creating augmented datasets for machine learning.
- Generating creative effects for graphics or presentations.
Experiment with these examples to understand how flipping and rotating images can fit into your projects.