Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GenevieveBuckley/26ba4c61b092a7548c9bc97100b7fad4 to your computer and use it in GitHub Desktop.
Save GenevieveBuckley/26ba4c61b092a7548c9bc97100b7fad4 to your computer and use it in GitHub Desktop.
Choose a threshold value using a magicgui widget in napari.
"""Choose a threshold value using a magicgui widget in napari.
Based on the magicgui excample script napari_parameter_sweep.py
https://github.com/napari/magicgui/blob/main/examples/napari_param_sweep.py
"""
import napari
import skimage.data
import skimage.filters
from napari.layers import Image
from napari.types import LabelsData
from magicgui import magicgui
# create a viewer and add some images
viewer = napari.Viewer()
viewer.add_image(skimage.data.astronaut().mean(-1), name="astronaut")
viewer.add_image(skimage.data.grass().astype("float"), name="grass")
# turn the gaussian blur function into a magicgui
# for details on why the `-> ImageData` return annotation works:
# https://napari.org/guides/magicgui.html#return-annotations
@magicgui(
# tells magicgui to call the function whenever a parameter changes
auto_call=True,
# `widget_type` to override the default (spinbox) "float" widget
thresh={"widget_type": "IntSlider", "max": 255},
layout="horizontal",
)
def threshold(layer: Image, thresh: int = 10, dark_background: bool = False) -> LabelsData:
"""Choose a threshold value for the ``layer``."""
if layer:
if dark_background is False:
return layer.data > thresh
else:
return layer.data < thresh
# Add it to the napari viewer
viewer.window.add_dock_widget(threshold, area="bottom")
napari.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment