Mirror/Flip Image | OpenCV vs Pillow | Python
In this tutorial, you will learn how to mirror and flip an image using OpenCV (cv2) or Pillow (PIL).
OpenCV
# flip vertically
flipped_cv2_img = cv2.flip(cv2_img, flipCode=0)
# flip horizontally
mirrored_cv2_img = cv2.flip(cv2_img, flipCode=1)
# flip vertically & horizontally (ratate 180 degrees)
rotated_cv2_img = cv2.flip(cv2_img, flipCode=-1)
Pillow
from PIL import Image, ImageOps
# flip vertically
flipped_pil_img = ImageOps.flip(pil_img)
# flip horizontally
mirrored_pil_img = ImageOps.mirror(pil_img)
Full Example
OpenCV
import cv2
# read image
cv2_img = cv2.imread("test_images/test1.jpg")
# flip vertically
flipped_cv2_img = cv2.flip(cv2_img, flipCode=0)
# flip horizontally
mirrored_cv2_img = cv2.flip(cv2_img, flipCode=1)
# flip vertically & horizontally (ratate 180 degrees)
rotated_cv2_img = cv2.flip(cv2_img, flipCode=-1)
# show the images
cv2.imshow("cv2 image (flip vertically)", flipped_cv2_img)
cv2.imshow("cv2 image (flip horizontally)", mirrored_cv2_img)
cv2.imshow("cv2 image (rotated)", rotated_cv2_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Pillow
from PIL import Image, ImageOps
# read image
pil_img = Image.open("test_images/test1.jpg")
# flip vertically
flipped_pil_img = ImageOps.flip(pil_img)
# flip horizontally
mirrored_pil_img = ImageOps.mirror(pil_img)
# show the images
flipped_pil_img.show("pil image (flip vertically)")
mirrored_pil_img.show("pil image (flip horizontally)")
Syntax
OpenCV
cv2.flip(src, flipCode[, dst])
Parameters:
src
: input array.dst
: output array of the same size and type as src.flipCode
: a flag to specify how to flip the array; 0 means flipping around the x-axis and positive value (for example, 1) means flipping around the y-axis. A negative value (for example, -1) means flipping around both axes.
Returns:
- An image (Numpy array)
Pillow
PIL.ImageOps.flip(image)
Parameters:
image
: The image to flip vertically (top to bottom).
Returns:
- An image.
PIL.ImageOps.mirror(image)
Parameters:
image
: The image to mirror horizontally (left to right).
Returns:
- An image.