Title: OpenCV Flip Image ( cv2.flip ) - PyImageSearch

URL Source: https://pyimagesearch.com/2021/01/20/opencv-flip-image-cv2-flip/

Published Time: 2021-01-21T04:46:00+00:00

Markdown Content:
In this tutorial, you will learn how to flip images using OpenCV and the `cv2.flip` function.

![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20475'%3E%3C/svg%3E)

Similar to [image rotation](https://pyimagesearch.com/2021/01/20/opencv-rotate-image/), OpenCV also provides methods to flip an image across its _x-_ or _y_\-axis. Though flipping operations are used less often, they are still very valuable to learn — and for reasons that you may not consider off the top of your head.

For example, let’s imagine working for a small startup company that wants to build a machine learning classifier to detect faces within images. We would need a dataset of example faces that our algorithm could use to “learn” what a face is. But unfortunately, the company has only provided us with a tiny dataset of 20 faces, and we don’t have the means to acquire more data.

So what do we do?

**We apply flipping operations to augment our dataset!**

We can horizontally flip each face image (since a face is still a face, whether mirrored or not) and use these mirrored versions as additional training data.

While this example sounds silly and contrived, it’s not. Powerful, data-hungry, deep learning algorithms purposely use flipping to generate extra data during training time (through a technique called [data augmentation](https://pyimagesearch.com/2019/07/08/keras-imagedatagenerator-and-data-augmentation/)).

So, as you see, the image processing techniques you’re learning here really are the building blocks for larger computer vision systems!

**To learn how to flip images with OpenCV and `cv2.flip`, _just keep reading._**

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

In the first part of this tutorial, we’ll discuss what image flipping is and how OpenCV can help us flip images.

From there, we’ll configure our development environment and review our project directory structure.

We’ll then implement a Python script to perform image flipping with OpenCV.

### **What is image flipping?**

We can flip an image around either the _x_\-axis, _y_\-axis, or even both.

Flipping an image is better explained by viewing an image flip’s output before starting the code. Check out **Figure 1** to see an image flipped horizontally:

![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20312'%3E%3C/svg%3E)

**Figure 1:** Using OpenCV to flip an image horizontally.

Notice how on the _left,_ we have our original image, and on the _right,_ the image has been mirrored horizontally.

We can do the same vertically:

![Image 4](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20311'%3E%3C/svg%3E)

**Figure 2:** Flipping an image vertically with OpenCV.

And we can combine horizontal and vertical flips as well:

![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20311'%3E%3C/svg%3E)

**Figure 3:** Flipping an image both horizontally and vertically with OpenCV.

Later in this tutorial, you’ll discover how to perform these image flipping operations with OpenCV.

### **Configuring your development environment**

To follow this guide, you need to have the OpenCV library installed on your system.

Luckily, OpenCV is pip-installable:

$ pip install opencv-contrib-python

**If you need help configuring your development environment for OpenCV, I _highly recommend_ that you read my** [**_pip install OpenCV_ guide**](https://pyimagesearch.com/2018/09/19/pip-install-opencv/) — it will have you up and running in a matter of minutes.

### **Having problems configuring your development environment?**

[![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20334'%3E%3C/svg%3E)](https://pyimagesearch.com/pyimagesearch-plus/)

**Figure 4:** Having trouble configuring your development environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join [PyImageSearch Plus](https://pyimagesearch.com/pyimagesearch-plus/) — you will be up and running with this tutorial in a matter of minutes.

All that said, are you:

*   Short on time?
*   Learning on your employer’s administratively locked system?
*   Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?
*   **Ready to run the code _right now_ on your Windows, macOS, or Linux systems?**

Then join [PyImageSearch Plus](https://pyimagesearch.com/pyimagesearch-plus/) today!

**Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides that are _pre-configured_ to run on Google Colab’s ecosystem right in your web browser!** No installation required.

And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!

### **Project structure**

Before reviewing any code for clipping an image with OpenCV, let’s first review our project directory structure.

Be sure to access the **_“Downloads”_** section of this tutorial to retrieve the source code and example image.

From there, take a peek at your project folder:

$ tree . --dirsfirst
.
├── opencv\_flip.py
└── opencv\_logo.png

0 directories, 2 files

Our `opencv_flip.py` script will load the `opencv_logo.png` image from disk and then demonstrate how to use the `cv2.flip` function to flip an image.

### **Implementing image flipping with OpenCV**

Next on our list of image transformations to explore is flipping. We can flip an image around either the _x-_ or _y_\-axis, or even both.

Flipping an image is better explained by viewing the output of an image flip, before we get into the code. Check out **Figure 5** to see an image flipped horizontally:

![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20481'%3E%3C/svg%3E)

**Figure 5:** Horizontal image flipping with OpenCV and cv2.flip.

Now that you see what an image flip looks like, we can explore the code:

\# import the necessary packages
import argparse
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add\_argument("-i", "--image", type=str, default="opencv\_logo.png",
	help="path to the input image")
args = vars(ap.parse\_args())

**Lines 2 and 3** import our required Python packages while **Lines 6-9** parse our command line arguments.

We only need a single argument here, `--image`, which is the path to the input image we want to flip. We default this value to the `opencv_logo.png` image in our project directory.

Let’s now flip the image horizontally:

\# load the original input image and display it to our screen
image = cv2.imread(args\["image"\])
cv2.imshow("Original", image)

# flip the image horizontally
print("\[INFO\] flipping image horizontally...")
flipped = cv2.flip(image, 1)
cv2.imshow("Flipped Horizontally", flipped)

We start on **Lines 12 and 13** by loading our input image from disk and displaying it to our screen.

Flipping an image horizontally is accomplished by making a call to the `cv2.flip` function on **Line 17**, the output of which is seen in **Figure 5**.

The `cv2.flip` method requires two arguments: the `image` we want to flip and a specific code/flag used to determine how we flip the image.

Using a flip code value of `1` indicates that we flipped the image horizontally, around the _y_\-axis.

Specifying a flip code of `0` indicates that we want to flip the image vertically, around the _x_\-axis:

\# flip the image vertically
flipped = cv2.flip(image, 0)
print("\[INFO\] flipping image vertically...")
cv2.imshow("Flipped Vertically", flipped)

**Figure 6** displays the output of flipping an image vertically:

![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20486'%3E%3C/svg%3E)

**Figure 6:** Flipping an image vertically with OpenCV and cv2.flip.

Finally, using a negative flip code flips the image around both axes.

\# flip the image along both axes
flipped = cv2.flip(image, -1)
print("\[INFO\] flipping image horizontally and vertically...")
cv2.imshow("Flipped Horizontally & Vertically", flipped)
cv2.waitKey(0)

Here, you can see that our image is flipped both horizontally and vertically:

![Image 9](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20475'%3E%3C/svg%3E)

**Figure 7:** Supply a negative file to cv2.flip to flip an image both horizontally and vertically.

Flipping an image is very simple — perhaps one of the most simple examples in this series!

### **OpenCV image flipping results**

To flip images with OpenCV, be sure to access the **_“Downloads”_** section of this tutorial to retrieve the source code and example image.

From there, open a shell and execute the following command:

$ python opencv\_flip.py 
\[INFO\] flipping image horizontally...
\[INFO\] flipping image vertically...
\[INFO\] flipping image horizontally and vertically...

Your OpenCV flipping results should match mine from the previous section.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

**Summary**
-----------

In this tutorial, you learned how to flip images horizontally and vertically with OpenCV and the `cv2.flip` function.

Admittedly, image flipping is one of the easiest image processing concepts we have covered. However, just because a concept is simple does not mean that it’s not used for more powerful purposes.

As I mentioned in the introduction to this tutorial, flipping is consistently used in machine learning/deep learning to generate more training data samples, thus creating more powerful and robust image classifiers.

**To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), _simply enter your email address in the form below!_**

![Image 10](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!