Thursday, 17 February 2022

Saving png sequence as WebP in pil makes background opaque black

from PIL import Image, ImageSequence


def gen_frame(im):
    alpha = im.getchannel('A')
    # Convert the image into P mode but only use 255 colors in the palette out of 256
    im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
    # Set all pixel values below 128 to 255 , and the rest to 0
    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
    # Paste the color of index 255 and use alpha as a mask
    im.paste(255, mask)
    # The transparency index is 255
    im.info['transparency'] = 255
    return im


im = Image.open("input_gif.gif")

im_list = []

for frame in ImageSequence.Iterator(im):
    # perform some functions on the image frames
    
    # frame = frame.convert('RGBA').resize((512, 512), Image.ANTIALIAS)
    # frame = gen_frame(frame)
    
    im_list.append(frame)

img = im_list[0]
imgs = im_list[1:]

img.save("output_gif.gif", save_all=True, append_images=imgs, duration=100, loop=0, optimize=False, disposal=2)
# works correctly, as intended

img.save("output_webp.webp", save_all=True, append_images=imgs, duration=100, loop=0, optimize=False, disposal=2)
# Transparency loss in the webp format

when saving as gif, it works great, but when saving as webp, the transparency is lost in all frames.

output of gif:

GIF output

in webp its same, just no transparency, all black background

how can this be fixed?



from Saving png sequence as WebP in pil makes background opaque black

No comments:

Post a Comment