代码之家  ›  专栏  ›  技术社区  ›  haseman

如何使用PIL使所有白色像素透明?

  •  99
  • haseman  · 技术社区  · 17 年前

    我试图使用Python图像库使所有白色像素透明。(我是一名试图学习python的C黑客,所以请温柔一点)

    img = Image.open('img.png')
    imga = img.convert("RGBA")
    datas = imga.getdata()
    
    newData = list()
    for item in datas:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append([255, 255, 255, 0])
        else:
            newData.append(item)
    
    imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1)
    imgb.save("img2.png", "PNG")
    
    10 回复  |  直到 5 年前
        1
  •  5
  •   Jonathan Dauwe    4 年前

    您需要进行以下更改:

    • (255, 255, 255, 0) 而不是列表 [255, 255, 255, 0]
    • 使用 img.putdata(newData)

    这是工作代码:

    from PIL import Image
    
    img = Image.open('img.png')
    img = img.convert("RGBA")
    datas = img.getdata()
    
    newData = []
    for item in datas:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)
    
    img.putdata(newData)
    img.save("img2.png", "PNG")
    
        2
  •  2
  •   leifdenby    4 年前

    您还可以使用像素访问模式就地修改图像:

    from PIL import Image
    
    img = Image.open('img.png')
    img = img.convert("RGBA")
    
    pixdata = img.load()
    
    width, height = img.size
    for y in range(height):
        for x in range(width):
            if pixdata[x, y] == (255, 255, 255, 255):
                pixdata[x, y] = (255, 255, 255, 0)
    
    img.save("img2.png", "PNG")
    

    如果你经常使用,你也可以把上面的内容包装成一个脚本。

        3
  •  2
  •   L.Lauenburg    4 年前

    import numpy as np
    
    def white_to_transparency(img):
        x = np.asarray(img.convert('RGBA')).copy()
    
        x[:, :, 3] = (255 * (x[:, :, :3] != 255).any(axis=2)).astype(np.uint8)
    
        return Image.fromarray(x)
    

    def white_to_transparency_gradient(img):
        x = np.asarray(img.convert('RGBA')).copy()
    
        x[:, :, 3] = (255 - x[:, :, :3].mean(axis=2)).astype(np.uint8)
    
        return Image.fromarray(x)
    

    备注: .copy()