Last modified: Oct 19, 2024 By Alexander Williams

Image Rotation and Flipping with Python Pillow

The Pillow library is a popular choice for image processing in Python. One of its common uses is rotating and flipping images. These operations are helpful when you want to adjust the orientation of images for various purposes. In this article, we will explore how to rotate and flip images using Python Pillow.

Getting Started with Pillow

If you're new to Pillow, you need to install it first. For instructions on installing Pillow, see our guide on Pillow: Installation and getting started (Python).

Loading an Image

To rotate or flip an image, you need to load it first using the Image.open() method:


from PIL import Image

# Load an image
image = Image.open('path_to_your_image.jpg')

Rotating an Image

You can rotate an image using the rotate() method. This method takes an angle as a parameter, measured in degrees:


# Rotate the image by 90 degrees
rotated_image = image.rotate(90)

The above code rotates the image by 90 degrees counter-clockwise. You can use any angle value to rotate the image as needed.

Flipping an Image

For flipping an image, Pillow provides two methods: Image.FLIP_LEFT_RIGHT and Image.FLIP_TOP_BOTTOM. These methods flip the image horizontally or vertically:


# Flip the image horizontally
flipped_image_horizontal = image.transpose(Image.FLIP_LEFT_RIGHT)

# Flip the image vertically
flipped_image_vertical = image.transpose(Image.FLIP_TOP_BOTTOM)

Use Image.FLIP_LEFT_RIGHT for a mirror effect and Image.FLIP_TOP_BOTTOM to flip the image upside down.

Saving the Rotated or Flipped Image

After rotating or flipping the image, you can save it using the save() method:


# Save the rotated image
rotated_image.save('rotated_image.jpg')

# Save the flipped image
flipped_image_horizontal.save('flipped_image_horizontal.jpg')
flipped_image_vertical.save('flipped_image_vertical.jpg')

Displaying the Transformed Image

If you want to view the transformed image immediately, you can use the show() method:


# Display the rotated image
rotated_image.show()

# Display the flipped image
flipped_image_horizontal.show()

For more information on displaying images, refer to our article on Python-Pillow: How to Show an image in Python.

Conclusion

Rotating and flipping images using Pillow is straightforward and effective. These simple transformations can make a big difference in how images are presented. For additional image manipulation techniques, check out our articles on Resizing Images Using Python Pillow and Cropping Images Using Python Pillow.