在 jupyter-lab 中显示数组视频的快速方法

Seb*_*n E 2 python matplotlib jupyter-notebook jupyter-lab

我正在尝试在 jupyter-lab 的笔记本中显示一些数组的视频。数组是在运行时生成的。什么方法显示图像可以提供(相对)高的帧速率?使用 matplotlib 和 imshow 有点慢。图片大小约为 1.8 兆像素。上面是一些非常小的例子来形象化我想要实现的目标。

while(True): #should run at least 30 times per second 
    array=get_image() #returns RGBA numpy array  
    show_frame(array) #function I search for

Run Code Online (Sandbox Code Playgroud)

Mat*_*t07 6

最快的方法(例如用于调试目的)是使用matplotlib inlinematplotlibanimation包。这样的事情对我有用

%matplotlib inline
from matplotlib import pyplot as plt
from matplotlib import animation
from IPython.display import HTML

# np array with shape (frames, height, width, channels)
video = np.array([...]) 

fig = plt.figure()
im = plt.imshow(video[0,:,:,:])

plt.close() # this is required to not display the generated image

def init():
    im.set_data(video[0,:,:,:])

def animate(i):
    im.set_data(video[i,:,:,:])
    return im

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=video.shape[0],
                               interval=50)
HTML(anim.to_html5_video())
Run Code Online (Sandbox Code Playgroud)

视频将以指定的帧速率循环再现(在上面的代码中,我将间隔设置为 50 毫秒,即 20 fps)。

注意,这是一个快速解决方法,并且IPython.display有一个包(您可以在此处Video找到文档)允许您从文件或 URL(例如,来自 YouTube)重现视频。因此,您还可以考虑在本地存储数据并利用内置的 Jupyter 视频播放器。