PIL - Prevent premultiplied alpha channel

1k Views Asked by At

I'm trying to add alpha channel on an image, but the result is not the expected one:

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')

Here's the given result:

result

The expected result:

expected result

Is it possible to prevent premultiplication ? I also tried to split bands and merge them with the new alpha channel, but it was the same result.

1

There are 1 best solutions below

0
On

You could try to reverse premultiplication manually like this:

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')