【问题标题】:transparent background in gif using Python Imageio使用 Python Imageio 的 gif 中的透明背景
【发布时间】:2018-04-01 16:43:50
【问题描述】:

基本上我正在使用以下代码从图像中制作 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 是一个包含所有要使用的文件名的数组。

【问题讨论】:

    标签: python python-imageio


    【解决方案1】:

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

    【讨论】:

    • 谢谢这很好用。我需要改变一点,因为我的一些数字也被上面的像素重置删除了。但它有效! :)
    • save 函数中缺少 disposal,请参阅 this。缺少disposal 会导致透明帧叠加在之前的帧之上。
    • 这太令人费解了,真的没有更好的办法吗!?
    • 我测试了这个解决方案,但它不适用于某些 gif。问题是,PIL 在保存过程中尝试再次优化托盘,这可能会改变透明度指数。为避免这种情况,您需要将optimize=False 传递给保存函数。
    猜你喜欢
    • 1970-01-01
    • 2015-12-11
    • 2023-03-03
    • 2020-04-13
    • 2021-03-19
    • 2020-01-24
    • 2013-11-25
    • 2014-01-08
    • 1970-01-01
    相关资源
    最近更新 更多