您好,我使用 matplotlib 动画的解决方案:
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
video # my numpy matrix of shape (frames, channel, w, h)
# initializing a figure in
# which the graph will be plotted
fig = plt.figure(figsize=(10,10))
# create an axis
ax = plt.axes()
# initializing a line variable
img = ax.imshow(np.ndarray(shape=video.shape[2:])
def animate(i):
img.set_data(i)
return img,
anim = FuncAnimation(fig, animate, frames=video, interval=20, blit=True)
anim.save(filename, writer='ffmpeg', fps=5, bitrate=2000)
请注意,如果您在 jupyter notebook 中,您可以使用临时文件和 ipywidgets 来显示视频而不保存它。
from tempfile import NamedTemporaryFile
f = NamedTemporaryFile(mode='w+', suffix='.mp4')
#...previous code
anim.save(f.name, writer='ffmpeg', fps=5, bitrate=2000)
from ipywidgets import Video
Video.from_file(f.name)