Jupyter Notebook 中的 Numpy 数组作为视频

sac*_*ruk 5 python jupyter-notebook

我有一组从视频中提取的边缘图像(使用cv2.Canny)。所以数组的大小是TxHxW。其中T是时间步长,后面的参数是高度和宽度。

目前,我在Jupyter Notebook上显示输出的方式是使用以下代码:

from IPython.display import HTML
import imageio

imageio.mimwrite('test2.mp4', edges, fps=30)
HTML("""
<video width="480" height="360" controls>
  <source src="{0}">
</video>
""".format('./test2.mp4'))
Run Code Online (Sandbox Code Playgroud)

我觉得生活中写入文件可能是不必要的,并且可能有更好的方法。如果有请告诉我。重点是在 Jupyter 笔记本中显示。

如果您需要测试用例,请让edges = np.random.randn(100, 80, 80).

解决方案一:

感谢下面@Alleo 的评论。使用 Ipython 7.6+,您可以执行以下操作:

import imageio; 
from IPython.display import Video; 
imageio.mimwrite('test2.mp4', edges, fps=30); 
Video('test2.mp4', width=480, height=360) #the width and height option as additional thing new in Ipython 7.6.1
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)。

请查看我对此问题的回答以了解更多详细信息。