3

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.

Example

Here's the original gif

http://imgur.com/XMxW3m3

Here's the first frame (comes out ok)

http://imgur.com/xv43alb

Here's the second frame (comes out screwed)

http://imgur.com/hG4VxzL

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

Then Wand:

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.

What's going on?

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

Community
  • 1
  • 1

1 Answers1

4

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

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

FlorianLudwig
  • 325
  • 2
  • 9
  • Hi! Thanks, but that's not the whole story. It fixed the missing parts so I guess there's some truth in what you say, but it still comes out wrong, although in a different way: http://imgur.com/rham3RW –  Feb 24 '14 at 15:36
  • 1
    Hi, I was still playing around with this and I noticed if you instead save the images are png, this method actually works perfectly. So, if you change your code to current.save('original0%d.png' % counter, 'PNG'), I will accept this answer as correct. BTW, it seems that saving as png is MUCH slower than saving as gif. Why is that? Do you know how it can be saved as gif, to make it faster? –  Feb 24 '14 at 16:47
  • I created another question, in case you're interested: http://stackoverflow.com/questions/21996710/more-problems-extracting-frames-from-gifs –  Feb 24 '14 at 19:10
  • Layers can contain information if they are merged or replace the previous frame. I am not sure how to extract this information with pil/pillow – FlorianLudwig Feb 27 '14 at 12:56