user2227523
user2227523

Reputation: 63

Detecting mouse event in an image with matplotlib

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!

Upvotes: 6

Views: 11880

Answers (2)

ealfonso
ealfonso

Reputation: 7302

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

cid = implot.figure.canvas.mpl_connect('button_press_event', onclick)

Upvotes: 3

tacaswell
tacaswell

Reputation: 87376

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()

Upvotes: 11

Related Questions