我正在处理一些图像数据,点击图像中的不同元素会有帮助。我希望将“shift-click”作为注册光标位置的触发机制。未按Matplotlib正确注册的按键事件
我写了一个“点击”功能,做正确的事情。但是,当我尝试将其升级到“shift-click”时,它根本不起作用。奇怪的是,它使用老版本的Matplotlib(1.1,运行在Linux机器上,我的版本是1.4.2,在Mac上运行,两个都运行Python 2.7)都能在我的同事的计算机上工作。
任何人有任何想法是怎么回事?我完全没有想法。其他可能相关的信息是我最近安装了Seaborn(然后卸载它)并升级了matplotlib(并试图降级,但失败了)
编辑好吧,我想我现在明白了。在开始正常工作之前,换挡必须至少按下并释放一次。也许有一个解决方法。
import numpy as np
import matplotlib.pyplot as plt
def shiftclick(refimage, comment=None, eq=True):
class EventHandler:
def __init__(self, spotlist):
fig.canvas.mpl_connect('button_press_event', self.onpress)
fig.canvas.mpl_connect('key_press_event', self.on_key_press)
fig.canvas.mpl_connect('key_release_event', self.on_key_release)
self.shift_is_held = False
def on_key_press(self, event):
if event.key == 'shift':
self.shift_is_held = True
def on_key_release(self, event):
if event.key == 'shift':
self.shift_is_held = False
def onpress(self, event):
if event.inaxes!=ax:
return
if self.shift_is_held:
xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
value = im.get_array()[xi,yi]
print xi, yi
spotlist.append((xi, yi))
im = plt.imshow(refimage, interpolation='nearest', origin='lower')
plt.title('SHIFT-click on locations')
fig = plt.gcf()
ax = plt.gca()
spotlist = []
handler=EventHandler(spotlist)
plt.show()
return spotlist
def click(refimage, comment=None):
class EventHandler:
def __init__(self, spotlist):
fig.canvas.mpl_connect('button_press_event', self.onpress)
def onpress(self, event):
if event.inaxes!=ax:
return
xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
value = im.get_array()[xi,yi]
print xi, yi
spotlist.append((xi, yi))
im = plt.imshow(refimage, interpolation='nearest', origin='lower')
fig = plt.gcf()
ax = plt.gca()
spotlist = []
handler=EventHandler(spotlist)
plt.show()
return spotlist
if __name__ == "__main__":
a = np.random.random((100, 100))
#this works
click(a)
#this doesn't work
shiftclick(a)