kthouz
kthouz

Reputation: 411

Python: how to get coordinates on mouse click using matplotlib.canvas

I am writing a class to process images. In that class, I want to define a method that can allow me to return coordinates of the mouse clicks. I can get the coordinates as an attribute but if I call the method to return the coordinates, I get an empty tuple

Here is the code:

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

Upvotes: 4

Views: 9328

Answers (1)

Andrey Sobolev
Andrey Sobolev

Reputation: 12693

Your code works for me, as long as I insert plt.show() after mpl_connect in 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

Upvotes: 3

Related Questions