4

So I'm trying write a program that detects a mouse click on an image and saves the x,y position. I've been using matplotlib and I have it working with a basic plot, but when I try to use the same code with an image, I get the following error:

cid = implot.canvas.mpl_connect('button_press_event', onclick) 'AxesImage' object has no attribute 'canvas'

This is my code:

import matplotlib.pyplot as plt

im = plt.imread('image.PNG')
implot = plt.imshow(im)

def onclick(event):
    if event.xdata != None and event.ydata != None:
        print(event.xdata, event.ydata)
cid = implot.canvas.mpl_connect('button_press_event', onclick)

plt.show()

Let me know if you have any ideas on how to fix this or a better way to achieve my goal. Thanks so much!

4

2 回答 2

10

The problem is that implot is a sub-class of Artist which draws to a canvas instance, but does not contain a (easy to get to) reference to the canvas. The attribute you are looking for is an attribute of the figure class.

You want to do:

ax = plt.gca()
fig = plt.gcf()
implot = ax.imshow(im)

def onclick(event):
    if event.xdata != None and event.ydata != None:
        print(event.xdata, event.ydata)
cid = fig.canvas.mpl_connect('button_press_event', onclick)

plt.show()
于 2013-03-30T23:28:10.523 回答
3

Simply replace implot.canvas with implot.figure.canvas:

cid = implot.figure.canvas.mpl_connect('button_press_event', onclick)
于 2014-04-30T18:00:25.333 回答