Write labels

Storing labels data alongside image data is a key application and feature of the ome-zarr file standard. First, let’s create some image data:

import os

import numpy as np
import zarr
from skimage.data import binary_blobs

from ome_zarr.writer import write_image, write_labels

path = "test_ngff_image_with_labels.zarr"
os.mkdir(path)

mean_val = 10
size = 64
rng = np.random.default_rng(0)
data = rng.poisson(mean_val, size=(size, size, size)).astype(np.uint8)

root = zarr.open_group(path, mode="w")
write_image(image=data, group=root, axes="zyx")
[]

In a next step, we create some dummy labels data:

# add labels...
blobs = binary_blobs(length=size, volume_fraction=0.1, n_dim=3).astype('int8')
blobs2 = binary_blobs(length=size, volume_fraction=0.1, n_dim=3).astype('int8')
# blobs will contain values of 1, 2 and 0 (background)
blobs += 2 * blobs2

We now need to create a new zarr group inside the hierarchy of the ome-zarr file to tore the labels data. By doing this, the hierarchy inside the ome-zarr file will look like this:

test_ngff_image_with_labels.zarr
├── zarr.json
├── labels
│   ├── zarr.json
│   └── blobs
|       ├── .zarr.json
|       ├── s0
|       └── s1
├── s0
└── s1
# write the labels to /labels
labels_grp = root.create_group("labels")

label_name = "blobs"
label_grp = labels_grp.create_group(label_name)
write_labels(blobs, label_grp, axes="zyx", name=label_name)
[]