Advanced cropping with Python Imaging Library

血红的双手。 提交于 2021-02-05 11:21:36

问题


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:


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

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

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:

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

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



来源:https://stackoverflow.com/questions/63219166/advanced-cropping-with-python-imaging-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!