Python:如何使用matplotlib.canvas获取鼠标点击的坐标

时间:2015-02-27 05:22:57

标签: python matplotlib coordinates

我正在写一个类来处理图像。在那个类中,我想定义一个方法,可以让我返回鼠标点击的坐标。我可以将坐标作为属性,但如果我调用方法返回坐标,我会得到一个空元组

以下是代码:

import cv2
import matplotlib.pyplot as plt

class TestClass():
    def __init__(self):
        self.fname = 'image.jpg'
        self.img = cv2.imread(self.fname)
        self.point = ()

    def getCoord(self):
        fig = plt.figure()
        ax = fig.add_subplot(111)
        plt.imshow(self.img)
        cid = fig.canvas.mpl_connect('button_press_event', self.__onclick__)
        return self.point

    def __onclick__(self,click):
        self.point = (click.xdata,click.ydata)
        return self.point

1 个答案:

答案 0 :(得分:1)

只要我在plt.show() mpl_connect之后插入getCoord,您的代码就适用于我:

def getCoord(self):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.imshow(self.img)
    cid = fig.canvas.mpl_connect('button_press_event', self.__onclick__)
    plt.show()
    return self.point
相关问题