在Jupyter Notebook 中显示动画
程序员文章站
2022-03-11 21:42:43
...
在 jupyter notebook 中显示动画比较麻烦,查了好多方法都不行,整理了两个可以实现功能的函数,一个函数 plot_sequence_images
用于显示有序的图片,达到动画的效果,另一个函数plot_animation_function
用于显示动态函数:
显示图片序列
例子中,将一个 mp4 视频通过 opencv 读取为一个图片序列,就可以在 Jupyter notebook 中显示视频了:
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import display, HTML
import numpy as np
def plot_sequence_images(image_array):
''' Display images sequence as an animation in jupyter notebook
Args:
image_array(numpy.ndarray): image_array.shape equal to (num_images, height, width, num_channels)
'''
dpi = 72.0
xpixels, ypixels = image_array[0].shape[:2]
fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi)
im = plt.figimage(image_array[0])
def animate(i):
im.set_array(image_array[i])
return (im,)
anim = animation.FuncAnimation(fig, animate, frames=len(image_array), interval=33, repeat_delay=1, repeat=True)
display(HTML(anim.to_html5_video()))
# Demo of plot_sequence_images
import cv2
video_path = "/home/linux_fhb/data/suzhouc/test/top_camera.mp4"
video = cv2.VideoCapture()
video.open(video_path)
imgs = []
while True:
is_valid, img = video.read()
if not is_valid: break
imgs.append(img)
video.release()
plot_sequence_images(imgs)
显示动态函数
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import display, HTML
import numpy as np
def plot_animation_function(xy_generator, frames=100, figsize=(6, 4),
xlim=(0,2), ylim=(0, 2),interval=20, blit=True):
fig, ax = plt.subplots(figsize=figsize)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return (line,)
def animate(*args, **kwargs):
x, y = next(xy_generator)
line.set_data(x, y)
return (line,)
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=frames,
interval=interval, blit=blit)
display(HTML(anim.to_html5_video()))
fig.delaxes(ax)
# Demo of plot_animation_function
frames = 100
def GeneratorXY(frames):
for i in range(frames):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
yield (x, y)
plot_animation_function(GeneratorXY(frames), frames=frames, figsize=(8, 6),
xlim=(0, 2), ylim=(-2, 2))
上一篇: mybatis foerach多条件查询
下一篇: 【LeetCode】344. 反转字符串
推荐阅读
-
trick: matlotlib在jupyter notebook 里中文乱码解决
-
请大家帮我看一下我这段代码中的ul和a为什么不能显示在同一行中。_html/css_WEB-ITnose
-
html网页中插入script脚本,src指向php文件,怎么在html中显示php返回的数据?求大神赐教。
-
解决Android帧动画在Oncreate中启动只显示第一帧
-
解决Android帧动画在Oncreate中启动只显示第一帧
-
div中有一个marquee标签,marquee中有滚动显示的文字,如何让文字在div中垂直居中从右向左滚动显示?_html/css_WEB-ITnose
-
php中运用GD2库创建图形在浏览器中显示不出来
-
css中如果没有设置display,则无法显示动画效果!_html/css_WEB-ITnose
-
怎么将这段文字显示出来,在textarea中,要有换行的格式
-
怎么将这段文字显示出来,在textarea中,要有换行的格式