Detecting mouse event in an image with matplotlib

隐身守侯 提交于 2019-12-07 08:30:27

问题


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!


回答1:


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



回答2:


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

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


来源:https://stackoverflow.com/questions/15721094/detecting-mouse-event-in-an-image-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!