使用PIL Python将白色背景转换为透明背景

5

如何使用PIL将PNG或JPG图像中的所有白色背景和白色元素转换为透明背景?

1个回答

9
使用numpy,以下内容可以将白色区域变为透明。您可以更改thresholddist来控制“白色”的定义。
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

我理解阈值,但是你能解释一下这里距离的目的吗? - kangax
通过降低“dist”,您可以确保仅消除灰色色调。 - unutbu
啊...有道理!#000、#555、#aaa、ccc、#eee、#fff都是灰色的不同深浅(距离=0),所以距离越近,颜色就越灰。谢谢。 - kangax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接