使用Python Imageio的gif透明背景

时间:2017-10-20 13:37:31

标签: python python-imageio

基本上我使用下面一段代码从图像中制作gif,我的图像是png,背景透明,但gif是黑色背景。我不知道如何制作透明背景的gif。

#gif writer
with io.get_writer('my.gif', mode='I', duration=0.1) as writer:
    for filename in file_names:
        image = io.imread(filename)
        writer.append_data(image)
#writer.close()

其中filenames是一个包含要使用的文件名称的数组。

1 个答案:

答案 0 :(得分:3)

尝试PIL

from PIL import Image

def gen_frame(path):
    im = Image.open(path)
    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


im1 = gen_frame('frame1.png')
im2 = gen_frame('frame2.png')        
im1.save('GIF.gif', save_all=True, append_images=[im2], loop=5, duration=200)