Pillow - Crop Image


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

PIL.Image.crop(box=None)

where

ParameterDescription
boxThe box is a tuple of (left, upper, right, lower) pixel coordinate.

Returns

The function returns a PIL.Image.Image object.

Examples

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 cropped_image.jpg.

Python Program

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]

Python Pillow - Convert image from JPEG to PNG Example - Output image

Resulting Image [cropped_image.jpg]

Summary

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.