python ffmpeg can't save gif ,but can save mp4

Viewed 894

I use python(jupyter) ffmpeg in mac , the main code is as follows:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
plt.rcParams['animation.ffmpeg_path'] = '/Users/water/anaconda/bin/ffmpeg'
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

mywriter = animation.FFMpegWriter()
anim.save('mymovie.mp4',writer=mywriter)

plt.show()

this will be right ,no error. but i want to save as gif, I change this part:

 anim.save('mymovie.gif',writer=mywriter)

I get the error as follows:

     37         except (AttributeError, TypeError, ValueError):
     38             raise ValueError("Invalid file object: "
---> 39                              "{!r}".format(fileobj)) from None
     40     if fd < 0:
     41         raise ValueError("Invalid file descriptor: {}".format(fd))

ValueError: Invalid file object: <_io.BufferedReader name=70>

can anyone tell why gif is error and mp4 is oK? and how to solve this problem

1 Answers

That is one weird error. I have no idea why you are getting it; But I was able to create a workaround, which basically takes the .mp4, and converts it to a .gif. Here is the code:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import os

plt.rcParams['animation.ffmpeg_path'] = '/Users/water/anaconda/bin/ffmpeg'
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=20, blit=True)

mywriter = animation.FFMpegWriter()
anim.save('in.mp4',writer=mywriter)

codeBASH = "ffmpeg -i in.mp4 -filter_complex 'fps=10,scale=320:-1:flags=lanczos,split [o1] [o2];[o1] palettegen [p]; [o2] fifo [o3];[o3] [p] paletteuse' out.gif"

os.system(codeBASH)
os.remove("in.mp4")
print("saved as gif and cleaned up")
plt.show()

Since I am not very adept at using matplotlib I am unsure how to show the gif in the matplotlib frame.

Related