How to Flip an Image using Python

While working in the Image Processing domain with Python, many times situations may arrive where you need to flip an existing image to get some insights out of it, to enhance its visibility or simply you need to set an image in whichever way you want. To accomplish this task there are many libraries supported by python such as Pillow, OpenCV, etc.

But, In this tutorial, we will be using the Python Imaging Library (PIL) i.e also Known as ‘Pillow’ for flipping the images. In this, I’ll be using two modules of Pillow library to do the same task, these modules are:

  • Image Module
  • ImageOps Module

Actually, the ‘ImageOps’ module internally uses ‘Image’ Module methods to perform different operations on the Images. So, you can say that both the modules are two faces of a single coin.

Also, read: Reading image from URL in Python

Using the Image Module

In this module, we will be using the ‘transpose(method)’ function for the flipping of Images.

Some of the methods supported by ‘transpose()’ are:

  •  Image.FLIP_LEFT_RIGHT – For flipping the image horizontally.
  •  Image.FlIP_TOP_BOTTOM – For flipping the image vertically.
  •  Image.ROTATE_90 – For rotating the image by specifying degree.

To learn more about Image Module you can refer to its documentation.

 Installation:

$ pip3 install pillow

Source Code:

# Importing Required Module
from PIL import Image

# Opening the Image as an object
org_img = Image.open("test.jpg")

# Flipping it Vertically
vert_img = org_img.transpose(method=Image.FLIP_TOP_BOTTOM)
vert_img.save("vertcal.jpg")

# Flipping it Horizontally
horz_img = org_img.transpose(method=Image.FLIP_LEFT_RIGHT)
horz_img.save("horizontal.jpg")

# Closing all the Image Objects
org_img.close()
vert_img.close()
horz_img.close()

Using the ImageOps Module

In this Module, we will be using two functions that are:

  • ImageOps.flip(Image) – For flipping the image vertically.
  • ImageOps.mirror(Image) – For flipping the image Horizontally.

Both the functions use ‘Image’ modules ‘transpose()’ function internally to perform this task.

To learn more about ImageOps Module you can refer to its documentation.

Installation:

You can install it using the pip:

$ pip3 install pillow

Source Code:

# Importing Required Modules
from PIL import Image
from PIL import ImageOps

# Opening the Image as an Object
org_img = Image.open("test.jpg")

# Flipping It Vertically
vert_img = ImageOps.flip(org_img)
vert_img.save("vertflip.jpg")

# Flipping It Horizontally
hort_img = ImageOps.mirror(org_img)
hort_img.save("horzflip.jpg")

# Closing all Image Objects
org_img.close()
vert_img.close()
hort_img.close()

So In this way, you can flip an image vertically or horizontally using Python. I hope this tutorial was fruitful to you, thank you ‘Keep Learning Keep Coding’.

Leave a Reply