与python的matplotlib图形交互:为选定的特征分配值

时间:2015-10-20 07:59:34

标签: python matplotlib figure

是否可以在matplotlib的图形窗口中选择一个区域来指定值,比如0?例如,我想说我想编写一个脚本,在某个点上,在图形窗口(pyplot.imshow)中显示图像,并要求用户选择一个值为0的区域? 希望这很清楚。

1 个答案:

答案 0 :(得分:2)

这很有效。在这里你有一个pcolormesh,你可以在其中点击,捕获click事件的onclick函数将处理它并将所选方块设置为零。 mpl_connect函数将onclick函数连接到button_press_event事件。您可以在点击后直接看到更新。

import numpy as np
import pylab as pl

pl.ioff()

rand_field = np.random.rand(10,10)

fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()

def onclick(event):
    indexx = int(event.xdata)
    indexy = int(event.ydata)
    print("Index ({0},{1}) will be set to zero".format(indexx, indexy))
    rand_field[indexy, indexx] = 0.
    cm.set_array(rand_field.ravel())
    event.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event', onclick)

pl.show()

在这里,您可以找到更高级的版本,可以拖动区域并处理错误,以防有人在图中外部点击。我把矩形的图画留给你了:

import numpy as np
import pylab as pl

pl.ioff()

rand_field = np.random.rand(10,10)

fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()

x_press = None
y_press = None

def onpress(event):
    global x_press, y_press
    x_press = int(event.xdata) if (event.xdata != None) else None
    y_press = int(event.ydata) if (event.ydata != None) else None

def onrelease(event):
    global x_press, y_press
    x_release = int(event.xdata) if (event.xdata != None) else None
    y_release = int(event.ydata) if (event.ydata != None) else None

    if (x_press != None and y_press != None and x_release != None and y_release != None):
        (xs, xe) = (x_press, x_release+1) if (x_press <= x_release) else (x_release, x_press+1)
        (ys, ye) = (y_press, y_release+1) if (y_press <= y_release) else (y_release, y_press+1)
        print("Slice [{0}:{1},{2}:{3}] will be set to zero".format(xs, xe, ys, ye))
        rand_field[ys:ye, xs:xe] = 0.
        cm.set_array(rand_field.ravel())
        event.canvas.draw()

    x_press = None
    y_press = None

cid_press   = fig.canvas.mpl_connect('button_press_event'  , onpress  )
cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)

pl.show()