How to Flip an Image Horizontally or Vertically in Python using OpenCV
In this article, we show how to flip an image horizontally or vertically in Python using the OpenCV module.
OpenCV has a number of built-in functions. The function we will be using in this article is the flip() function. This function allows us to flip an image horizontally, vertically, or both horizontally and vertically.
The original image we will be for all the flip demonstrations is shown below.
To Flip an Image Horizontally
The above stick figure image flipped horizontally gives us the following
image shown below.
To flip an image horizontally (along the image's vertical axis), we
use the following code shown below.
We must first import cv2 to use OpenCV.
We then read in our stick figure image using the imread() function. This is read into the variable, image.
We then create another variable, flippedimage. This will contain the flipped image.
To horizontally flip an image (flip the image about its vertical axis), we use the flip() function. The flip() function takes in 2 parameters. The first parameter is the image you want to flip. The second parameter is 1 (for horizontal flipping).
We then show the image, which we can see is flipped horizontally.
To Flip an Image Vertically
The original stick figure image flipped vertically gives us the following
image shown below.
To flip an image vertically (along the image's horizontal axis), we
use the following code shown below.
To vertically flip an image (flip the image about its vertical axis), we use the flip() function. The flip() function takes in 2 parameters. The first parameter is the image you want to flip. The second parameter is 0 (for vertical flipping).
We then show the image, which we can see is flipped vertically.
To Flip an Image Horizontally and Vertically
The original stick figure image flipped horizontally and
vertically gives us the following image shown below.
To flip an image horizontally and vertically, we
use the following code shown below.
To horizontally and vertically flip an image, we use the flip() function. The flip() function takes in 2 parameters. The first parameter is the image you want to flip. The second parameter is -1 (for horizontal and vertical flipping).
We then show the image, which we can see is flipped horizontally and vertically. This is the equivalent of rotating an image 180 degrees.
So these are powerful functions in OpenCV that we can use to flip images
horizontally or vertically.
And this is how to flip an image horizontally or vertically using the OpenCV
module.
Related Resources
How to Randomly Select From or Shuffle a List in Python