为什么每次更新时我的 pylab 动画都会变慢? [英] Why does my pylab animation slow down with each update?

查看:42
本文介绍了为什么每次更新时我的 pylab 动画都会变慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to display a simple animation by calling imshow in a for loop. Here's a demo of my problem:

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 函数.我得到的结果如下所示:

Note that I generate the images before running the loop, and that the only parts I time are the imshow and draw functions. I'm getting results that look like this:

我怎样才能避免这种放缓?

How can I avoid this slowdown?

推荐答案

事情变慢了,因为您每次都添加越来越多的图像并全部绘制它们.

Things are slowing down because you're adding more and more images and drawing them all each time.

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

Either 1) clear the plot between each image (In your case, pylab.cla()), or better yet 2) don't make a new image, just set the data of the existing image to the new data.

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()

并作为仅设置数据的示例:

And as an example of just setting the data:

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()

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

You'll notice that the second method is considerably faster.

这篇关于为什么每次更新时我的 pylab 动画都会变慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆