我尝试使用Matplotlib中的这个矩形选择器示例来裁剪图像,但每次运行此代码时,它都会显示“NameError:name'x1'未定义”,但我已将它们定义为全局变量并命名它们在line_select_callback函数中。我原本认为当我点击并释放时,我点击和释放的坐标数据将保存在x1,x2,y1,y2中,然后我将能够使用它们来裁剪原始图像,但似乎出现了问题,我不知道为什么。
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
def line_select_callback(eclick, erelease):
global x1, y1, x2, y2
'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 = plt.figure()
ax = fig.add_subplot(111)
filename="C:\\Users\\motorsgroup\\Desktop\\test.png"
im = Image.open(filename)
arr = np.asarray(im)
plt_image=plt.imshow(arr)
print("\n click --> release")
# drawtype is 'box' or 'line' or 'none'
toggle_selector.RS = RectangleSelector(ax, line_select_callback,
drawtype='box', useblit=True,
button=[1, 3], # don't use middle button
minspanx=5, minspany=5,
spancoords='pixels',
interactive=True)
plt.connect('key_press_event', toggle_selector)
plt.show()
newim = arr[int(x1):int(x2),int(y2):int(y1)]
非常感谢你!