Scripting Napari using Python#

Napari is an interactive program for working with image data. It can be programmed from Python.

In this notebook, we will open a napari viewer, add images and perform some interactions with them.

from skimage.io import imread
from skimage.filters import threshold_otsu, gaussian

Opening the napari Viewer#

In order to open the viewer, we first have to import napari

import napari

Now, we can open the viewer with the following command:

viewer = napari.Viewer()

Napari should open in a separated window. Some warning messages in the cell above are normal.

Let’s show a screenshot of the viewer here. We pass the variable viewer to the function.

napari.utils.nbscreenshot(viewer)

Opening images in napari from a notebook#

Now, let’s load some example images here and visualize them in napari. This loads a 3D image:

mri = imread("https://github.com/clEsperanto/clesperanto_example_data/raw/main/Haase_MRT_tfl3d1.tif")
mri.shape
(120, 160, 160)

To open an image in napari from a notebook, we use the command add_image() from the viewer.

viewer.add_image(mri)
<Image layer 'mri' at 0x2171b7e7700>

This adds the image as a layer in napari. The layers list can be seen at the bottom left of the screen. For now, we have a single image layer there. Let’s take a new screenshot so that it’s late reproducible what we’re doing.

napari.utils.nbscreenshot(viewer)

Visualization configuration#

We can configure how to view the data when adding it to the viewer. We can for example tune the contrast_limits.

viewer.add_image(mri, contrast_limits=(12000, 40000))

napari.utils.nbscreenshot(viewer)

We can also keep the layer that was just added to napari in a variable and modify visualization afterwwards.

image_layer = viewer.add_image(mri)

napari.utils.nbscreenshot(viewer)
image_layer.contrast_limits = (2000, 50000)
image_layer.colormap = "viridis"

napari.utils.nbscreenshot(viewer)

Removing layers#

We can also remove layers, for example the second one (that has index 1).

viewer.layers.remove(viewer.layers[1])

Or we remove the last one (on top, which has index -1).

viewer.layers.remove(viewer.layers[-1])

napari.utils.nbscreenshot(viewer)

Segmentation visualization#

You can also add a segmentation result to the viewer, which will get overlayed with the original image.

blurred = gaussian(mri, sigma=5)

binary_image = blurred > threshold_otsu(blurred)

viewer.add_labels(binary_image)

napari.utils.nbscreenshot(viewer)

Segmentation results can also be visualized with their outlines.

labels_layer = viewer.layers[-1]

labels_layer.contour = 3

napari.utils.nbscreenshot(viewer)

Exercise#

Create another viewer window and add the image https://github.com/clEsperanto/clesperanto_example_data/raw/main/Lund_000500_resampled-cropped.tif. Binarize the image, label connected components and add the result to a new viewer.