How to Flip Image Using OpenCV in Computer Vision
To flip an image in OpenCV, use the
cv2.flip() function with the image and a flip code: 0 for vertical, 1 for horizontal, and -1 for both axes. This function returns the flipped image which you can display or save.Syntax
The cv2.flip() function syntax is:
cv2.flip(src, flipCode)
Where:
srcis the source image to flip.flipCodedetermines the flip direction:0for vertical flip,1for horizontal flip, and-1for both vertical and horizontal flips.
python
flipped_image = cv2.flip(src, flipCode)
Example
This example loads an image, flips it horizontally, vertically, and both ways, then displays all results in separate windows.
python
import cv2 # Load image from file image = cv2.imread('input.jpg') if image is None: print('Error: Image not found or unable to load.') else: # Flip horizontally flip_horizontal = cv2.flip(image, 1) # Flip vertically flip_vertical = cv2.flip(image, 0) # Flip both axes flip_both = cv2.flip(image, -1) # Show images cv2.imshow('Original', image) cv2.imshow('Flip Horizontal', flip_horizontal) cv2.imshow('Flip Vertical', flip_vertical) cv2.imshow('Flip Both', flip_both) cv2.waitKey(0) cv2.destroyAllWindows()
Output
Four windows open showing the original image and the three flipped versions.
Common Pitfalls
Common mistakes when flipping images with OpenCV include:
- Using incorrect
flipCodevalues other than 0, 1, or -1, which will not flip the image as expected. - Not checking if the image loaded correctly before flipping, which can cause errors.
- Forgetting to call
cv2.waitKey()andcv2.destroyAllWindows()aftercv2.imshow(), so windows may not display or close properly.
python
import cv2 image = cv2.imread('input.jpg') if image is None: print('Error: Image not found or unable to load.') else: # Wrong flipCode example (no flip) flip_wrong = cv2.flip(image, 2) # Invalid flipCode # Correct flipCode flip_correct = cv2.flip(image, 1) # Horizontal flip cv2.imshow('Wrong FlipCode', flip_wrong) cv2.imshow('Correct FlipCode', flip_correct) cv2.waitKey(0) cv2.destroyAllWindows()
Output
The 'Wrong FlipCode' window shows the original image unchanged; 'Correct FlipCode' shows the horizontally flipped image.
Quick Reference
| Flip Code | Flip Direction |
|---|---|
| 0 | Flip vertically (upside down) |
| 1 | Flip horizontally (mirror image) |
| -1 | Flip both vertically and horizontally |
Key Takeaways
Use cv2.flip(image, flipCode) with flipCode 0, 1, or -1 to flip images vertically, horizontally, or both.
Always check if the image loaded successfully before flipping to avoid errors.
Remember to use cv2.waitKey() and cv2.destroyAllWindows() to properly display and close image windows.
Invalid flipCode values will not flip the image and may cause confusion.
Flipping images is useful for data augmentation and image preprocessing in computer vision.