saeyslab / napari-sparrow

https://sparrow-pipeline.readthedocs.io/en/latest/
Other
19 stars 0 forks source link

labels to shapes function #184

Open julienmortier opened 7 months ago

julienmortier commented 7 months ago

I often find myself needing to convert a shapes layer to a labels layer, but currently there is no function in sparrow that does this (not that I can find anyway). I have currently needed it in of 2 flavors:

1) Converting the cell segmentation shapes to a labels mask where the cell indexes are preserved. 2) Converting a region annotation to a binary mask

Based on some suggestions from Arne, I currently use the functions below, but it would be more streamlined if a more general single function would be implemented in sparrow. However, I am not exactly sure how to properly do this myself within the sparrow codebase:) Also, I wonder whether these types of functions are something that would fit better within the spatialdata package itself?

import rasterio.features
from affine import Affine

def create_labels_from_shapes(sdata, shapes_layer: str, out_shape: list, output_layer: str):

    transform = Affine.translation(0, 0)

    masks = rasterio.features.rasterize(
        zip(
            sdata[shapes_layer].geometry,
            sdata[shapes_layer].index.values.astype(float),
        ),
        out_shape=out_shape,
        dtype="uint32",
        fill=0,
        transform=transform
    )

    sdata = sp.im._add_label_layer(sdata, arr=masks, chunks=1024, output_layer=output_layer)

    return sdata
import rasterio.features
from affine import Affine

def create_binary_mask_from_shapes(sdata, shapes_layer: str, out_shape: list, output_layer: str):

    transform = Affine.translation(0, 0)

    masks = rasterio.features.rasterize(
        sdata[shapes_layer].geometry,
        out_shape=out_shape,
        dtype="uint8",
        fill=0,
        transform=transform,
        default_value=1,
    )

    sdata = sp.im._add_label_layer(sdata, arr=masks, chunks=1024, output_layer=output_layer)

    return sdata
lopollar commented 5 months ago

Hey Julien, I use the same functions, but they are indeed not built in into SPArrOW. (We do use them internally). I don't know exactly where we should build them in SPArrOW, I have some other functions too like this that we could call 'handy extra's', but this will be difficult to make user-friendly.

ArneDefauw commented 5 months ago

This is implemented in the sparrow fork https://github.com/saeyslab/harpy, see https://github.com/saeyslab/harpy/blob/bfb8f5843df1580a17fb8634c8d3d4b704cc0aae/src/sparrow/_tests/test_image/test_shapes_to_labels.py#L7 for usage. It can be moved to the main branch it this would be necessary