Created
July 6, 2022 14:07
-
-
Save alisterburt/1652abe1dab714b3e1e4f9da76ab0227 to your computer and use it in GitHub Desktop.
simple evented model demo in napari
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Tuple | |
| import napari | |
| import scipy.ndimage as ndi | |
| import numpy as np | |
| from psygnal import EventedModel | |
| viewer = napari.Viewer(ndisplay=3) | |
| mask_layer = viewer.add_image(mask := np.zeros((128, 128, 128))) | |
| class SphericalMaskParameters(EventedModel): | |
| """simple evented model (dataclass) with parameters for mask creation""" | |
| sidelength: int | |
| position: Tuple[int, int, int] | |
| radius: int | |
| def create_sphere_mask(mask_parameters: SphericalMaskParameters) -> np.ndarray: | |
| """Create a spherical mask with specific parameters""" | |
| ones = np.ones((128, 128, 128)) | |
| ones[mask_parameters.position] = 0 | |
| edt = ndi.distance_transform_edt(ones) | |
| mask = np.logical_and(edt < mask_parameters.radius, edt != 0) | |
| return mask | |
| # instantiate the mask parameters class | |
| parameters = SphericalMaskParameters(sidelength=128, position=(64, 64, 64), radius=20) | |
| # define a callback which will be called whenever field values on the model change | |
| def update_viewer(): | |
| """callback to update mask data in the viewer""" | |
| global parameters, mask_layer | |
| mask = create_sphere_mask(parameters) | |
| mask_layer.data = mask | |
| # connect events from evented model so that GUI is updated | |
| parameters.events.sidelength.connect(update_viewer) | |
| parameters.events.position.connect(update_viewer) | |
| parameters.events.radius.connect(update_viewer) | |
| # put local variables in the napari console so they can be played with from napari | |
| viewer.window._qt_viewer.console.push(locals()) | |
| napari.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment