在Python中用鼠标单击获取图像的像素坐标

时间:2019-02-13 19:58:16

标签: python mouseclick-event

我确定这将是一个简单的任务,但是经过两天的搜索和实施,我无法解决它。

目标很容易:我想从2D图像中提取像素坐标,并用鼠标单击它,然后,我想将这些坐标用于不同的计算。

我发现使用不同的库实现了不同的实现,并且更有趣的解决方案如下:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
def onclick(event):
    print('you pressed', event.key, event.xdata, event.ydata)
    X_coordinate = event.xdata
    Y_coordinate = event.ydata

cid = fig.canvas.mpl_connect('button_press_event', onclick)
lines, = plt.plot([1,2,3])
plt.show()

现在,我的问题是找出两个变量(X_coordinate和Y_coordinate),并将其用于其他用途。

我尝试了从此处(how to return a value from button_press_event matplotlib?)复制的以下解决方案,以尝试提取X_coordinate,但不起作用:

import matplotlib.pyplot as plt
import numpy as np
mutable_object = {} 
fig = plt.figure()
def onclick(event):
    print('you pressed', event.key, event.xdata, event.ydata)
    X_coordinate = event.xdata
    Y_coordinate = event.ydata
    mutable_object['click'] = X_coordinate

cid = fig.canvas.mpl_connect('button_press_event', onclick)
lines, = plt.plot([1,2,3])
X_coordinate = mutable_object['key']
plt.show()

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我认为问题可能在于在函数定义中使用了mutable_object ['click']而在函数外部使用了mutable_object ['key']。键“ key”不在字典mutable_object中。

import matplotlib.pyplot as plt
import numpy as np
mutable_object = {} 
fig = plt.figure()
def onclick(event):
    print('you pressed', event.key, event.xdata, event.ydata)
    X_coordinate = event.xdata
    Y_coordinate = event.ydata
    mutable_object['click'] = X_coordinate

cid = fig.canvas.mpl_connect('button_press_event', onclick)
lines, = plt.plot([1,2,3])
plt.show()
X_coordinate = mutable_object['click']
print(X_coordinate)

下面粘贴的示例来自matplotlib文档,从长远来看,可能是更好的方法。基本思想是创建一个将点击位置存储在属性中的对象。单击完成后即可调用此属性。

from matplotlib import pyplot as plt

class LineBuilder:
    def __init__(self, line):
        self.line = line
        self.xs = list(line.get_xdata())
        self.ys = list(line.get_ydata())
        self.cid = line.figure.canvas.mpl_connect('button_press_event', self)

    def __call__(self, event):
        print('click', event)
        if event.inaxes!=self.line.axes: return
        self.xs.append(event.xdata)
        self.ys.append(event.ydata)
        self.line.set_data(self.xs, self.ys)
        self.line.figure.canvas.draw()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0])  # empty line
linebuilder = LineBuilder(line)

plt.show()