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

100

我正在尝试使用Python Image Library将所有白色像素变成透明的。 (我是一个尝试学习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")
11个回答

1
我还需要从复杂图像中去除背景颜色(异质阈值和颜色、光晕等),花了几个小时来解决这个问题。这里的解决方案都不令人满意,因为太过简单。
所以我决定直接使用这个主题中的主代码:Color-To-Alpha Gimp插件。而且它出奇地简单!
我只需将col_to_alpha.py复制到我的项目中,并像这样调用它:
import numpy as np
from col_to_alpha import color_to_alpha

def makeColorTransparent(image):
    image = image.convert("RGBA")
    pixels = np.array(image, dtype=np.ubyte)
    new_pixels = color_to_alpha(pixels, (255, 0, 255), 0.5 * 18, 0.75 * 193, 'cube', 'smooth')  # 0.5 and 0.75 match with the plugin sliders.
    return Image.fromarray(np.ubyte(new_pixels))

def main():
    image = Image.open('input.png')
    result = makeColorTransparent(image)
    result.save('output.png')

if __name__ == '__main__':
    main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接