如何使用 PIL 将 png 或 jpg 图像的所有白色背景和白色元素转换为透明背景?
最佳答案
以下使用 numpy 使白色区域透明。您可以更改 threshold
和 dist
来控制“white-ish”的定义。
import Image
import numpy as np
threshold=100
dist=5
img=Image.open(FNAME).convert('RGBA')
# np.asarray(img) is read only. Wrap it in np.array to make it modifiable.
arr=np.array(np.asarray(img))
r,g,b,a=np.rollaxis(arr,axis=-1)
mask=((r>threshold)
& (g>threshold)
& (b>threshold)
& (np.abs(r-g)<dist)
& (np.abs(r-b)<dist)
& (np.abs(g-b)<dist)
)
arr[mask,3]=0
img=Image.fromarray(arr,mode='RGBA')
img.save('/tmp/out.png')
代码很容易修改,因此只有 RGB 值 (255,255,255) 变为透明 - 如果那是您真正想要的。只需将 mask
更改为:
mask=((r==255)&(g==255)&(b==255)).T
关于python - 使用PIL python从白色背景到透明背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5365589/