如何使用PIL将PNG或JPG图像中的所有白色背景和白色元素转换为透明背景?
如何使用PIL将PNG或JPG图像中的所有白色背景和白色元素转换为透明背景?
threshold
和dist
来控制“白色”的定义。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