python - 使用PIL python从白色背景到透明背景

标签 python python-imaging-library

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

最佳答案

以下使用 numpy 使白色区域透明。您可以更改 thresholddist 来控制“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/

相关文章:

python - 如何找到曲线下的面积?

python - 将 2D 列表分配给 2 个 Dataframe 列 Pandas

python - 正则表达式匹配 'lol' 到 'lolllll' 和 'omg' 到 'omggg' 等

python - 如何在 Python 中基于 if 语句保存一个文档?

python - 为什么我可以用两种不同的方式导入 PIL(以及为什么这样做会出现问题)?

python - 当使用 PIL 中的 Image.new(...) 导入图像时,大小从什么开始?

python - PIL透视变换,计算出(a,b,c,d,e,f,g,h)

algorithm - 查找颜色相似的图像

python - Matplotlib 和单元测试

python - 如何在 Python 中创建一个空的 n*m PNG 文件?