[英]White background to transparent background using PIL python
如何使用PIL在透明背景中转换png或jpg图像的所有白色背景和白色元素?
Using numpy, the following makes white-ish areas transparent. 使用numpy,以下使白色区域透明。 You can change
threshold
and dist
to control the definition of "white-ish". 您可以更改
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')
The code is easy to modify so that only RGB value (255,255,255) is turned transparent -- if that is what you truly want. 代码很容易修改,只有RGB值(255,255,255)变为透明 - 如果这是你真正想要的。 Simply change the
mask
to: 只需将
mask
更改为:
mask=((r==255)&(g==255)&(b==255)).T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.