Flip Image with OpenCV


Python OpenCV - Flip Image

To flip an image along x-axis, y-axis, or both axes, with OpenCV in Python, you can use cv2.flip() function.

Python OpenCV - Flip image

In this tutorial, you will learn how to use cv2.flip() function to flip an image, with examples.

Syntax of flip()

The syntax of cv2.flip() function is

cv2.flip(src, flipCode[, dst])

where

ParameterDescription
srcInput/source image array.
flipCodeThe code that specifies how to flip the array.
0: flip image around x-axis
1: flip image around y-axis (or any other positive value)
-1: flip image around both axes (or any other negative value)
dst[Optional] Output array of the same size and type as src.

Steps to flip an image

  1. Read an image into an array using cv2.imread() function.
  2. Define the flip code.
  3. Flip the image (2D array) using cv2.flip() function. Call the function and pass the input image array and flip code as arguments. It returns the flipped image array.
  4. Save the flipped image using cv2.imwrite() function.

Examples

In the following examples, we take the below image, and flip it.

Input Image - test_image_house.jpg

Python OpenCV - Flip image example - Input image

1. Flip image around X-axis

In the following program, we flip the input image around X-axis (flipping vertically). So, we pass 0 for the flipCode parameter.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Flip the image around X-axis
flipped_img = cv2.flip(img, 0)

# Save flipped image
cv2.imwrite('flipped_img.jpg', flipped_img)

flipped_img.jpg

Python OpenCV - Flip image around X-axis

2. Flip image around Y-axis

In the following program, we flip the input image around Y-axis (flipping horizontally). So, we pass 1 for the flipCode parameter.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Flip the image around Y-axis
flipped_img = cv2.flip(img, 1)

# Save flipped image
cv2.imwrite('flipped_img.jpg', flipped_img)

flipped_img.jpg

Python OpenCV - Flip image around Y-axis

3. Flip image around both axes

In the following program, we flip the input image around both X-axis and Y-axis (flipping both horizontally and vertically). So, we pass -1 for the flipCode parameter.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Flip the image around both axes
flipped_img = cv2.flip(img, -1)

# Save flipped image
cv2.imwrite('flipped_img.jpg', flipped_img)

flipped_img.jpg

Python OpenCV - Flip image around both axes

Summary

In this Python OpenCV Tutorial, we have seen how to flip an image along x-axis, y-axis, or both axis, using cv2.flip() function.