python - Colab 有动态生成动画的方法吗?

标签 python animation google-colaboratory

我写了一个 Langton 的 Ant 代码,我想让动画在 Colab 中运行,直到它被用户停止或在一定数量的帧之后。就像现在一样,它先生成所有的帧,然后将它们编译成动画然后显示。如果有很多帧,则需要很长时间和/或 Colab 内存不足。这就是为什么我希望有一种方法可以一次只生成一帧并不断更新图像。 FuncAnimation 似乎没有这种能力,但也许我只是没有看到它。 如果有人知道有帮助的方法或文档,请告诉我。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc, colors
from IPython.display import HTML

N = 40
ant = np.array([N//2, N//2])
move = {'N': [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]}
d = ['N', 'E', 'S', 'W']
facing = 1
board = np.zeros((N, N))
color = 0
board[ant[0]][ant[1]] = 4

cmap = colors.ListedColormap(['darkgreen', 'limegreen', 'greenyellow', 'yellow', 'red'])


def turn(direction):
    if direction == 'R':
        return (facing + 1) % 4
    else:
        return (facing - 1) % 4


def update(data):
    global ant, board, facing, color
    if color in [0, 1]:
        facing = turn('R')
    else:
        facing = turn('L')

    board[ant[0]][ant[1]] = (color + 1) % 4
    ant += move[str(d[facing])]
    color = board[ant[0]][ant[1]]
    board[ant[0]][ant[1]] = 4

    mat.set_data(board)
    return [mat]

fig, ax = plt.subplots(figsize=(5, 5));

ax.grid(False)
plt.axis('off')

mat = ax.matshow(board, cmap=cmap)
ani = animation.FuncAnimation(fig, update, frames = 150, interval = 1, repeat=False, blit=True)

rc('animation', html='jshtml')
ani

最佳答案

您的代码似乎缺少更新。根据您的描述,您正在制作大量情节而没有清除它们。看看这个奇怪的 gif 东西的一些标志

from IPython.display import SVG, display
out=display(SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg'), display_id=True)
while True:
    out.update(SVG(url='https://upload.wikimedia.org/wikipedia/commons/f/fa/Flag_of_the_People%27s_Republic_of_China.svg'))
    out.update(SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg'))

这里的关键部分是out.update。你有一个更新功能。

空间

它看起来也像 Goolge Colab 中存在小部件,并且它们有一个笔记本可以显示它:https://colab.research.google.com/notebooks/widgets.ipynb

看起来你可以使用 Bokeh 制作动画,我不知道这是否可能,但我 100% 确定这是可能的。 https://colab.research.google.com/notebooks/charts.ipynb#scrollTo=nv8P3UYm6SiQ

关于python - Colab 有动态生成动画的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52618058/

相关文章:

用于在 Windows 中自动执行桌面事件的 Python 代码

html - 我的 :hover seem to be in conflict with something

objective-c - UIBarButtonItem 中的 UIButton 放弃了动画效果

jquery - 除非放大,否则 Chrome 中的 CSS 动画会断断续续

google-colaboratory - 本地运行时 404 GET

python - 是否可以在 Google Colaboratory 中进行动画可视化?

Python、SQLAlchemy 和 MySQL,奇数字符

python - 在 Python 中的不同行上打印列表元素

python - 从命令行调用 Python 脚本时有没有办法实现 **kwargs 行为

python - 在google colaboratory上安装seq2seq