How to Flip Image in Python: Simple Methods Explained
You can flip an image in Python using the
Pillow library with Image.transpose() or using cv2.flip() from OpenCV. These methods let you flip images horizontally, vertically, or both by specifying the flip mode.Syntax
Here are the basic ways to flip images using two popular Python libraries:
- Pillow: Use
Image.transpose(method)wheremethodcan beImage.FLIP_LEFT_RIGHTfor horizontal flip orImage.FLIP_TOP_BOTTOMfor vertical flip. - OpenCV: Use
cv2.flip(src, flipCode)whereflipCodeis1for horizontal,0for vertical, and-1for both flips.
python
from PIL import Image import cv2 # Pillow syntax image = Image.open('image.jpg') flipped_image = image.transpose(Image.FLIP_LEFT_RIGHT) # OpenCV syntax image_cv = cv2.imread('image.jpg') flipped_cv = cv2.flip(image_cv, 1)
Example
This example shows how to flip an image horizontally using Pillow and OpenCV, then save the flipped images.
python
from PIL import Image import cv2 # Flip image horizontally using Pillow image = Image.open('example.jpg') flipped_image = image.transpose(Image.FLIP_LEFT_RIGHT) flipped_image.save('flipped_pillow.jpg') # Flip image horizontally using OpenCV image_cv = cv2.imread('example.jpg') flipped_cv = cv2.flip(image_cv, 1) cv2.imwrite('flipped_opencv.jpg', flipped_cv) print('Images flipped and saved successfully.')
Output
Images flipped and saved successfully.
Common Pitfalls
Common mistakes when flipping images include:
- Using the wrong flip mode number in OpenCV, which can flip the image in an unintended direction.
- Forgetting to save or display the flipped image after processing.
- Not handling file paths correctly, causing file not found errors.
Always check the flip mode and confirm the output visually.
python
import cv2 # Wrong flip code (vertical instead of horizontal) image = cv2.imread('example.jpg') flipped_wrong = cv2.flip(image, 0) # flips vertically cv2.imwrite('flipped_wrong.jpg', flipped_wrong) # Correct flip code flipped_correct = cv2.flip(image, 1) # flips horizontally cv2.imwrite('flipped_correct.jpg', flipped_correct)
Quick Reference
| Library | Function | Flip Mode | Description |
|---|---|---|---|
| Pillow | Image.transpose(method) | Image.FLIP_LEFT_RIGHT | Flip image horizontally |
| Pillow | Image.transpose(method) | Image.FLIP_TOP_BOTTOM | Flip image vertically |
| OpenCV | cv2.flip(src, flipCode) | 1 | Flip image horizontally |
| OpenCV | cv2.flip(src, flipCode) | 0 | Flip image vertically |
| OpenCV | cv2.flip(src, flipCode) | -1 | Flip image both horizontally and vertically |
Key Takeaways
Use Pillow's Image.transpose() with FLIP_LEFT_RIGHT or FLIP_TOP_BOTTOM to flip images easily.
OpenCV's cv2.flip() uses flipCode 1 for horizontal and 0 for vertical flips.
Always verify the flip direction to avoid unexpected results.
Remember to save or display the flipped image after processing.
Handle file paths carefully to prevent errors when loading images.