Last modified: Apr 12, 2025 By Alexander Williams
Python Image Cropping Guide
Image cropping is a common task in image processing. It helps remove unwanted parts of an image. Python offers multiple libraries for this purpose.
Table Of Contents
Why Crop Images in Python?
Cropping improves image focus. It removes distractions. It also reduces file size. This is useful for machine learning and web applications.
Before cropping, you may need to download images first. Or check image dimensions to plan your crop.
Cropping with PIL/Pillow
Pillow is the most popular Python imaging library. Here's how to crop with it:
from PIL import Image
# Open image
img = Image.open('input.jpg')
# Define crop area (left, top, right, bottom)
box = (100, 100, 400, 400)
# Crop image
cropped_img = img.crop(box)
# Save result
cropped_img.save('output.jpg')
The crop()
method takes a tuple of coordinates. These define the rectangular crop area.
Cropping with OpenCV
OpenCV is another powerful option. It's great for computer vision tasks.
import cv2
# Read image
img = cv2.imread('input.jpg')
# Define crop area (y1:y2, x1:x2)
cropped = img[100:400, 100:400]
# Save result
cv2.imwrite('output.jpg', cropped)
OpenCV uses NumPy array slicing. The syntax is different from Pillow but equally effective.
Automated Center Cropping
Sometimes you need to crop the center of an image. Here's how:
from PIL import Image
def center_crop(img, new_width, new_height):
width, height = img.size
left = (width - new_width)/2
top = (height - new_height)/2
right = (width + new_width)/2
bottom = (height + new_height)/2
return img.crop((left, top, right, bottom))
img = Image.open('input.jpg')
cropped = center_crop(img, 300, 300)
cropped.save('center_crop.jpg')
Cropping Circular Regions
For circular crops, we need a mask:
import cv2
import numpy as np
img = cv2.imread('input.jpg')
height, width = img.shape[:2]
# Create mask
mask = np.zeros((height, width), np.uint8)
cv2.circle(mask, (width//2, height//2), 150, 255, -1)
# Apply mask
result = cv2.bitwise_and(img, img, mask=mask)
# Save
cv2.imwrite('circle_crop.jpg', result)
Common Cropping Mistakes
Avoid these errors:
1. Coordinates out of image bounds. Always check image size first.
2. Forgetting to save in correct format. Use proper file extensions.
3. Not maintaining aspect ratio. This causes image distortion.
For more control, learn about PIL image handling.
Conclusion
Image cropping in Python is simple with Pillow or OpenCV. Choose Pillow for basic edits. Use OpenCV for advanced computer vision tasks.
Remember to always keep backups of original images. Cropping is destructive - you can't undo it later.
Now you can crop images like a pro! Try these techniques on your next project.