如何将matplotlib动画转换为HTML5 <video>标签

4
以下是一个matplolib动画图的代码,这里有如何保存它的方法。
from IPython.display import HTML
import matplotlib.pyplot as plt
import matplotlib.animation 
import numpy as np

t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i]);

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t));
#HTML(ani.to_jshtml())

ani.to_html5_video()

我基本上所做的是将生成的代码复制到像这样的基本HTML脚本中:

<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>

<video width="432" height="288" controls autoplay loop> BLABLA </video>
</body>
</html>

图表没有显示,但标题和视频菜单还在。为什么?我该怎么办?


我认为这个问题缺少非常重要的一步,即ani.to_html5_video()如何与BLABLA相关。可能你只是在复制时犯了一个错误? - ImportanceOfBeingErnest
嘿,我得到的链接非常长,所以我不想复制粘贴它,并且我找不到附加文件的方法。这是我的驱动器中的链接:https://drive.google.com/file/d/1bGpBR5zoHFD_MCzZLuIaUWT3H0OVeHeO/view?usp=sharing - G. Macia
2个回答

7

仅仅使用ani.to_html5_video()并不能正确地输出字符串。 如果你仔细观察复制的内容,你会发现输出中有很多换行符(\n)。(在截图中我标记了它们...)

enter image description here

使用
print(ani.to_html5_video())

获取视频的HTML代码。或者,直接保存到文件中。

with open("myvideo.html", "w") as f:
    print(ani.to_html5_video(), file=f)


解释

作为一个解释性例子,假设

string = "Hello\nWorld"

如果在单元格中输入 string,它将生成。
'Hello\nWorld'

但是如果你使用print(string),它会给你解释后的字符串。

Hello
World

enter image description here


1
< p > to_html5 函数默认的 embed_limit 是 20 MB。 < /p >
If the embed_limit is exceeded, this returns the string "Video too large to embed."

我的猜测是您的动画超过了这个限制。由于在HTML中定义了<video>标签,标题和控件仍然会生成。
您可以查看生成的文档,看看视频主体是否只显示“视频太大无法嵌入”。如果是这种情况,您可以尝试增加embed_limit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接