【问题标题】:matplotlib imshow(): how to animate?matplotlib imshow():如何制作动画?
【发布时间】:2013-06-17 06:08:10
【问题描述】:

我发现了这个关于动画的精彩简短教程:

http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

但是我无法制作相同方式的动画 imshow() 情节。 我试图替换一些行:

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
#line, = ax.plot([], [], lw=2)
a=np.random.random((5,5))
im=plt.imshow(a,interpolation='none')
# initialization function: plot the background of each frame
def init():
    im.set_data(np.random.random((5,5)))
    return im

# animation function.  This is called sequentially
def animate(i):
    a=im.get_array()
    a=a*np.exp(-0.001*i)    # exponential decay of the values
    im.set_array(a)
    return im

但我遇到了错误 你能帮我把它运行起来吗? 先感谢您。 最好的,

【问题讨论】:

  • 作为旁注,最好在问题中包含您遇到的错误。

标签: image animation matplotlib


【解决方案1】:

这是一个完整的例子:

# Usually we use `%matplotlib inline`. However we need `notebook` for the anim to render in the notebook.
%matplotlib notebook

import random
import numpy as np

import matplotlib
import matplotlib.pyplot as plt

import matplotlib.animation as animation


fps = 30
nSeconds = 5
snapshots = [ np.random.rand(5,5) for _ in range( nSeconds * fps ) ]

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure( figsize=(8,8) )

a = snapshots[0]
im = plt.imshow(a, interpolation='none', aspect='auto', vmin=0, vmax=1)

def animate_func(i):
    if i % fps == 0:
        print( '.', end ='' )

    im.set_array(snapshots[i])
    return [im]

anim = animation.FuncAnimation(
                               fig, 
                               animate_func, 
                               frames = nSeconds * fps,
                               interval = 1000 / fps, # in ms
                               )

anim.save('test_anim.mp4', fps=fps, extra_args=['-vcodec', 'libx264'])

print('Done!')

# plt.show()  # Not required, it seems!

【讨论】:

    【解决方案2】:

    您非常接近,但有一个错误 - initanimate 应该返回包含正在制作动画的艺术家的 iterables。这就是为什么在 Jake 的版本中它们返回 line,(实际上是一个元组)而不是 line(这是一个单行对象)。遗憾的是,文档对此并不清楚!

    您可以像这样修复您的版本:

    # initialization function: plot the background of each frame
    def init():
        im.set_data(np.random.random((5,5)))
        return [im]
    
    # animation function.  This is called sequentially
    def animate(i):
        a=im.get_array()
        a=a*np.exp(-0.001*i)    # exponential decay of the values
        im.set_array(a)
        return [im]
    

    【讨论】:

    • 漂亮!这个逗号符号以前让我很困惑,但这对我有帮助!
    • 这在全局脚本中对我有用,但在主函数中不起作用。我在 main 中有 init 和 animate 函数。有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    相关资源
    最近更新 更多