Last modified: Oct 19, 2024 By Alexander Williams
Cropping Images Using Python Pillow
The Pillow library in Python allows you to perform a variety of image processing tasks, including cropping. Cropping is useful when you need to extract a specific region from an image. In this guide, we'll walk through the steps to crop images using Pillow.
Getting Started with Pillow
Before we begin, ensure that you have the Pillow library installed. If not, follow our Pillow: Installation and getting started (Python) guide to install it.
Loading an Image
To crop an image, you first need to load it using the Image.open()
method:
from PIL import Image
# Load an image
image = Image.open('path_to_your_image.jpg')
Cropping the Image
You can crop an image using the crop()
method, which requires a tuple representing the cropping box. The box is defined by four values: (left, upper, right, lower).
# Define the cropping box (left, upper, right, lower)
crop_box = (100, 100, 400, 400)
# Crop the image
cropped_image = image.crop(crop_box)
The above code crops a region from (100, 100) to (400, 400) in the image. Adjust the crop_box coordinates based on your desired area.
Saving the Cropped Image
Once you've cropped the image, you can save it using the save()
method:
# Save the cropped image
cropped_image.save('cropped_image.jpg')
Displaying the Cropped Image
If you want to view the cropped image directly, you can use the show()
method:
# Display the cropped image
cropped_image.show()
For more details on displaying images, check out our article on Python-Pillow: How to Show an image in Python.
Conclusion
Cropping images with Pillow is a simple yet powerful way to focus on specific parts of an image. By using the crop()
method and defining the appropriate coordinates, you can easily extract regions from any image. For other image manipulation techniques like resizing, refer to our article on Resizing Images Using Python Pillow.