If you like taking photos than you will probably also find yourself cropping your photos from time to time. I will crop photos to get rid of background noise or to just focus more on the subject I was trying to capture. I also like to take high resolution photos of insects or other small creatures and then crop it down to make it seem like I was even closer to the insect than I really was.
Now most people will use a photo editing application to crop their image, such as Photoshop Elements. I use these kinds of tools too, but you can also use the Python programming language to do the cropping for you. One good example where you might want to use Python is if you have thousands of scanned images of the same type, then it makes more sense to just write a script to do the cropping for you.
The most popular package for image manipulation in Python is the Pillow package, a "Friendly fork of the Python Imaging Library (PIL)". You can install Pillow using pip:
pip install Pillow
Now that we have Pillow installed, we just need a photo. Here's one of a grasshopper I took:
Let's write some code to try to crop the picture down to just the grasshopper's head:
from PIL import Image def crop(image_path, coords, saved_location): """ @param image_path: The path to the image to edit @param coords: A tuple of x/y coordinates (x1, y1, x2, y2) @param saved_location: Path to save the cropped image """ image_obj = Image.open(image_path) cropped_image = image_obj.crop(coords) cropped_image.save(saved_location) cropped_image.show() if __name__ == '__main__': image = 'grasshopper.jpg' crop(image, (161, 166, 706, 1050), 'cropped.jpg')
The first thing we do in this code is to import the Image sub-module from PIL. Then we create a crop() function that takes 3 parameters:
After we open the initial image, we get an object back that we can call crop() on. The crop method takes the coordinates we passed in and crops the image down appropriately and returns a second image object. We then call this second image object's save() method and tell it to save it to the specified location.
When you run the code, it will show the cropped image as well as saving it:
This is pretty close to what I wanted. You can experiment a bit with the x/y coordinates in the code above to try cropping the image in various ways to see how that works.
This code should probably have a check in it that prevents the user from overwriting the original image. Any good photo editor will not overwrite the original photo as that is really annoying and usually a bad thing. But I will leave that to the reader to figure it out.
Anyway, the Pillow project is a really powerful and helpful package for working with images in Python. Give it a try and see what fun things you can accomplish!
Copyright © 2022 Mouse Vs Python | Powered by Pythonlibrary