2016-02-28 74 views
0

我有一個腳本,繪製一些圖像:阻止並繼續在matplotlib

from matplotlib import pyplot as plt 
from matplotlib import image as mpimg 

(...) 

fig = plt.figure() 
ax = fig.add_subplot(111) 

(...) 

for img in images: 
    imgdata = mpimg.imread(img) 
    ax.imshow(imgdata) 
    plt.show(block=True) 

不幸的是,這似乎是unpossible阻止GUI和等待用戶輸入與fig.show()。只需plt.show()塊...所以我必須使用plt.show解決方案?

此外,我正在聽的用戶事件是這樣的:

cid = fig.canvas.mpl_connect('key_press_event', on_key_press) 

def on_key_press(event): 
    if event.key == "n": 
     ax.cla() 
     plt.show(block=False) 

我的目的是聽「N」(如「下一步」),然後用for循環繼續,因此加載下一個圖像數據並繪製它,再等等等待用戶輸入...

然而,第二個電話show()plt.show(block=False))更新圖像(所以ax數據被清除),但鎖不釋放 - 在對循環不會繼續。我怎麼能實現這種行爲?

編輯:我需要event.xdataevent.ydataevent.xevent.ymatplotlib值,因此實施「黑客」的東西,如input()因此讓蟒蛇等待用戶輸入在控制檯(使用matplotlib與block=False每時間)不會解決我的問題。

+0

http://matplotlib.org/examples/pylab_examples/ginput_demo.html – tacaswell

+0

感謝您的評論。其實我使用'ginput'作爲鼠標座標,但我也需要關鍵聽衆。我想爲基本操作創建快捷鍵,如增加/減少亮度,保存圖像,加載下一張圖像,... – daniel451

回答

0

我不太清楚你想要什麼樣的行爲,而是要像

def set_up_figure(): 
    fig, ax = plt.subplots() 
    fig.canvas.mpl_connect(..) 
    fig.canvas.mpl_connect(..) 
    return fig, ax 

for img in images: 
    fig, ax = set_up_figure() 
    ax.imshow(img) 
    plt.show(block=True) 

可能會奏效。

什麼plt.show做(即fig.show不)是啓動GUI事件循環是什麼,到底,將用戶輸入,打亂它通過回調機制,手事件的MPL回調機制,反過來實際上運行你的功能。

+0

這與我的代碼非常相似嗎?基本上我想要一個關鍵的監聽器,按'n'for循環('img in images')應該可以繼續,但到目前爲止我無法實現這一點。 'plot.show(block = True)'塊像永遠 - 我無法釋放它的塊。 – daniel451

+0

這是你想要的嗎? https://gist.github.com/tacaswell/4545013 – tacaswell

+0

在這種情況下,關閉窗口,它將繼續在循環中 – tacaswell