In notebook: Getting updated source.data after boxedittool

Hi!

I’m using bokeh in a jupyter notebook.
And i’m trying to use the boxedittool to select patches of a plotted image and to get back the selected boxes’ properties in the python code.
But the source.data[‘x’/‘y’…] doen’t contain the new values.
(iv’e alse tried to push them to the source.data in js_on_change(“data”, CustomJS manner)

is this possible? is there another more elegant way to implement my task rather than using boxedittool?

here the core code:

img = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE).astype('float') / 255
width, height = img.shape

palette = ['#%02x%02x%02x' %(i,i,i) for i in range(256)]
fig = figure(tools="pan,wheel_zoom,box_edit,reset,box_zoom,box_select")
fig.y_range = Range1d(0, height, bounds=(0, height))
fig.x_range = Range1d(0, width, bounds=(0, width))
imfig = fig.image(image=[img[::-1,:,...]], x=[0], y=[0], dw=[width], dh=[height], palette=palette)

src = ColumnDataSource({
    'x': [0], 'y': [0], 'width': [0],
    'height': [0], 'alpha': [0]
})


renderer = fig.rect('x', 'y', 'width', 'height', source=src, alpha='alpha')

draw_tool = BoxEditTool(renderers=[renderer], empty_value=1)
fig.add_tools(draw_tool)
fig.toolbar.active_drag = draw_tool

show(fig, notebook_handle=True)

Hope you can help me,
Thank you very much :smile:

When you call show on a plain Bokeh object (e.g. a plot) you are generating standalone HTML output, that has no further direct connection to any Python process. If you want to get updates back from BokehJS that you can respond to, that requires a Bokeh server app. [1] (The Bokeh serve is the thing that maintains automatic synchronization between the JS and Python sides of things). Fortunately Bokeh server apps can be embedded directly in a running notebook. Here is a complete example:

bokeh/notebook_embed.ipynb at branch-3.0 · bokeh/bokeh · GitHub


  1. It is possible to use push_notebook to push changes to update existing output in a notebook, but that is a one-way operation. Getting data and events back requires the Bokeh server (unless you want to resort to hacky things like calling kernel.execute from JavaScript, to run Python code that updates the notebook state. I don’t advise). ↩︎

Thank you very much for the detailed answer!
This community is really great :slight_smile:

2 Likes