我在mac中使用python(jupyter)ffmpeg,主要代码如下:
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()
这是对的,没有错误。 但我想保存为gif,我改变了这一部分:
anim.save('mymovie.gif',writer=mywriter)
我得到如下错误:
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>
任何人都可以告诉为什么gif是错误而mp4是oK?以及如何解决这个问题
答案 0 :(得分:0)
那是一个奇怪的错误。我不知道你为什么要得到它。但是我能够创建一种变通方法,该变通方法基本上采用了.mp4
,并将其转换为.gif
。这是代码:
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()
由于我不太擅长使用matplotlib
,所以不确定如何在matplotlib
框架中显示gif。