简体   繁体   中英

Imageio python converts GIF to MP4 incorrectly

I am writing a function to speed up/down a given GIF (or .gifv) file, and save the resulting animation as an .mp4 file.

I'm using the python imageio package (and its ffmpeg plugin) to do this - download the raw binary data from the gif, write each frame to an mp4, and set the fps of the mp4 to whatever.

My code is -

def changespeed(vid, mult):
    vid = vid.replace('.gifv', '.gif')
    data = urllib2.urlopen(vid).read()
    reader = imageio.get_reader(data, 'gif')
    dur = (float(reader.get_meta_data()['duration']))
    oldfps = 1000.0 / (10 if dur == 0 else dur)


    writer = imageio.get_writer('output.mp4', fps=(oldfps*mult), quality=8.0)

    for frame in reader:
        writer.append_data(frame)
    writer.close()

The problem is, at times the output colors will be heavily corrupted, and there doesn't seem to be any predictability. This happens with some gifs and doesn't happen with others. I have tried setting a high quality parameter in the writer but this doesn't help.

Here is an example of a problematic GIF -

Input: https://i.imgur.com/xFezNYK.gif

Output: https://giant.gfycat.com/MelodicShimmeringBarb.mp4

I can see this issue locally in output.mp4 , so the issue isn't with uploading to Gfycat.

Is there anything I can do to avoid this behavior? Thanks.

Update - Figured it out. The colors themselves are not corrupted - the black portions are actually transparent portions, meant to be replaced with data from the previous frame.

Used this code to ensure transparent portions remain transparent (and can be alpha composited with PIL later) rather than black: https://gist.github.com/BigglesZX/4016539

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM