Crop a part of the image with Python, Pillow (trimming)
The image processing library Pillow (PIL) of Python provides
Image.crop() for cutting out a partial area of an image.
This article describes the following contents with sample code.
- Normal crop
- Specify outside area
- Crop the center of the image
- Crop the largest square from the rectangle
Please see the following article for the installation and basic usage of Pillow (PIL).
resize() to resize the whole image instead of cutting out a part of the image, and use
putalpha() to create a transparent image by cutting out a shape other than a rectangle (such as a circle).
Use slicing to crop the image represented by the NumPy array
PIL and open the target image.
from PIL import Image im = Image.open('data/src/astronaut_rect.bmp')
Set the cropping area with
box=(left, upper, right, lower).
The top left coordinates correspond to
(x, y) = (left, upper), and the bottom right coordinates correspond to
(x, y) = (right, lower). The area to be cropped is
left <= x <right and
upper <= y <lower, and the pixels of
x = right and
y = lower are not included.
Be careful not to forget that
im_crop = im.crop((60, 20, 400, 200)) im_crop.save('data/dst/astronaut_pillow_crop.jpg', quality=95)
If you just want to save the cropped image without using it for other operation, you can write in one line.
im.crop((60, 20, 400, 200)).save('data/dst/astronaut_pillow_crop.jpg', quality=95)
Specify outside area
If the outside of the image is set in the cropping area, an error does not occur and the image is displayed in black.
im_crop_outside = im.crop((200, 150, 600, 360)) im_crop_outside.save('data/dst/astronaut_pillow_crop_outside.jpg', quality=95)
Crop the center of the image
If you want to crop the center of the image to any size, it is convenient to define the following function.
def crop_center(pil_img, crop_width, crop_height): img_width, img_height = pil_img.size return pil_img.crop(((img_width - crop_width) // 2, (img_height - crop_height) // 2, (img_width + crop_width) // 2, (img_height + crop_height) // 2))
im_new = crop_center(im, 300, 150) im_new.save('data/dst/astronaut_pillow_crop_center.jpg', quality=95)
Crop the largest square from the rectangle
When creating a thumbnail image, you may need to trim a square as large as possible from the rectangular image.
Define a function that crop a square of short side length from the center of the rectangular image.
size attribute to get the height and width of the image, and
min() to get the shorter one. The function
crop_center() defined above is used.
def crop_max_square(pil_img): return crop_center(pil_img, min(pil_img.size), min(pil_img.size))
im_new = crop_max_square(im) im_new.save('data/dst/astronaut_pillow_crop_max_square.jpg', quality=95)
See the following article for more information about generating thumbnail images with Pillow.