Pillow – Crop Image
We can crop an image in Pillow, by calling Image.crop() function on the given image, with crop rectangle passed as argument.
Syntax of crop() function
The syntax of crop() function from PIL.Image module is
|The box is a tuple of (left, upper, right, lower) pixel coordinate.|
The function returns a PIL.Image.Image object.
1. Crop image in the ROI (50, 50, 200, 200)
In the following example, we read an image
test_image.jpg with JPEG format into an Image object. Then, we crop this image with a crop rectangle of
(50, 50, 200, 200) using Image.crop() function. We save the cropped image to a file
from PIL import Image, ImageFilter import numpy as np # Open the image image = Image.open("test_image.jpg") # Rectangle bounds for cropping box = (50, 50, 200, 200) # Crop the image cropped_image = image.crop(box) # Save the cropped image cropped_image.save("cropped_image.jpg")
Original Image [test_image.jpg]
Resulting Image [cropped_image.jpg]
In this Python Pillow Tutorial, we learned how to crop a given image where the crop is defined by a boundary box, using PIL.Image.crop() function, with the help of examples.