我使用matplotlib中的矩形选择器来裁剪一些图像 它可以打印我点击并释放的位置,但我无法保存它们的坐标数据。 我应该怎么做才能保存那些我点击并作为变量发布的坐标数据? 例如,在我运行代码之后,它只会打印类似(2.14,-0.62) - &gt;的内容。 (5.86,0.74)。 (2.14,-0.62)是我点击的点的坐标数据,(5.86,0.74)是我发布的点。但我希望我可以有一些变量来保存这两个坐标日期,如:xclick = 2.14,yclick = -0.62,xrelease = 5.86,yrelease = 0.74,但我找不到办法做到这一点。 我知道x,y坐标可能保存在x1,y1,x2,y2中,但是当我想调用其中的四个时,它返回“name'x1'未定义”,它们也不在我的变量explorer中。< / p>
以下是来自matplotlib示例的代码:
from __future__ import print_function
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
def line_select_callback(eclick, erelease):
print(eclick.xdata)
'eclick and erelease are the press and release events'
x1, y1 = eclick.xdata, eclick.ydata
x2, y2 = erelease.xdata, erelease.ydata
print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))
print(" The button you used were: %s %s" % (eclick.button,
erelease.button))
def toggle_selector(event):
print(' Key pressed.')
if event.key in ['Q', 'q'] and toggle_selector.RS.active:
print(' RectangleSelector deactivated.')
toggle_selector.RS.set_active(False)
if event.key in ['A', 'a'] and not toggle_selector.RS.active:
print(' RectangleSelector activated.')
toggle_selector.RS.set_active(True)
fig, current_ax = plt.subplots() # make a new plotting range
N = 100000 # If N is large one can see
x = np.linspace(0.0, 10.0, N) # improvement by use blitting!
plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something
plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5)
plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3)
print("\n click --> release")
# drawtype is 'box' or 'line' or 'none'
toggle_selector.RS = RectangleSelector(current_ax, line_select_callback,
drawtype='box', useblit=True,
button=[1, 3], # don't use middle button
minspanx=5, minspany=5,
spancoords='pixels',
interactive=True,state_modifier_keys = 'extents')
plt.connect('key_press_event', toggle_selector)
plt.show()
非常感谢你!
答案 0 :(得分:1)
变量x1
,y1
,x2
和y2
位于line_select_callback
函数的本地范围内。您可以使用global
语句将它们全局访问。
def line_select_callback(eclick, erelease):
global x1, y1, x2, y2
x1, y1 = eclick.xdata, eclick.ydata
x2, y2 = erelease.xdata, erelease.ydata
或者您可以将它们分配到全局定义的列表
click = [None,None]
release = [None,None]
def line_select_callback(eclick, erelease):
click[:] = eclick.xdata, eclick.ydata
release[:] = erelease.xdata, erelease.ydata