2015-02-24 187 views
1

我正在做的是在無限循環中互換顯示2個圖像,直到用戶單擊窗口關閉它。matplotlib繪製在顯示圖像時循環很慢

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

我的期望是繪圖時間必須是所有循環次數相同。我在這裏做錯了什麼?

回答

4

問題是,您每次撥打ax.imshow時,都會爲該地塊添加一位其他藝術家(即,您爲添加了圖片,而不是僅替換它)。因此,在每次迭代中,plt.draw()都有一個額外的圖像可供繪製。

爲了解決這個問題,只是實例藝術家一次(前循環):

img_artist = ax.imshow(imggray) 

然後在循環中,只需調用

img_artist.set_data(gray) 

取代圖像內容(或img_artist.set_data(imggray)當然)

+0

非常感謝您的幫助解決方案。但是要在循環之前使用imshow來獲得圖像藝術家的刺激感。只是好奇有沒有其他方式讓藝術家使用imshow? – 2015-03-17 08:04:23

+0

什麼令人不愉快?將'img_artist'想象成一個處理所有與繪圖相關的屬性的容器,並且由於您只想更改顯示的數據,所以只需要其中一個對象。 – hitzg 2015-03-17 10:10:21