Python 从GIF中提取帧的更多问题

Python 从GIF中提取帧的更多问题,python,gif,Python,Gif,在我前面的问题()之后,我现在有了一些有时有效的代码 例如,此代码 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, 'PNG') img.seek(img.tell()+

在我前面的问题()之后,我现在有了一些有时有效的代码

例如,此代码

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, 'PNG')
        img.seek(img.tell()+1)
        current = Image.alpha_composite(current, img.convert('RGBA'))
        counter += 1
    except EOFError:
        break
…在大多数GIF上都能很好地工作,但在其他GIF上会产生奇怪的结果。例如,应用于此2帧GIF时:

它生成以下两个帧:

第一个还行,第二个还行


现在怎么办?

听起来你想这样做:

while True:
    try:
        current.save('original%d.gif' % counter)
        img.seek(img.tell()+1)
        current = img.convert('RGBA')
        counter += 1
    except EOFError:
        break
试试看(Wand是一个基于ctypes的简单的Python ImageMagick绑定。)

frame-0.png


frame-1.png

您没有真正阅读上一个问题,是吗?我之前的问题就是,代码不起作用。太好了。那么你的问题是什么?那么这个方法或者另一个SO'er提供的方法是错误的呢?在我的问题中,我要说的问题是:当代码应用于某些GIF时,仍然会产生错误的结果。结果是错误的。显示的结果看起来像是在另一个图像上合成了一个图像。我的解决方案应该是(大概是)不进行合成的图像。如果你阅读我前面的问题,你会发现合成是必要的,因为gif只保存帧与帧之间的更改。所以你所拥有的不是一个“解决方案”。请阅读链接问题。尝试查看第二帧,而不要将其与第一帧混合,并查看其像素是否发生了变化。
from wand.image import Image

def extract_frames(gif_file):
    with Image(filename=gif_file) as gif:
        for i, single_img in enumerate(gif.sequence):
            with Image(image=single_img) as frame:
                frame.format = 'PNG'
                frame.save(filename='frame-%d.png' % i)

extract_frames('test.gif')