Detecting mouse events in an image using matplotlib

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

cid = implot.canvas.mpl_connect ('button_press_event', onclick) The AxesImage object does not have a canvas attribute

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 the best way to achieve my goal. Thank you very much!

+4
source share
2 answers

The problem is that implot is a subclass of Artist that accesses the canvas instance but does not contain a link (easy to get) 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() 
+6
source

Just replace implot.canvas with implot.figure.canvas :

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

All Articles