In our last article, we learned how to crop images with the Pillow package. For this article, we will learn how to rotate and mirror our images.
Rotating an Image
Rotating an image with Python and Pillow is quite simple. Let’s take a look at some code:
from PIL import Image def rotate(image_path, degrees_to_rotate, saved_location): """ Rotate the given photo the amount of given degreesk, show it and save it @param image_path: The path to the image to edit @param degrees_to_rotate: The number of degrees to rotate the image @param saved_location: Path to save the cropped image """ image_obj = Image.open(image_path) rotated_image = image_obj.rotate(degrees_to_rotate) rotated_image.save(saved_location) rotated_image.show() if __name__ == '__main__': image = 'mantis.png' rotate(image, 90, 'rotated_mantis.jpg')
Here we just import the Image module from PIL and create a rotate() function. Our custom rotate function takes the following parameters: the image path that we will be rotating, the degrees we want to rotate and where we want to save the result. The actual code is quite straight-forward. All we do is open the image and then call the image object’s rotate() method while passing it the number of degrees to rotate it counter-clockwise. Then we save the result and call the image object’s show() method to see the result:
In the example above, we rotated the praying mantis 90 degrees counter-clockwise.
Mirroring an Image
Now let’s try to flip or mirror our mantis image. Here’s an example that mirrors the image from left to right:
from PIL import Image def flip_image(image_path, saved_location): """ Flip or mirror the image @param image_path: The path to the image to edit @param saved_location: Path to save the cropped image """ image_obj = Image.open(image_path) rotated_image = image_obj.transpose(Image.FLIP_LEFT_RIGHT) rotated_image.save(saved_location) rotated_image.show() if __name__ == '__main__': image = 'mantis.png' flip_image(image, 'flipped_mantis.jpg')
This code is very similar to the previous example. The meat of this code is that we are using the image object’s transpose() method which takes one of the following constants:
You can also use one of Pillow’s ROTATE constants here too, but we’re focusing just on the mirroring aspect of the transpose() method. Try swapping in one of these other constants into the code above to see what happens.
Now you know how to use the Pillow package to rotate and flip/mirror your images. Python makes this sort of thing quite trivial to do. You should give it a try and be sure to check out Pillow’s documentation to find out what else you can do!