Flipping Images with OpenCV

Samuel Ozechi
2 min readJul 23, 2024

--

Flipping images is one of the easiest processes to apply to images when using the OpenCV library. OpenCV makes it easy to flip images horizontally (mirror effect), vertically or with a combination of both operations in a single function call.

Here’s how to flip images with OpenCV.

  1. Load and display the image to be flipped.
# import OpenCV
import cv2

# load and display the original image
image = cv2.imread('logo.jpg')
cv2.imshow("Original", image)
cv2.waitKey(0)

Output:

Display of the original image

2. Flip the image horizontally using the cv2.flip

# flip the image horizontally
flipped = cv2.flip(image, 1)
cv2.imshow("Flipped Horizontally", flipped)
cv2.waitKey(0)

In this script, the image is flipped using the cv2.flip function, it takes as arguments the image object and a numerical flip code value that defines the flipping operation, typical values are 0 for vertical flip, 1 for horizontal flip (as in our example) and -1 for a combined flip (vertical and horizontal).

Output:

Horizontally flipped version of the original image

What more? We could also flip the image vertically by supplying the appropriate argument.

Flipping the image vertically

# flip the image vertically
flipped = cv2.flip(image, 0)
cv2.imshow("Flipped Vertically", flipped)
cv2.waitKey(0)

Output:

Vertical flipped version of the original image

As you can see, we the image is now flipped vertically (upside down). Finally, we should combine both flip operations in a single function call.

Flip the image Horizontally and Vertically

# flip the image along both axes
flipped = cv2.flip(image, -1)
cv2.imshow("Flipped Horizontally & Vertically", flipped)
cv2.waitKey(0)

Output:

Both horizontal and vertical flips applied to the original image

This time both flips (horizontal and vertical) are applied to the image. That’s about the size of flipping processes in OpenCV.

Summary: In this article, I describe steps in flipping images vertically, horizontally or along both axes by passing certain numerical values (flipcodes) to the cv2.flip function.

--

--

No responses yet