Skip to content

napari segmentation example #280

@will-moore

Description

@will-moore

This uses code from https://napari.org/stable/tutorials/segmentation/annotate_segmentation.html

I have tested this workflow with an RGB image from IDR, exported with Batch_Image_Export, but you can also simply save https://idr.openmicroscopy.org/webclient/render_image/179764/0/0/ and import it...

Then, using napari-omero open it in napari with $ omero napari view Image:ID

Copy the code from the link above - you just need the imports (maybe not all needed) and the segment() method.
Specifically I copied this code and pasted it into napari terminal...

import numpy as np
from skimage import data
from skimage.filters import threshold_otsu
from skimage.segmentation import clear_border
from skimage.measure import label, regionprops_table
from skimage.morphology import closing, square, remove_small_objects
import napari


def segment(image):
    """Segment an image using an intensity threshold determined via
    Otsu's method.

    Parameters
    ----------
    image : np.ndarray
        The image to be segmented

    Returns
    -------
    label_image : np.ndarray
        The resulting image where each detected object labeled with a unique integer.
    """
    # apply threshold
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(4))

    # remove artifacts connected to image border
    cleared = remove_small_objects(clear_border(bw), 20)

    # label image regions
    label_image = label(cleared)

    return label_image

Then you can use the first "Red" layer from the RGB, slice it to 2D (required by code above) and compute() to turn it from a dask array into a numpy array, which also seems to be needed.

image = viewer.layers[0].data
image.shape
>>> (1, 1, 1024, 1344)
plane = image[0, 0]
plane = plane.compute()

Now we can use the segment() method we created above to give us labels...
Then we add back 2 dimensions to get back to 4D (shape is (1, 1, 1024, 1344) again) which seems to be needed for saving to OMERO.

labels = segment(plane)
lab3d = np.expand_dims(labels, axis=0)
lab4d = np.expand_dims(lab3d, axis=0)

Finally, we can add the labels to the viewer to see them in napari...

viewer.add_labels(lab4d)

Screenshot 2023-10-30 at 15 21 51

Then you can hit Save ROIs to OMERO and you should see the labels saved as new Masks in OMERO:

Screenshot 2023-10-30 at 15 23 10

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions