matplotlib draw 在显示图像时循环缓慢

matplotlib draw is slow in loop when it showing an image

我正在做的是在无限循环中将 2 个图像互换显示为一个图形,直到用户单击 window 将其关闭。

#import things
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import cv2
import time

#turn on interactive mode for pyplot
plt.ion()

quit_frame = False

#load the first image
img = cv2.imread("C:\Users\al\Desktop\Image1.jpg")
#make the second image from the first one
imggray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

def onclick(event):
    global quit_frame
    quit_frame = not quit_frame

fig = plt.figure()
ax = plt.gca()
fig.canvas.mpl_connect('button_press_event', onclick)

i = 0

while quit_frame is False:
    if i % 2 == 0: #if i is even, show the first image
        ax.imshow(img)
    else: #otherwise, show the second
        ax.imshow(imggray)

    #show the time for drawing
    start = time.time()
    plt.draw()
    print time.time() - start

    i = i + 1
    fig.canvas.get_tk_widget().update()
    if quit_frame is True:
        plt.close(fig)

这里的问题是打印的时间在开始循环时非常小,但逐渐增加:

0.107000112534
0.074000120163
0.0789999961853
0.0989999771118
0.0880000591278
...
0.415999889374
0.444999933243
0.442000150681
0.468999862671
0.467000007629
0.496999979019
(and continue to increase)

我的期望是所有循环时间的绘制时间必须相同。我在这里做错了什么?

问题是,每次调用 ax.imshow 时,都会向绘图中添加一个额外的艺术家(即,您 添加 图像,而不是仅仅替换它) .因此,在每次迭代中 plt.draw() 都有一个额外的图像要绘制。

要解决这个问题,只需实例化一次艺术家(在循环之前):

img_artist = ax.imshow(imggray)

然后在循环中,调用

img_artist.set_data(gray)

替换图片内容(当然是img_artist.set_data(imggray)