2013-03-30 57 views
4

因此,我正在嘗試編寫一個檢測鼠標在圖像上單擊並保存x,y位置的程序。我一直在使用matplotlib和我有一個基本的情節的工作,但是當我嘗試使用的圖像使用相同的代碼,我得到以下錯誤:用matplotlib檢測圖像中的鼠標事件

cid = implot.canvas.mpl_connect('button_press_event', onclick) 'AxesImage' object has no attribute 'canvas'

這是我的代碼:

import matplotlib.pyplot as plt 

im = plt.imread('image.PNG') 
implot = plt.imshow(im) 

def onclick(event): 
    if event.xdata != None and event.ydata != None: 
     print(event.xdata, event.ydata) 
cid = implot.canvas.mpl_connect('button_press_event', onclick) 

plt.show() 

讓我知道如果你有任何想法如何解決這個問題或更好的方式來實現我的目標。非常感謝!

回答

6

問題是implotArtist的子類,它繪製到canvas實例,但不包含(容易到達)對畫布的引用。您正在查找的屬性是figure類的屬性。

你想做的事:

ax = plt.gca() 
fig = plt.gcf() 
implot = ax.imshow(im) 

def onclick(event): 
    if event.xdata != None and event.ydata != None: 
     print(event.xdata, event.ydata) 
cid = fig.canvas.mpl_connect('button_press_event', onclick) 

plt.show() 
+0

是的!我無法弄清楚爲什麼這些地塊有畫布,並且沒有。太棒了。非常感謝。 – user2227523

+1

@ user2227523如果這解決了您的問題,您能否接受它(左邊的大灰色複選標記)?它給我們兩個代表,並標誌着未來用戶解決的問題。 – tacaswell

+0

對!我有點新... – user2227523

3

只需implot.canvasimplot.figure.canvas取代:

cid = implot.figure.canvas.mpl_connect('button_press_event', onclick) 
相關問題