python - 为什么我的 pylab 动画每次更新都会变慢?

标签 python matplotlib

我想通过在 for 循环中调用 imshow 来显示一个简单的动画。这是我的问题的演示:

import pylab,time
images = [pylab.uniform(0,255,(50,50)) for _ in xrange(40)]
pylab.ion()
timings = []
for img in images:
  tic = time.time()
  pylab.imshow(img)
  pylab.draw()
  toc = time.time()
  timings.append(toc-tic)
pylab.clf()
pylab.plot(timings)
pylab.title('elapsed time per iteration')
pylab.ioff()
pylab.show()

请注意,我在运行循环之前生成图像,并且我计时的唯一部分是 imshowdraw 函数。我得到的结果如下所示: Result of running my demo

我怎样才能避免这种减速?

最佳答案

事情正在变慢,因为您要添加越来越多的图像并每次绘制它们所有

要么 1) 清除每张图像之间的图(在您的情况下,pylab.cla()),要么更好 2) 不要制作新图像,只需设置现有图像到新数据。

作为使用 cla() 的例子:

import matplotlib.pyplot as plt
import numpy as np

images = np.random.uniform(0, 255, size=(40, 50, 50))

fig, ax = plt.subplots()

fig.show()
for image in images:
    ax.imshow(image)
    fig.canvas.draw()
    ax.cla()

作为仅设置数据的示例:

import matplotlib.pyplot as plt
import numpy as np

images = np.random.uniform(0, 255, size=(40, 50, 50))

fig, ax = plt.subplots()

im = ax.imshow(images[0])
fig.show()
for image in images[1:]:
    im.set_data(image)
    fig.canvas.draw()

您会注意到第二种方法要快得多。

关于python - 为什么我的 pylab 动画每次更新都会变慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10272478/

相关文章:

python - 在 Python 中组合两个排序列表

python - Matplotlib - 散布在常规图的顶部

matplotlib - 是否可以使用 Matplotlib imshow() 将二维数组显示为极坐标图?

python - pyplot : how to explicitly number an axis in a human-readable way

python - 计算向量范数相对于python中向量的梯度

python - Log(2 ** 62,2).is_integer() 返回 false 。任何想法为什么?

python - 如何从 matplotlib 中的轴删除 xtics?

python - 如何绘制我的数据框(python 和 pandas)

matplotlib - matplotlib contourf 图像文件的大小

python - 将字符串从 html 搜索框传递给 python 函数