Cropping is a common image manipulation task where you extract a specific rectangular portion of an image. Using Python's Pillow library, you can easily crop images and customize the region of interest.
In this tutorial, we’ll cover:
1. Installing Pillow
To install Pillow, use pip:
pip install pillow
2. Basic Cropping
The crop() method in Pillow allows you to define a box and extract a region from the image.
Example: Simple Cropping
from PIL import Image # Open an image image = Image.open("example.jpg") # Define the cropping box (left, upper, right, lower) crop_box = (100, 100, 400, 400) # Crop the image cropped_image = image.crop(crop_box) # Save and display the cropped image cropped_image.save("cropped_image.jpg") cropped_image.show()
Explanation
- The box is defined as (left, upper, right, lower) coordinates.
- (100, 100) is the top-left corner of the box, and (400, 400) is the bottom-right corner.
3. Cropping Based on Specific Coordinates
You can dynamically determine the cropping box based on the image size.
Example: Cropping Dynamically
# Get the image dimensions width, height = image.size # Crop the central 50% of the image left = width * 0.25 upper = height * 0.25 right = width * 0.75 lower = height * 0.75 cropped_center = image.crop((left, upper, right, lower)) cropped_center.save("cropped_center.jpg") cropped_center.show()
Explanation
- The crop box is calculated as a percentage of the image size.
- This method is useful for consistently cropping multiple images.
4. Center Cropping
Center cropping ensures the cropped region is centered in the image.
Example: Center Cropping with Fixed Size
def center_crop(image, crop_width, crop_height): width, height = image.size # Calculate the cropping box left = (width - crop_width) // 2 upper = (height - crop_height) // 2 right = (width + crop_width) // 2 lower = (height + crop_height) // 2 return image.crop((left, upper, right, lower)) # Crop the image to a size of 300x300 center_cropped = center_crop(image, 300, 300) center_cropped.save("center_cropped.jpg") center_cropped.show()
5. Cropping Using Aspect Ratio
You can crop an image while maintaining a specific aspect ratio (e.g., 16:9, 1:1).
Example: Cropping to a Specific Aspect Ratio
def crop_to_aspect_ratio(image, aspect_ratio_width, aspect_ratio_height): width, height = image.size target_aspect_ratio = aspect_ratio_width / aspect_ratio_height # Calculate new dimensions current_aspect_ratio = width / height if current_aspect_ratio > target_aspect_ratio: # Wider than target: crop width new_width = int(height * target_aspect_ratio) left = (width - new_width) // 2 right = left + new_width top, bottom = 0, height else: # Taller than target: crop height new_height = int(width / target_aspect_ratio) top = (height - new_height) // 2 bottom = top + new_height left, right = 0, width return image.crop((left, top, right, bottom)) # Crop the image to a 16:9 aspect ratio cropped_aspect_ratio = crop_to_aspect_ratio(image, 16, 9) cropped_aspect_ratio.save("cropped_aspect_ratio.jpg") cropped_aspect_ratio.show()
6. Saving Cropped Images
Save cropped images in the desired format using the save() method:
cropped_image.save("output.jpg", "JPEG", quality=95)
7. Batch Cropping Multiple Images
You can automate cropping for multiple images in a directory.
Example: Batch Cropping
import os def batch_crop(input_folder, output_folder, crop_box): os.makedirs(output_folder, exist_ok=True) for filename in os.listdir(input_folder): if filename.endswith((".jpg", ".jpeg", ".png")): image = Image.open(os.path.join(input_folder, filename)) cropped_image = image.crop(crop_box) cropped_image.save(os.path.join(output_folder, filename)) print(f"Cropped and saved: {filename}") # Crop the top-left 300x300 pixels for all images in a folder batch_crop("input_images", "output_images", (0, 0, 300, 300))
8. Practical Examples
8.1 Cropping a Region for Face Detection
# Suppose a face is detected at coordinates (x=50, y=50) with a width and height of 150 face_box = (50, 50, 200, 200) face_crop = image.crop(face_box) face_crop.save("face_cropped.jpg") face_crop.show()
8.2 Creating Thumbnails from Cropped Regions
thumbnail_crop = center_crop(image, 400, 400) thumbnail_crop.thumbnail((100, 100)) thumbnail_crop.save("thumbnail.jpg") thumbnail_crop.show()
8.3 Combining Cropping and Resizing
You can crop an image to focus on a specific region and then resize it.
def crop_and_resize(image, crop_box, target_size): cropped = image.crop(crop_box) resized = cropped.resize(target_size, Image.Resampling.LANCZOS) return resized # Crop a region and resize it to 200x200 processed_image = crop_and_resize(image, (50, 50, 300, 300), (200, 200)) processed_image.save("cropped_and_resized.jpg") processed_image.show()
9. Summary
Key Methods
- crop(box): Crops the image using the specified box (left, upper, right, lower).
- thumbnail(size): Resizes the cropped region while maintaining the aspect ratio.
- save(): Saves the cropped image in the desired format.
Use Cases
- Extracting specific regions of interest (e.g., faces or objects).
- Preparing images for display in specific aspect ratios.
- Automating tasks with batch cropping.