Opencv is the best python library for image processing. It has many inbuilt function that allows you to manipulate any image easily. The cv2.flip() method is one of them. In this entire tutorial, you will know how to implement the cv2 flip() method with examples.
Before going to the coding demonstration part let’s know the syntax for cv2.flip().
cv2.cv.flip(src, flipCode, dst )
Here src is the input image, flipCode is a flag that allows you to flip the image vertically or horizontally. For example, if the flag is 0 then the image will be flipped around the x-axis and if the flag is 1 then the image will be flipped vertically(y-axis). The flag value of -1 will flip the image around both the axis. And the last dst is the output image of the same size and type as the input image.
Examples of using the cv2 flip method
In this section, you will know all the examples that will be very helpful for understanding cv2.flip() method. In the code, I will import all the required packages for implementation.
Example 1: Flip the image horizontally
To flip the image horizontally or along x-axis you have to pass the flag value 0. Execute the below lines of code and see the output.
import cv2 img = cv2.imread("thank_you.png") image = cv2.flip(img,0) cv2.imshow("Original Image",img) cv2.imshow("Flipped Image",image) cv2.waitKey(0)
In the above code, I am first reading the image using the cv2.imread() method and for displaying the image to the screen I am using the cv2.imshow() method. The cv2.waitKey() method will display the image to the screen until any keyboard key is pressed.
Example 2: Use cv2.flip() to flip image vertically
In the same way, you can flip the image vertically after passing flag 1 . Run the below lines of code to flip the image vertically.
import cv2 img = cv2.imread("thank_you.png") image = cv2.flip(img,1) cv2.imshow("Original Image",img) cv2.imshow("Flipped Image",image) cv2.waitKey(0)
Example 3: Flipping the image around axes
In the above examples, you were flipping the image horizontally and vertically. Now, let’s flip the image around both axes. To do so you have to pass the flag as -1. Use the following lines of code and execute it.
import cv2 img = cv2.imread("thank_you.png") image = cv2.flip(img,-1) cv2.imshow("Original Image",img) cv2.imshow("Flipped Image",image) cv2.waitKey(0)
These are examples of the cv2.flip() method. This method is very useful if you have got the image flipped and want to rotate it according to your requirements. I hope you have understood this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.