简体   繁体   English

使用 Python 成像库进行高级裁剪

[英]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.我有一个带有一些文本的 A4 png 图像,它是透明的,我的问题是,我如何裁剪图像以仅包含文本,我知道在 PIL 中裁剪,但如果我将其设置为固定值,它将无法裁剪在另一个地方有该文本的另一个图像。 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!提前致谢!

You can do this by extracting the alpha channel and cropping to that.您可以通过提取 alpha 通道并对其进行裁剪来完成此操作。 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.关键词:图像处理,Python,PIL/Pillow,修剪到 alpha,裁剪到 alpha,修剪到透明,裁剪到透明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM