Skip to content

Add support for clim (contrast limits) #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Dec 17, 2020
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
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,11 @@ the package.

## Reference

<!--- The below is autogenerated - do not edit --->

### The VolumeSlicer class

**class `VolumeSlicer(app, volume, *, spacing=None, origin=None, axis=0, reverse_y=True, scene_id=None, color=None, thumbnail=True)`**
**class `VolumeSlicer(app, volume, *, spacing=None, origin=None, axis=0, reverse_y=True, clim=None, scene_id=None, color=None, thumbnail=True)`**

A slicer object to show 3D image data in Dash. Upon
instantiation one can provide the following parameters:
Expand All @@ -95,6 +97,8 @@ instantiation one can provide the following parameters:
the slice is in the top-left, rather than bottom-left. Default True.
Note: setting this to False affects performance, see #12. This has been
fixed, but the fix has not yet been released with Dash.
* `clim` (tuple of `float`): the (initial) contrast limits. Default the min
and max of the volume.
* `scene_id` (`str`): the scene that this slicer is part of. Slicers
that have the same scene-id show each-other's positions with
line indicators. By default this is derived from `id(volume)`.
Expand All @@ -118,6 +122,10 @@ color can be a list of such colors, defining a colormap.

**property `VolumeSlicer.axis`** (`int`): The axis to slice.

**property `VolumeSlicer.clim`**: A `dcc.Store` representing the contrast limits as a 2-element tuple.
This value should probably not be changed too often (e.g. on slider drag)
because the thumbnail data is recreated on each change.

**property `VolumeSlicer.extra_traces`**: A `dcc.Store` that can be used as an output to define
additional traces to be shown in this slicer. The data must be
a list of dictionaries, with each dict representing a raw trace
Expand Down
3 changes: 3 additions & 0 deletions dash_slicer/docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import dash_slicer


md_seperator = "<!--- The below is autogenerated - do not edit --->" # noqa


def dedent(text):
"""Dedent a docstring, removing leading whitespace."""
lines = text.lstrip().splitlines()
Expand Down
94 changes: 65 additions & 29 deletions dash_slicer/slicer.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ class VolumeSlicer:
the slice is in the top-left, rather than bottom-left. Default True.
Note: setting this to False affects performance, see #12. This has been
fixed, but the fix has not yet been released with Dash.
* `clim` (tuple of `float`): the (initial) contrast limits. Default the min
and max of the volume.
* `scene_id` (`str`): the scene that this slicer is part of. Slicers
that have the same scene-id show each-other's positions with
line indicators. By default this is derived from `id(volume)`.
Expand All @@ -137,6 +139,7 @@ def __init__(
origin=None,
axis=0,
reverse_y=True,
clim=None,
scene_id=None,
color=None,
thumbnail=True,
Expand All @@ -161,21 +164,29 @@ def __init__(
self._axis = int(axis)
self._reverse_y = bool(reverse_y)

# Check and store contrast limits
if clim is None:
self._initial_clim = self._volume.min(), self._volume.max()
elif isinstance(clim, (tuple, list)) and len(clim) == 2:
self._initial_clim = float(clim[0]), float(clim[1])
else:
raise ValueError("The clim must be None or a 2-tuple of floats.")

# Check and store thumbnail
if not (isinstance(thumbnail, (int, bool))):
raise ValueError("thumbnail must be a boolean or an integer.")
if thumbnail is False:
self._thumbnail = False
self._thumbnail_param = None
elif thumbnail is None or thumbnail is True:
self._thumbnail = 32 # default size
self._thumbnail_param = 32 # default size
else:
thumbnail = int(thumbnail)
if thumbnail >= np.max(volume.shape[:3]):
self._thumbnail = False # dont go larger than image size
self._thumbnail_param = None # dont go larger than image size
elif thumbnail <= 0:
self._thumbnail = False # consider 0 and -1 the same as False
self._thumbnail_param = None # consider 0 and -1 the same as False
else:
self._thumbnail = thumbnail
self._thumbnail_param = thumbnail

# Check and store scene id, and generate
if scene_id is None:
Expand Down Expand Up @@ -207,8 +218,7 @@ def __init__(

# Build the slicer
self._create_dash_components()
if thumbnail:
self._create_server_callbacks()
self._create_server_callbacks()
self._create_client_callbacks()

# Note(AK): we could make some stores public, but let's do this only when actual use-cases arise?
Expand Down Expand Up @@ -271,6 +281,14 @@ def state(self):
"""
return self._state

@property
def clim(self):
"""A `dcc.Store` representing the contrast limits as a 2-element tuple.
This value should probably not be changed too often (e.g. on slider drag)
because the thumbnail data is recreated on each change.
"""
return self._clim

@property
def extra_traces(self):
"""A `dcc.Store` that can be used as an output to define
Expand Down Expand Up @@ -377,31 +395,31 @@ def _subid(self, name, use_dict=False, **kwargs):
assert not kwargs
return self._context_id + "-" + name

def _slice(self, index):
def _slice(self, index, clim):
"""Sample a slice from the volume."""
# Sample from the volume
indices = [slice(None), slice(None), slice(None)]
indices[self._axis] = index
im = self._volume[tuple(indices)]
return (im.astype(np.float32) * (255 / im.max())).astype(np.uint8)
Copy link
Contributor

Choose a reason for hiding this comment

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

If I understand well, before having clim the contrast could vary as the slice changed, since the max of the slice was used?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Nicely spotted! Yes, it did. I think I originally meant to scale to the volume min/max, but accidentally used the im instead.

im = self._volume[tuple(indices)].astype(np.float32)
# Apply contrast limits
clim = min(clim), max(clim)
im = (im - clim[0]) * (255 / (clim[1] - clim[0]))
im[im < 0] = 0
im[im > 255] = 255
return im.astype(np.uint8)

def _create_dash_components(self):
"""Create the graph, slider, figure, etc."""
info = self._slice_info

# Prep low-res slices. The get_thumbnail_size() is a bit like
# a simulation to get the low-res size.
if not self._thumbnail:
thumbnail_size = None
if self._thumbnail_param is None:
info["thumbnail_size"] = info["size"]
else:
thumbnail_size = self._thumbnail
info["thumbnail_size"] = get_thumbnail_size(
info["size"][:2], thumbnail_size
info["size"][:2], self._thumbnail_param
)
thumbnails = [
img_array_to_uri(self._slice(i), thumbnail_size)
for i in range(info["size"][2])
]

# Create the figure object - can be accessed by user via slicer.graph.figure
self._fig = fig = plotly.graph_objects.Figure(data=[])
Expand Down Expand Up @@ -451,8 +469,11 @@ def _create_dash_components(self):
# A dict of static info for this slicer
self._info = Store(id=self._subid("info"), data=info)

# A list of contrast limits
self._clim = Store(id=self._subid("clim"), data=self._initial_clim)

# A list of low-res slices, or the full-res data (encoded as base64-png)
self._thumbs_data = Store(id=self._subid("thumbs"), data=thumbnails)
self._thumbs_data = Store(id=self._subid("thumbs"), data=[])

# A list of mask slices (encoded as base64-png or null)
self._overlay_data = Store(id=self._subid("overlay"), data=[])
Expand Down Expand Up @@ -482,6 +503,7 @@ def _create_dash_components(self):

self._stores = [
self._info,
self._clim,
self._thumbs_data,
self._overlay_data,
self._server_data,
Expand All @@ -498,15 +520,29 @@ def _create_server_callbacks(self):
app = self._app

@app.callback(
Output(self._server_data.id, "data"),
[Input(self._state.id, "data")],
Output(self._thumbs_data.id, "data"),
[Input(self._clim.id, "data")],
)
def upload_requested_slice(state):
if state is None or not state["index_changed"]:
return dash.no_update
index = state["index"]
slice = img_array_to_uri(self._slice(index))
return {"index": index, "slice": slice}
def upload_thumbnails(clim):
return [
img_array_to_uri(self._slice(i, clim), self._thumbnail_param)
for i in range(self.nslices)
]

if self._thumbnail_param is not None:
# The callback to push full-res slices to the client is only needed
# if the thumbnails are not already full-res.

@app.callback(
Output(self._server_data.id, "data"),
[Input(self._state.id, "data"), Input(self._clim.id, "data")],
)
def upload_requested_slice(state, clim):
if state is None or not state["index_changed"]:
return dash.no_update
index = state["index"]
slice = img_array_to_uri(self._slice(index, clim))
return {"index": index, "slice": slice}

def _create_client_callbacks(self):
"""Create the callbacks that run client-side."""
Expand Down Expand Up @@ -714,7 +750,7 @@ def _create_client_callbacks(self):
State(self._info.id, "data"),
State(self._graph.id, "figure"),
],
# prevent_initial_call=True,
prevent_initial_call=True,
)

# ----------------------------------------------------------------------
Expand Down Expand Up @@ -770,9 +806,9 @@ def _create_client_callbacks(self):
Input(self._slider.id, "value"),
Input(self._server_data.id, "data"),
Input(self._overlay_data.id, "data"),
Input(self._thumbs_data.id, "data"),
],
[
State(self._thumbs_data.id, "data"),
State(self._info.id, "data"),
State(self._img_traces.id, "data"),
],
Expand Down
31 changes: 31 additions & 0 deletions examples/contrast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
A small example demonstrating contrast limits.
"""

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
from dash_slicer import VolumeSlicer
import imageio


app = dash.Dash(__name__, update_title=None)

vol = imageio.volread("imageio:stent.npz")
slicer = VolumeSlicer(app, vol, clim=(0, 1000))
clim_slider = dcc.RangeSlider(
id="clim-slider", min=vol.min(), max=vol.max(), value=(0, 1000)
)

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


@app.callback(Output(slicer.clim.id, "data"), [Input("clim-slider", "value")])
def update_clim(value):
Copy link
Contributor

Choose a reason for hiding this comment

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

beautifully simple!

return value


if __name__ == "__main__":
# Note: dev_tools_props_check negatively affects the performance of VolumeSlicer
app.run_server(debug=True, dev_tools_props_check=False)
12 changes: 7 additions & 5 deletions examples/slicer_with_3_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@

# Read volumes and create slicer objects
vol = imageio.volread("imageio:stent.npz")
slicer0 = VolumeSlicer(app, vol, axis=0)
slicer1 = VolumeSlicer(app, vol, axis=1)
slicer2 = VolumeSlicer(app, vol, axis=2)
slicer0 = VolumeSlicer(app, vol, clim=(0, 800), axis=0)
slicer1 = VolumeSlicer(app, vol, clim=(0, 800), axis=1)
slicer2 = VolumeSlicer(app, vol, clim=(0, 800), axis=2)

# Calculate isosurface and create a figure with a mesh object
verts, faces, _, _ = marching_cubes(vol, 300, step_size=4)
Expand All @@ -34,7 +34,7 @@
app.layout = html.Div(
style={
"display": "grid",
"gridTemplateColumns": "40% 40%",
"gridTemplateColumns": "50% 50%",
},
children=[
html.Div(
Expand Down Expand Up @@ -92,7 +92,9 @@
let s = {
type: 'scatter3d',
x: xyz[0], y: xyz[1], z: xyz[2],
mode: 'lines', line: {color: state.color}
mode: 'lines', line: {color: state.color},
hoverinfo: 'skip',
showlegend: false,
};
traces.push(s);
}
Expand Down
2 changes: 1 addition & 1 deletion examples/threshold_contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

vol = imageio.volread("imageio:stent.npz")
mi, ma = vol.min(), vol.max()
slicer = VolumeSlicer(app, vol)
slicer = VolumeSlicer(app, vol, clim=(0, 800))


app.layout = html.Div(
Expand Down
2 changes: 1 addition & 1 deletion examples/threshold_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

vol = imageio.volread("imageio:stent.npz")
mi, ma = vol.min(), vol.max()
slicer = VolumeSlicer(app, vol)
slicer = VolumeSlicer(app, vol, clim=(0, 800))


app.layout = html.Div(
Expand Down
4 changes: 2 additions & 2 deletions tests/test_docs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os

from dash_slicer.docs import get_reference_docs
from dash_slicer.docs import get_reference_docs, md_seperator


HERE = os.path.dirname(os.path.abspath(__file__))
Expand All @@ -18,7 +18,7 @@ def test_that_reference_docs_in_readme_are_up_to_date():
assert os.path.isfile(filename)
with open(filename, "rb") as f:
text = f.read().decode()
_, _, ref = text.partition("## Reference")
_, _, ref = text.partition(md_seperator)
ref1 = ref.strip().replace("\r\n", "\n")
ref2 = get_reference_docs().strip()
assert (
Expand Down
19 changes: 18 additions & 1 deletion tests/test_slicer.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ def test_slicer_init():
assert isinstance(s.slider, dcc.Slider)
assert isinstance(s.stores, list)
assert all(isinstance(store, (dcc.Store, dcc.Interval)) for store in s.stores)
for store in [s.clim, s.state, s.extra_traces, s.overlay_data]:
assert isinstance(store, dcc.Store)


def test_slicer_thumbnail():
app = dash.Dash()
vol = np.random.uniform(0, 255, (100, 100, 100)).astype(np.uint8)

app = dash.Dash()
_ = VolumeSlicer(app, vol)
# Test for name pattern of server-side callback when thumbnails are used
assert any(["server-data.data" in key for key in app.callback_map])
Expand All @@ -49,6 +51,21 @@ def test_slicer_thumbnail():
assert not any(["server-data.data" in key for key in app.callback_map])


def test_clim():
app = dash.Dash()
vol = np.random.uniform(0, 255, (10, 10, 10)).astype(np.uint8)
mi, ma = vol.min(), vol.max()

s = VolumeSlicer(app, vol)
assert s._initial_clim == (mi, ma)

s = VolumeSlicer(app, vol, clim=None)
assert s._initial_clim == (mi, ma)

s = VolumeSlicer(app, vol, clim=(10, 12))
assert s._initial_clim == (10, 12)


def test_scene_id_and_context_id():
app = dash.Dash()

Expand Down
Loading