使用matplotlib检测图像中的鼠标事件 [英] Detecting mouse event in an image with matplotlib

查看:1809
本文介绍了使用matplotlib检测图像中的鼠标事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试编写一个程序来检测图像上的鼠标点击并保存x,y位置。我一直在使用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'对象没有属性'canvas'

cid = implot.canvas.mpl_connect('button_press_event', onclick) 'AxesImage' object has no attribute '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()

如果您对如何解决此问题或更好的方法有任何想法,请告诉我。实现我的目标。非常感谢!

Let me know if you have any ideas on how to fix this or a better way to achieve my goal. Thanks so much!

推荐答案

问题是 implot 是一个子-class of Artist ,它绘制到 canvas 实例,但不包含(易于获取)引用画布。您要查找的属性是数字类的属性。

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.

您想要这样做:

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

这篇关于使用matplotlib检测图像中的鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆