Image processing 使用matplotlib检测图像中的鼠标事件

Image processing 使用matplotlib检测图像中的鼠标事件,image-processing,matplotlib,mouseevent,Image Processing,Matplotlib,Mouseevent,所以我试着写一个程序,检测鼠标点击图像并保存x,y位置。我一直在使用matplotlib,我让它处理基本绘图,但当我尝试对图像使用相同的代码时,我得到以下错误: cid=implot.canvas.mpl\u connect('button\u press\u event',onclick) “AxeImage”对象没有属性“canvas” 这是我的代码: import matplotlib.pyplot as plt im = plt.imread('image.PNG') implot =

所以我试着写一个程序,检测鼠标点击图像并保存x,y位置。我一直在使用matplotlib,我让它处理基本绘图,但当我尝试对图像使用相同的代码时,我得到以下错误:

cid=implot.canvas.mpl\u connect('button\u press\u event',onclick) “AxeImage”对象没有属性“canvas”

这是我的代码:

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

如果你对如何解决这个问题有任何想法,或者有更好的方法来实现我的目标,请告诉我。非常感谢

问题在于,
implot
Artist
的一个子类,它绘制到
canvas
实例,但不包含对canvas的引用(易于获取)。您要查找的属性是
figure
类的属性

您要执行以下操作:

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

只需将
implot.canvas
替换为
implot.figure.canvas

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

对我不明白为什么情节有画布,而IMPLAT没有。这太完美了。非常感谢。@user2227523如果这解决了您的问题,您能接受它吗(左边的大灰色复选标记)?它为我们两人提供了代表,并为未来用户解决了问题。@user2227523无需担心。欢迎来到SO!