Interactive image visualization with napari#

napari is a python-based image viewer. This notebooks demonstrates how to remote control it from python.

See also

For opening an image, we still use scikit-image:

from skimage.io import imread

image = imread('../../data/blobs.tif')

# print out the spatial dimensions of the image
image.shape
(254, 256)
import napari

# Create an empty viewer
viewer = napari.Viewer()
Public access to Window.qt_viewer is deprecated and will be removed in
v0.5.0. It is considered an "implementation detail" of the napari
application, not part of the napari viewer model. If your use case
requires access to qt_viewer, please open an issue to discuss.
# Add a new layer containing an image
viewer.add_image(image)
<Image layer 'image' at 0x1cbb0d69070>

With this command, we can make a screenshot of napari and save it in our notebook.

napari.utils.nbscreenshot(viewer)
# Remove all layers to start from scratch
for l in viewer.layers:
    viewer.layers.remove(l)

napari.utils.nbscreenshot(viewer)
# add the image again and modify the lookup table
layer = viewer.add_image(image)

layer.colormap = 'green'

napari.utils.nbscreenshot(viewer)
# modify brightness & contrast
layer.contrast_limits = (0, 128)

napari.utils.nbscreenshot(viewer)

Image segmentation#

We now blur the image and put it in the viewer

from skimage.filters import gaussian
blurred_image = gaussian(image, sigma=2)

# Add to napari
viewer.add_image(blurred_image)

napari.utils.nbscreenshot(viewer)

We now threshold the image and add it to the viewer as a labels layer

from skimage.filters import threshold_otsu
threshold = threshold_otsu(blurred_image)
print(threshold)
binary_image = blurred_image > threshold

# Add a new labels layer containing an image
binary_layer = viewer.add_labels(binary_image, name="binary image")

napari.utils.nbscreenshot(viewer)
0.48307635389561887
# hide the binary image to make the next step better visible
binary_layer.visible = False

Connected component labeling allows us to identify individual objects.

from skimage.measure import label
label_image = label(binary_image)

# add labels to viewer
label_layer = viewer.add_labels(label_image)

You can visualize labelled objects as overlay (per default)

napari.utils.nbscreenshot(viewer)

… or as opaque contours

label_layer.contour = 1
label_layer.opacity = 1

napari.utils.nbscreenshot(viewer)