I use Rectangle Selector from matplotlib to crop some image
It can print the position that I click and release, but I can't save the coordinate data of them.
What should I do to save those coordinate data where I click and release as variables?
For example, after I run the code, it will only print something like(2.14, -0.62) --> (5.86, 0.74). (2.14, -0.62) is the coordinate data of the point I click and (5.86, 0.74) is the point I release. But I hope I can have some variable to save this two coordinate date like: xclick = 2.14, yclick = -0.62, xrelease = 5.86, yrelease = 0.74, but I could not find a way to do it.
I know the x,y coordinate might save in x1,y1,x2,y2, but when I want to call four of them, it return "name 'x1' is not defined" and they are also not in my variables explorer.
Below is my code from matplotlib example:
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):
'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,
print(' Key pressed.')
if event.key in ['Q', 'q'] and toggle_selector.RS.active:
print(' RectangleSelector deactivated.')
if event.key in ['A', 'a'] and not toggle_selector.RS.active:
print(' RectangleSelector activated.')
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,
button=[1, 3], # don't use middle button
interactive=True,state_modifier_keys = 'extents')
y2 are in the local scope of the
line_select_callback function. You may turn them globally accessible using the
def line_select_callback(eclick, erelease): global x1, y1, x2, y2 x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata
Or you can assign them to a globally defined list,
click = [None,None] release = [None,None] def line_select_callback(eclick, erelease): click[:] = eclick.xdata, eclick.ydata release[:] = erelease.xdata, erelease.ydata