Professional Documents
Culture Documents
Looking to help automate photo cropping? Look no further than this article, then,
as we take a look at how to accomplish just that using Python!
If you like taking photos, then 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:
Now that we have Pillow installed, we just need a photo. Here�s one of a
grasshopper I took:
Image title
Let�s write some code to try to crop the picture down to just the grasshopper�s
head:
When you run the code, it will show the cropped image as well as save it:
Image title
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.
Wrapping Up
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!
Related Reading
An Intro to the Python Imaging Library/Pillow