Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 977
user2227523 Avatar asked Dec 12 '22 16:12

user2227523


1 Answers

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()
like image 131
tacaswell Avatar answered Apr 01 '23 15:04

tacaswell