使用matplotlib矩形时不能使用坐标变量

2024-05-19 13:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Matplotlib中的矩形选择器示例来裁剪图像,但每次运行此代码时,都会显示“NameError:name'x1'is not defined”,但我已经将它们定义为全局变量,并在line_select_回调函数中命名它们。我原以为当我点击释放的时候,我点击释放的坐标数据会保存在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)]

非常感谢你!在


Tags: importlinebuttonpltselectorprintx1x2