Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
First poc by almarklein · Pull Request #2 · plotly/dash-slicer · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' First poc by almarklein · Pull Request #2 · plotly/dash-slicer · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' First poc by almarklein · Pull Request #2 · plotly/dash-slicer · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' First poc by almarklein · Pull Request #2 · plotly/dash-slicer · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' First poc by almarklein · Pull Request #2 · plotly/dash-slicer · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' First poc by almarklein · Pull Request #2 · plotly/dash-slicer · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); First poc by almarklein · Pull Request #2 · plotly/dash-slicer · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
__pycache__
*.pyc
*.pyo
*.egg-info
dist/
build/
33 changes: 32 additions & 1 deletion README.md
Original file line numberDiff line numberDiff line change
@@ -1 +1,32 @@
# dash-3d-viewer
# dash-3d-viewer

A tool to make it easy to build slice-views on 3D image data, in Dash apps.

The API is currently a WIP.


## Installation

Eventually, this would be pip-installable. For now, use the developer workflow.


## Usage

TODO, see the examples.


## License

This code is distributed under MIT license.


## Developers


* Make sure that you have Python with the appropriate dependencies installed, e.g. via `venv`.
* Run `pip install -e .` to do an in-place install of the package.
* Run the examples using e.g. `python examples/slicer_with_1_view.py`

* Use `black .` to autoformat.
* Use `flake8 .` to lint.
* Use `pytest .` to run the tests.
10 changes: 10 additions & 0 deletions dash_3d_viewer/__init__.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
"""
Dash 3d viewer - a tool to make it easy to build slice-views on 3D image data.
"""


from .slicer import DashVolumeSlicer # noqa: F401


__version__ = "0.0.1"
version_info = tuple(map(int, __version__.split(".")))
192 changes: 192 additions & 0 deletions dash_3d_viewer/slicer.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
import numpy as np
from plotly.graph_objects import Figure
from dash import Dash
from dash.dependencies import Input, Output, State
from dash_core_components import Graph, Slider, Store

from .utils import gen_random_id, img_array_to_uri


class DashVolumeSlicer:
"""A slicer to show 3D image data in Dash."""

def __init__(self, app, volume, axis=0, id=None):
if not isinstance(app, Dash):
raise TypeError("Expect first arg to be a Dash app.")
# Check and store volume
if not (isinstance(volume, np.ndarray) and volume.ndim == 3):
raise TypeError("Expected volume to be a 3D numpy array")
self._volume = volume
# Check and store axis
if not (isinstance(axis, int) and 0 <= axis <= 2):
raise ValueError("The given axis must be 0, 1, or 2.")
self._axis = int(axis)
# Check and store id
if id is None:
id = gen_random_id()
elif not isinstance(id, str):
raise TypeError("Id must be a string")
self._id = id

# Get the slice size (width, height), and max index
arr_shape = list(volume.shape)
arr_shape.pop(self._axis)
slice_size = list(reversed(arr_shape))
self._max_index = self._volume.shape[self._axis] - 1

# Create the figure object
fig = Figure()
fig.update_layout(
template=None,
margin=dict(l=0, r=0, b=0, t=0, pad=4),
)
fig.update_xaxes(
showgrid=False,
range=(0, slice_size[0]),
showticklabels=False,
zeroline=False,
)
fig.update_yaxes(
showgrid=False,
scaleanchor="x",
range=(slice_size[1], 0), # todo: allow flipping x or y
showticklabels=False,
zeroline=False,
)
# Add an empty layout image that we can populate from JS.
fig.add_layout_image(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we sent you code where the image was added as a layout image but the more "modern" way of doing this is to use an Image trace like in https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L68 and https://github.com/plotly/dash-sample-apps/blob/master/apps/dash-covid-xray/app.py#L418. This way you can get hover and click events on image pixels, which is not the case with a layout image

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that the two examples used different methods, and I assumed that layout images where easier, but will change this :) I think I'll do that in a new PR. Are there any other differences? E.g. I saw that with layout images one can create a stack of them and use alpha blending to overlay e.g. segmentation results. Is that possible with image traces as well?

dict(
source="",
xref="x",
yref="y",
x=0,
y=0,
sizex=slice_size[0],
sizey=slice_size[1],
sizing="contain",
layer="below",
)
)
# Wrap the figure in a graph
# todo: or should the user provide this?
self.graph = Graph(
id=self._subid("graph"),
figure=fig,
config={"scrollZoom": True},
)
# Create a slider object that the user can put in the layout (or not)
self.slider = Slider(
id=self._subid("slider"),
min=0,
max=self._max_index,
step=1,
value=self._max_index // 2,
updatemode="drag",
)
# Create the stores that we need (these must be present in the layout)
self.stores = [
Store(id=self._subid("slice-index"), data=volume.shape[self._axis] // 2),
Store(id=self._subid("_requested-slice-index"), data=0),
Store(id=self._subid("_slice-data"), data=""),
]

self._create_server_callbacks(app)
self._create_client_callbacks(app)
Comment thread
almarklein marked this conversation as resolved.

def _subid(self, subid):
"""Given a subid, get the full id including the slicer's prefix."""
return self._id + "-" + subid

def _slice(self, index):
"""Sample a slice from the volume."""
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
return self._volume[tuple(indices)]

def _create_server_callbacks(self, app):
"""Create the callbacks that run server-side."""

@app.callback(
Output(self._subid("_slice-data"), "data"),
[Input(self._subid("_requested-slice-index"), "data")],
)
def upload_requested_slice(slice_index):
slice = self._slice(slice_index)
slice = (slice.astype(np.float32) * (255 / slice.max())).astype(np.uint8)
return [slice_index, img_array_to_uri(slice)]

def _create_client_callbacks(self, app):
"""Create the callbacks that run client-side."""

app.clientside_callback(
"""
function handle_slider_move(index) {
return index;
}
""",
Output(self._subid("slice-index"), "data"),
[Input(self._subid("slider"), "value")],
)

app.clientside_callback(
"""
function handle_slice_index(index) {
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
if (slice_cache[index]) {
return window.dash_clientside.no_update;
} else {
console.log('requesting slice ' + index)
return index;
}
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("_requested-slice-index"), "data"),
[Input(self._subid("slice-index"), "data")],
)

# app.clientside_callback("""
# function update_slider_pos(index) {
# return index;
# }
# """,
# [Output("slice-index", "data")],
# [State("slider", "value")],
# )

app.clientside_callback(
"""
function handle_incoming_slice(index, index_and_data, ori_figure) {
let new_index = index_and_data[0];
let new_data = index_and_data[1];
// Store data in cache
if (!window.slicecache_for_{{ID}}) { window.slicecache_for_{{ID}} = {}; }
let slice_cache = window.slicecache_for_{{ID}};
slice_cache[new_index] = new_data;
// Get the data we need *now*
let data = slice_cache[index];
// Maybe we do not need an update
if (!data) {
return window.dash_clientside.no_update;
}
if (data == ori_figure.layout.images[0].source) {
return window.dash_clientside.no_update;
}
// Otherwise, perform update
console.log("updating figure");
let figure = {...ori_figure};
figure.layout.images[0].source = data;
return figure;
}
""".replace(
"{{ID}}", self._id
),
Output(self._subid("graph"), "figure"),
[
Input(self._subid("slice-index"), "data"),
Input(self._subid("_slice-data"), "data"),
],
[State(self._subid("graph"), "figure")],
)
19 changes: 19 additions & 0 deletions dash_3d_viewer/utils.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
import random

import PIL.Image
import skimage
from plotly.utils import ImageUriValidator


def gen_random_id(n=6):
return "".join(random.choice("abcdefghijklmnopqrtsuvwxyz") for i in range(n))


def img_array_to_uri(img_array):
Comment thread
almarklein marked this conversation as resolved.
img_array = skimage.util.img_as_ubyte(img_array)
# todo: leverage this Plotly util once it becomes part of the public API (also drops the Pillow dependency)
# from plotly.express._imshow import _array_to_b64str
# return _array_to_b64str(img_array)
img_pil = PIL.Image.fromarray(img_array)
uri = ImageUriValidator.pil_image_to_uri(img_pil)
return uri
20 changes: 20 additions & 0 deletions examples/slicer_with_1_view.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
"""
A truly minimal example.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer = DashVolumeSlicer(app, vol)

app.layout = html.Div([slicer.graph, slicer.slider, *slicer.stores])


if __name__ == "__main__":
app.run_server(debug=False)
46 changes: 46 additions & 0 deletions examples/slicer_with_2_views.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
"""
An example with two slicers on the same volume.
"""

import dash
import dash_html_components as html
from dash_3d_viewer import DashVolumeSlicer
import imageio


app = dash.Dash(__name__)

vol = imageio.volread("imageio:stent.npz")
slicer1 = DashVolumeSlicer(app, vol, axis=1, id="slicer1")
slicer2 = DashVolumeSlicer(app, vol, axis=2, id="slicer2")

app.layout = html.Div(
style={
"display": "grid",
"grid-template-columns": "40% 40%",
},
children=[
html.Div(
[
html.H1("Coronal"),
slicer1.graph,
html.Br(),
slicer1.slider,
*slicer1.stores,
]
),
html.Div(
[
html.H1("Sagittal"),
slicer2.graph,
html.Br(),
slicer2.slider,
*slicer2.stores,
]
),
],
)


if __name__ == "__main__":
app.run_server(debug=True)
Loading