【问题标题】:White background to transparent background using PIL python使用PIL python的白色背景到透明背景
【发布时间】:2013-08-16 17:55:31
【问题描述】:

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

【问题讨论】:

    标签: python python-imaging-library


    【解决方案1】:

    使用 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
    

    【讨论】:

    • 我理解阈值,但你能解释一下距离的目的吗?
    • @kangax:通过降低dist,您可以确保只消除灰色。
    • 啊……有道理! #000、#555、#aaa、ccc、#eee、#fff 都是灰色阴影(距离 = 0),因此灰色距离越小。谢谢。
    猜你喜欢
    • 2014-08-21
    • 2013-04-03
    • 2018-03-25
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多