PIL - 防止预乘alpha通道

时间:2016-08-21 23:22:59

标签: python python-imaging-library alpha premultiplied-alpha

我试图在图片上添加Alpha通道,但结果不是预期的结果:

from PIL import Image
baseImage = Image.open('baseimage.png').convert('RGBA')
alphaImage = Image.open('alphaimage.png').convert('L')
baseImage.putalpha(alphaImage)
baseImage.save('newimage.tiff', 'TIFF', compression='tiff_adobe_deflate')

这是给定的结果:

result

预期结果:

expected result

是否可以防止预乘?我还尝试拆分乐队并将它们与新的alpha通道合并,但结果相同。

1 个答案:

答案 0 :(得分:0)

您可以尝试手动反转预乘,如下所示:

from PIL import Image

baseImage = Image.open('baseIm.tiff').convert('RGBA')
alphaImage = Image.open('alphaIm.tiff').convert('L')

px = baseImage.load()
width, height = baseImage.size
for i in range(width):
    for j in range(height):
        if px[i, j][3] != 0:
            R = int(round(255.0 * px[i, j][0] / px[i, j][3]))
            G = int(round(255.0 * px[i, j][1] / px[i, j][3]))
            B = int(round(255.0 * px[i, j][2] / px[i, j][3]))
            a = px[i, j][3]

            px[i, j] = (R, G, B, a)


baseImage.putalpha(alphaImage)
baseImage.save('newIm.tiff', 'TIFF', compression='tiff_adobe_deflate')