用python打开的Gif帧已损坏 [英] Gifs opened with python have broken frames

查看:137
本文介绍了用python打开的Gif帧已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,当打开gif并将单独的框架保存到文件中时,框架会变形.并非所有的gif都发生这种情况,但是发生在所有gif上的情况都发生在这种情况下.

Sometimes when opening gifs and saving separate frames to files, the frames come out in bad shape. This doesn't happen with all the gifs, but with the ones that does it happens to many frames.

示例

这是原始的gif

http://imgur.com/XMxW3m3

这是第一帧(好了)

http://imgur.com/xv43alb

这是第二个框架(拧紧)

Here's the second frame (comes out screwed)

http://imgur.com/hG4VxzL

我用两个不同的python模块尝试了同样的事情.第一个PIL

I tried the same thing with two different python modules. First PIL

from PIL import Image

img = Image.open('pigs.gif')

counter = 0
collection = []
while True:
    try:
        img.save('original%d.gif' % counter)
        img.seek(img.tell()+1)
        counter += 1
    except EOFError:
        break

然后是魔杖:

from wand.image import Image

img = Image(filename='pigs.gif')

for i in range(len(img.sequence)):
    img2 = Image(img.sequence[i])
    img2.save(filename='original%d.gif' % i)

两个模块都发生同样的情况.

and the same happens with both modules.

这是怎么回事?

P.S .: 我发现其他人也有相同的症状.但是,这些解决方案(两者都围绕着PIL的错误,当您执行.seek()时,该错误会删除调色板)无法解决我的问题: Python:将GIF帧转换为PNG PIL-将GIF帧转换为JPG

P.S.: I have found other people having the same symptoms. However, these solutions (both of which revolve around a bug of PIL which deletes the palette when you do .seek()) didn't solve my problem: Python: Converting GIF frames to PNG and PIL - Convert GIF Frames to JPG

推荐答案

在gif中,一帧可能只包含在该帧中更改的像素.因此,当您导出时,黑色变了.

In gifs a frame may contain only the pixels that changed in that frame. So when you export you get black where there was no change.

from PIL import Image

img = Image.open('pigs.gif')

counter = 0
collection = []
current = img.convert('RGBA')
while True:
    try:
        current.save('original%d.png' % counter)
        img.seek(img.tell()+1)
        current = Image.alpha_composite(current, img.convert('RGBA'))
        counter += 1
    except EOFError:
        break

由于出现调色板问题,注释中建议将输出格式更改为png.

Changed output format to png as suggested in comments due to color palette problems that otherwise occur.

这篇关于用python打开的Gif帧已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆