3

Following my previous question (Gifs opened with python have broken frames) I now have code that works sometimes.

For example, this code

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

…works on most GIFs perfectly, but on others it produces weird results. For example, when applied to this 2-frame GIF:

GIF

It produces these two frames:

Frame 1 Frame 2

The first one is ok, the second one not so much.

What now?

Community
  • 1
  • 1
  • Try viewing the second frame without composting it with the first and see if it's what it ought be as far as what pixels have changed and have not. – martineau Feb 25 '14 at 18:20

2 Answers2

1

Sounds like you want to do this:

while True:
    try:
        current.save('original%d.gif' % counter)
        img.seek(img.tell()+1)
        current = img.convert('RGBA')
        counter += 1
    except EOFError:
        break
Clarus
  • 2,259
  • 16
  • 27
  • You didn't really read the previous question, did you? My previous question was precisely that THAT code doesn't work. –  Feb 24 '14 at 19:29
  • Great. So then what is your question? What about either this approach or the approach that another SO'er provided is wrong? – Clarus Feb 24 '14 at 20:03
  • In my question, I say what the question is: that code when applied to some gifs still produces a wrong result. –  Feb 24 '14 at 20:11
  • What is wrong about the result. The result you showed looks like compositing an image on top of another image. The solution I have should (presumably) be the image without compositing. – Clarus Feb 24 '14 at 23:16
  • 1
    If you read my previous question, you'll see that the composition is necessary, because gif only saves changes from frame to frame. So what you have is not a "solution". Read the linked question please. –  Feb 24 '14 at 23:32
1

try Wand (Wand is a ctypes-based simple ImageMagick binding for Python.)

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

frame-0

frame-0.png

frame-1

frame-1.png

FelixHo
  • 1,254
  • 14
  • 26