HenkJan van der Pol HenkJan van der Pol - 1 year ago 91
Python Question

Changed behaviour of ImageEnhance.Brightness in Pillow

I'm trying to paste image B over image A with half opacity (i.e. pasted image is half transparent).

In version 2.1.0 of pillow the following code worked, in version 3.3.1 it no longer works:

A = Image.open('A.png')

B = Image.open('B.png')
enhancer = ImageEnhance.Brightness(B)
mask = enhancer.enhance(0.5)
print(mask.getpixel((10,10)), mask.getpixel((30,30)))

A.paste(B, (0,0), mask)

Image A is a black 'A' on a white background

Image B is a red 'B' on a transparent background

Images are provided below

Version 2.1.0 produces (127,0,0,127) for pixel 30,30 of the mask

Version 3.3.1 produces (127,0,0,255) for pixel 30,30 of the mask

Image A
Image B

Answer Source

Pillow is correct, changing the brightness of a pixel should not change its transparency. Obviously there was a bug in PIL.

What you really want is to split the alpha from image B and turn that into a mask. Using the technique from this answer:

mask = B.split()[-1]
enhancer = ImageEnhance.Brightness(mask)
mask = enhancer.enhance(0.5)