Skip to main content
 首页 » 编程设计

python之获取matplotlib中矩形选区的数据

2025年05月04日10emanlee

我试图了解 RectangleSelector 在 matplotlib 中的使用。基本上我正在用 imshow 绘制一个二维数组,然后我想用鼠标选择一个矩形部分并保存矩形的角以供稍后在脚本中使用。我在 matplotlib 文档中阅读了 RectangleSelector 的使用,但我无法获取数据。 我现在所做的是以下内容

import matplotlib as mpl 
import bumpy as np 
from matplotlib.widgets import RectangleSelector 
# let z be my 2D array 
z=np.ones((100,1000)) 
def onselect(eclick, erelease): 
  'eclick and erelease are matplotlib events at press and release' 
   print ' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata) 
   print ' endposition   : (%f, %f)' % (erelease.xdata, erelease.ydata) 
   print ' used button   : ', eclick.button 
 
fig=mpl.pylab.figure() 
ax=fig.add_subplot(111) 
ax.imshow(z,aspect='auto',origin='lower',extent=((0,100,0,1000))) 
toggle_selector.RS=RectangleSelector(ax,onselect,drawtype='box',useblit=True,button=[1,3]) 

现在使用 onselect 函数打印出矩形的最小值和最大值的 (x,y) 坐标值。但我想存储这些值以备后用。 我怎样才能做到这一点?

请您参考如下方法:

我只是创建了几个全局变量,并将 eclick.xdata、eclick.ydata、erelease.xdata 和 erelease.ydata 的值存储在全局变量中。

def onselect(eclick, erelease): 
    global index 
    global startpos 
    global endpos 
    print ' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata) 
    print ' endposition   : (%f, %f)' % (erelease.xdata, erelease.ydata) 
    print ' used button   : ', eclick.button 
    startpos[index] = [eclick.xdata, eclick.ydata] 
    endpos[index]   = [erelease.xdata, erelease.ydata] 

不确定这是否是“最佳”方式,但它确实有效:)