Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced cropping with Python Imaging Library

I have an A4 png image with some text in it, it's transparent, my question is, how can I crop the image to only have the text, I am aware of cropping in PIL, but if I set it to fixed values, it will not be able to crop another image that has that text in another place. So, how can I do it so it finds where the text, sticker, or any other thing is placed on that big and empty image, and crop it so the thing fits perfectly?

Thanks in advance!


1 Answers

You can do this by extracting the alpha channel and cropping to that. So, if this is your input image:

enter image description here

Here it is again, smaller and on a chessboard background so you can see its full extent:

enter image description here

The code looks like this:

#!/usr/bin/env python3

from PIL import Image

# Load image
im = Image.open('image.png')

# Extract alpha channel as new Image and get its bounding box
alpha = im.getchannel('A')
bbox  = alpha.getbbox()

# Apply bounding box to original image
res = im.crop(bbox)
res.save('result.png')

Here is the result:

enter image description here

And again on a chessboard pattern so you can see its full extent:

enter image description here

Keywords: Image processing, Python, PIL/Pillow, trim to alpha, crop to alpha, trim to transparency, crop to transparency.

like image 74
Mark Setchell Avatar answered Sep 14 '25 21:09

Mark Setchell