2017-05-08 53 views
0

我清理了我的代码以问这个问题,然后在清理时找到了解决方案。请参阅下面的解决方案动态图像使用imshow()和matplotlib.patches快速静态圆圈

我想用matplotlib.patchesimshow()上创建一个动态图像(电影),其顶部使用静态圆圈绘制,但随着电影播放(延迟随时间线性增加)而减慢。圆圈是静态的,因此必须有一种方法使matplotlib.patches运行得更快,因为imshow()正在更新。这是我的代码:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.patches import Circle 
from scipy.linalg import toeplitz 

# Radius for circle of circles 
r = 0.5 
# Number of circles 
n = 7 
# Locations of centers of circles 
a = r*np.transpose(np.array([np.cos(np.arange(0,2*np.pi,2*np.pi/n)), 
          np.sin(np.arange(0,2*np.pi,2*np.pi/n))])) 

# Create first background image. 
E = toeplitz(np.random.rand(70)) 

# Plot the first frame. 
fig = plt.figure(1) 
ax = fig.add_subplot(111) 
im = ax.imshow(E,extent=np.array([-1,1,-1,1])) 
# Draw the circles on the image 
for k in range(np.shape(a)[0]): 
    ax.add_patch(Circle((a[k][0],a[k][1]),0.1)) 
plt.show() 

# Update with background image and redraw the circles. 
for t in range(60): 
    # Update the background image. 
    E=toeplitz(np.random.rand(70)) 
    im.set_array(E) 
    # Update the circles 
    for k in range(np.shape(a)[0]): 
     ax.add_patch(Circle((a[k][0],a[k][1]),0.1)) 
    fig.canvas.draw() 

回答

0

这原来是一个非常简单的解决方案。 add_patch()函数只需要在影片开头运行一次,并且set_array更新圆圈后面​​的数组。下面是与add_patch()功能从主for循环中去除代码:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.patches import Circle 
from scipy.linalg import toeplitz 

# Radius for circle of circles 
r = 0.5 
# Number of circles 
n = 7 
# Locations of centers of circles 
a = r*np.transpose(np.array([np.cos(np.arange(0,2*np.pi,2*np.pi/n)), 
          np.sin(np.arange(0,2*np.pi,2*np.pi/n))])) 

# Create first background image. 
E = toeplitz(np.random.rand(70)) 

# Plot the first frame. 
fig = plt.figure(1) 
ax = fig.add_subplot(111) 
im = ax.imshow(E,extent=np.array([-1,1,-1,1])) 
# Draw the circles on the image 
for k in range(np.shape(a)[0]): 
    ax.add_patch(Circle((a[k][0],a[k][1]),0.1)) 
plt.show() 

# Update with background image. 
for t in range(60): 
    E=toeplitz(np.random.rand(70)) 
    im.set_array(E) 
    fig.canvas.draw() 

这与运行几乎恒定时间。希望这将在未来为其他人节省几个小时的时间。