matplotlib绘制在显示图像时循环缓慢

时间:2015-02-24 09:35:25

标签: python matplotlib

我正在做的是在无限循环中向一个数字交替显示2个图像,直到用户点击窗口关闭它。

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

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

1 个答案:

答案 0 :(得分:7)

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

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

img_artist = ax.imshow(imggray)

然后在循环中,只需调用

img_artist.set_data(gray)

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