4

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. it is working for me as well. Now I agree with my professor who once said that "it's harder to debug your own code than someone else" . Omitting that line, made me spending hours trying to find the bug. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.