Python 使用imshow()和matplotlib.patches在动态图像中快速绘制静态圆
为了问这个问题,我清理了我的代码,然后在清理时找到了解决方案。请参阅下面我的解决方案 我试图在Python 使用imshow()和matplotlib.patches在动态图像中快速绘制静态圆,python,matplotlib,geometry,movie,imshow,Python,Matplotlib,Geometry,Movie,Imshow,为了问这个问题,我清理了我的代码,然后在清理时找到了解决方案。请参阅下面我的解决方案 我试图在imshow()中创建一个动态图像(一部电影),并使用matplotlib.patches在其上绘制静态圆圈,但随着电影的播放,它的速度变慢了(延迟随时间线性增加)。圆圈是静态的,因此必须有一种方法使matplotlib.patches在更新imshow()时运行得更快。这是我的密码: import matplotlib.pyplot as plt import numpy as np from mat
imshow()
中创建一个动态图像(一部电影),并使用matplotlib.patches
在其上绘制静态圆圈,但随着电影的播放,它的速度变慢了(延迟随时间线性增加)。圆圈是静态的,因此必须有一种方法使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()
这是一个非常简单的解决方案。
add_patch()
函数只需在电影开始时运行一次,set_array
更新圆圈后面的数组。以下是从主for
循环中删除add_patch()
函数的代码:
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()
这几乎是以恒定的时间运行的。希望这将在将来为其他人节省几个小时的调试时间