Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Return coordinate info on mouse click

I would like to display an image in python and allow the user to click on a specific pixel. I then want to use the x and y coordinates to perform further calculations.

So far, I've been using the event picker:

def onpick1(event):
    artist = event.artist
    if isinstance(artist, AxesImage):
        mouseevent = event.mouseevent
        x = mouseevent.xdata
        y = mouseevent.ydata
        print x,y

xaxis = frame.shape[1]
yaxis = frame.shape[0]
fig = plt.figure(figsize=(6,9))
ax = fig.add_subplot(111)
line, = [ax.imshow(frame[::-1,:], cmap='jet', extent=(0,xaxis,0,yaxis), picker=5)]
fig.canvas.mpl_connect('pick_event', onpick1)
plt.show()

Now I would really like the function onpick1() to return x and y so I can use it after plt.show() to perform further calculations.

Any suggestions?

like image 828
user3560311 Avatar asked Apr 30 '26 01:04

user3560311


1 Answers

A good lesson with GUI programming is to go object oriented. Your problem right now is that you have an asynchronous callback and you want to keep its values. You should consider packing everything up together, like:

class MyClickableImage(object):
    def __init__(self,frame):
        self.x = None
        self.y = None
        self.frame = frame
        self.fig = plt.figure(figsize=(6,9))
        self.ax = self.fig.add_subplot(111)
        xaxis = self.frame.shape[1]
        yaxis = self.frame.shape[0]
        self.im = ax.imshow(self.frame[::-1,:], 
                  cmap='jet', extent=(0,xaxis,0,yaxis), 
                  picker=5)
        self.fig.canvas.mpl_connect('pick_event', self.onpick1)
        plt.show()

    # some other associated methods go here...

    def onpick1(self,event):
        artist = event.artist
        if isinstance(artist, AxesImage):
            mouseevent = event.mouseevent
            self.x = mouseevent.xdata
            self.y = mouseevent.ydata

Now when you click on a point, it will set the x and y attributes of your class. However, if you want to perform calculations using x and y you could simply have the onpick1 method perform those calculations.

like image 189
ebarr Avatar answered May 01 '26 13:05

ebarr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!