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

3 python png image crop python-imaging-library

我有一个 A4 png 图像,其中有一些文本,它是透明的,我的问题是,如何裁剪图像以仅包含文本,我知道 PIL 中的裁剪,但如果我将其设置为固定值,它将无法裁剪在其他位置具有该文本的另一张图像。那么,我该怎么做才能找到文本、贴纸或任何其他东西放置在大而空的图像上的位置,并裁剪它以使东西完美贴合?

提前致谢!

Mar*_*ell 5

您可以通过提取 Alpha 通道并对其进行裁剪来实现此目的。因此,如果这是您的输入图像:

在此输入图像描述

这是它,更小,位于棋盘背景上,这样您就可以看到它的完整范围:

在此输入图像描述

代码如下所示:

#!/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')
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

再次在棋盘图案上,这样你就可以看到它的完整范围:

在此输入图像描述

关键词:图像处理、Python、PIL/Pillow、修剪到 alpha、裁剪到 alpha、修剪到透明度、裁剪到透明度。