3

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?

Rugmangathan
  • 3,186
  • 6
  • 33
  • 44
user3560311
  • 85
  • 2
  • 6

1 Answers1

2

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.

ebarr
  • 7,704
  • 1
  • 29
  • 40