Matplotlib捕获错误的鼠标坐标

时间:2017-05-21 01:31:46

标签: python matplotlib

目标是在图像上单击鼠标两次并检索2个坐标。这样做的代码:

class ImageListener(object):

def __init__(self):
    self.coordinates = []

def onclick(self, event):
    print(event.x, event.y)
    self.coordinates.extend([event.x, event.y])

def show_image(self, img, close=True):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(img)
    cid = fig.canvas.mpl_connect('button_press_event', self.onclick)
    while len(self.coordinates) < 3:
        plt.waitforbuttonpress(0)
    if close:
        plt.close(fig)

    fig.canvas.mpl_disconnect(cid)

但是,捕获的坐标是错误的。在下图中,单击时鼠标位于(700,333)。 (截图期间鼠标消失)。相反,(514,154)被捕获。

enter image description here

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

问题在于您使用event.xevent.y

  • x:x位置 - 画布左侧的像素

  • y:y位置 - 画布底部的像素

如果您想在数据坐标中使用鼠标坐标,则应使用:

  • xdata:x coord of mouse in data coords
  • ydata:y coord of mouse in data coords

请参阅doc