【问题标题】:python ffmpeg can't save gif ,but can save mp4python ffmpeg无法保存gif,但可以保存mp4
【发布时间】:2018-01-24 09:03:32
【问题描述】:

我在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 是好的?以及如何解决这个问题

【问题讨论】:

  • 嗨,水。您是否偶然找到了解决方案?我可以确认我在Ubuntu 16.04 上遇到了同样的问题

标签: macos python-3.x ffmpeg anaconda jupyter


【解决方案1】:

这是一个奇怪的错误。我知道你为什么会得到它;但我能够创建一个解决方法,它基本上采用.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。

【讨论】:

    猜你喜欢
    • 2017-11-21
    • 1970-01-01
    • 2018-11-18
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2021-09-14
    • 2018-06-05
    相关资源
    最近更新 更多