Last modified: Apr 21, 2025 By Alexander Williams

Python Image Flipping: Horizontal and Vertical

Flipping images is a common task in image processing. Python offers easy ways to flip images horizontally or vertically. This guide will show you how.

Why Flip Images?

Image flipping is useful for data augmentation, correcting orientation, or creating visual effects. It's often used in image analysis and image recognition.

Methods to Flip Images in Python

Two popular libraries can flip images: PIL (Pillow) and OpenCV. Both are simple to use.

1. Using PIL (Pillow)

Pillow is a friendly library for basic image operations. Install it with pip install pillow.


from PIL import Image

# Open an image
img = Image.open('sample.jpg')

# Flip horizontally
horizontal_img = img.transpose(Image.FLIP_LEFT_RIGHT)

# Flip vertically
vertical_img = img.transpose(Image.FLIP_TOP_BOTTOM)

# Save flipped images
horizontal_img.save('horizontal_flip.jpg')
vertical_img.save('vertical_flip.jpg')

The transpose() method handles flipping. Use FLIP_LEFT_RIGHT for horizontal and FLIP_TOP_BOTTOM for vertical.

2. Using OpenCV

OpenCV is powerful for advanced image processing. Install it with pip install opencv-python.


import cv2

# Read an image
img = cv2.imread('sample.jpg')

# Flip horizontally
horizontal_img = cv2.flip(img, 1)

# Flip vertically
vertical_img = cv2.flip(img, 0)

# Save flipped images
cv2.imwrite('horizontal_flip.jpg', horizontal_img)
cv2.imwrite('vertical_flip.jpg', vertical_img)

The flip() function takes two arguments: the image and a flip code. Use 1 for horizontal and 0 for vertical.

Comparing PIL and OpenCV

Pillow is simpler for basic tasks. OpenCV offers more control and is faster for large images. Choose based on your needs.

Practical Example

Let's flip an image and display both versions. We'll use matplotlib to show the results.


import matplotlib.pyplot as plt
from PIL import Image

# Open and flip image
img = Image.open('sample.jpg')
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)

# Display both images
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('Original')

plt.subplot(1, 2, 2)
plt.imshow(flipped_img)
plt.title('Flipped')

plt.show()

This code creates a side-by-side comparison. It helps visualize the flipping effect.

Common Use Cases

Image flipping is often used in:

  • Data augmentation for machine learning
  • Creating mirror effects
  • Correcting camera orientation issues

For more advanced operations, check our image rescaling guide.

Conclusion

Flipping images in Python is simple with PIL or OpenCV. Both methods work well for horizontal and vertical flips. Choose PIL for simplicity or OpenCV for performance.

Remember to save your flipped images properly. This basic skill is useful in many image processing tasks.