使用imshow()和matplotlib.patches补丁程序

2024-05-29 12:02:07 发布

您现在位置:Python中文网/ 问答频道 /正文

为了提出这个问题,我清理了我的代码,然后在清理的同时找到了解决方案。请参阅下面我的解决方案。在

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

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

Tags: oftheimageimportformatplotlibnppi
1条回答
网友
1楼 · 发布于 2024-05-29 12:02:07

结果证明这是一个非常简单的解决方案。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()

这几乎以恒定的时间运行。希望这能为其他人节省几小时的调试时间。在

相关问题 更多 >

    热门问题