如何在散景中选择图像的区域

时间:2016-10-14 08:26:11

标签: bokeh

在网络应用中,我想让用户使用散景的漂亮的盒子/套索选择工具在绘制的图像中选择感兴趣的区域。我希望在python中接收选定的像素以进行进一步的操作。

对于散点图,这很容易与gallery

类似
import bokeh.plotting
import numpy as np

# data
X = np.linspace(0, 10, 20)
def f(x): return np.random.random(len(x))

# plot and add to document
fig = bokeh.plotting.figure(x_range=(0, 10), y_range=(0, 10),
    tools="pan,wheel_zoom,box_select,lasso_select,reset")
plot = fig.scatter(X, f(X))
#plot = fig.image([np.random.random((10,10))*255], dw=[10], dh=[10])
bokeh.plotting.curdoc().add_root(fig)

# callback
def callback(attr, old, new):
    # easily access selected points:
    print sorted(new['1d']['indices'])
    print sorted(plot.data_source.selected['1d']['indices'])
    plot.data_source.data = {'x':X, 'y':f(X)}
plot.data_source.on_change('selected', callback)

但是如果我用

替换散点图
plot = fig.image([np.random.random((10,10))*255], dw=[10], dh=[10])

然后使用图像上的选择工具不会改变plot.data_source.selected中的任何内容。

我确定这是预期的行为(也是有意义的),但如果我想选择图像的像素呢?我当然可以在图像的顶部放置一个不可见的散点网格,但有没有更优雅的方法来实现这一点?

1 个答案:

答案 0 :(得分:0)

听起来您正在寻找的工具实际上是BoxEditTool。请注意,BoxEditTool需要一个字形列表(通常是Rect实例),这些字形将呈现ROI,并且应使用以下命令设置侦听更改:

rect_glyph_source.on_change('data', callback)

只要您对投资回报率进行任何更改,这就会触发callback功能。

相关的ColumnDataSource实例(在此示例中为rect_glyph_source)将被更新,以使“ x”和“ y”键列出图像坐标空间中每个ROI的中心,当然还包括“ width”和“高度”描述其大小。据我所知,目前还没有内置的方法来提取数据本身,因此您将必须执行以下操作:

rois = rect_glyph_source.data
roi_index = 0 # x, y, width and height are lists, and each ROI has its own index

x_center = rois['x'][roi_index]
width = rois['width'][roi_index]
y_center = rois['y'][roi_index]
height = rois['height'][roi_index]

x_start = int(x_center - 0.5 * width)
x_end = int(x_center + 0.5 * width)
y_start = int(y_center - 0.5 * height)
y_end = int(y_center + 0.5 * height)

roi_data = image_plot.source.data['image'][0][y_start:y_end, x_start:x_end]

重要:在Bokeh的当前版本(0.13.0)中,服务器上BoxEditTool的同步存在问题,并且无法正常工作。这应该在Bokeh的下一个正式版本中修复。有关更多信息和临时解决方案,请参见this answerthis discussion