Skip to content

zarrnii.atlas

Atlas handling via ZarrNiiAtlas, including TemplateFlow integration for brain atlas operations.

Atlas handling module for ZarrNii.

This module provides functionality for working with brain atlases through TemplateFlow, specifically BIDS-formatted dseg.nii.gz segmentation images with corresponding dseg.tsv lookup tables. It enables region-of-interest (ROI) based analysis and aggregation of data across atlas regions.

Based on functionality from SPIMquant: https://github.com/khanlab/SPIMquant/blob/main/spimquant/workflow/scripts/

Classes

zarrnii.atlas.ZarrNiiAtlas(darr=None, axes_order='ZYX', orientation='RAS', xyz_orientation=None, ngff_image=None, spacing=(1.0, 1.0, 1.0), origin=(0.0, 0.0, 0.0), name='image', _omero=None, affine=None, **kwargs)

Bases: ZarrNii

Brain atlas with segmentation image and region lookup table.

Represents a brain atlas consisting of a segmentation image (dseg) that assigns integer labels to brain regions, and a lookup table (tsv) that maps these labels to region names and other metadata.

Extension of ZarrNii to support atlas label tables.

Inherits all functionality from ZarrNii and adds support for storing region/label metadata in a pandas DataFrame.

Attributes

labels_df : pandas.DataFrame DataFrame containing label information for the atlas. label_column : str Name of the column in labels_df containing label indices. name_column : str Name of the column in labels_df containing region names. abbrev_column : str Name of the column in labels_df containing region abbreviations.

Source code in zarrnii/core.py
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
def __init__(
    self,
    darr=None,
    axes_order="ZYX",
    orientation="RAS",
    xyz_orientation=None,
    ngff_image=None,
    spacing: Tuple[float, float, float] = (1.0, 1.0, 1.0),
    origin: Tuple[float, float, float] = (0.0, 0.0, 0.0),
    name: str = "image",
    _omero: Optional[object] = None,
    affine: Optional[AffineTransform] = None,
    **kwargs,
):
    """
    Constructor with backward compatibility for old signature.

    Raises:
        ValueError: If affine parameter is provided
    """
    # Check for deprecated affine parameter
    if affine is not None:
        raise ValueError(
            "The 'affine' parameter is no longer supported in ZarrNii(). "
            "Please use 'spacing' and 'origin' parameters instead. "
            "If you need to specify a full affine transformation, use from_nifti() "
            "or construct the NgffImage directly."
        )

    # Handle backwards compatibility: if xyz_orientation is provided, use it
    # Otherwise, use orientation for backwards compatibility
    final_orientation = (
        xyz_orientation if xyz_orientation is not None else orientation
    )

    if ngff_image is not None:
        # New signature
        object.__setattr__(self, "ngff_image", ngff_image)
        object.__setattr__(self, "axes_order", axes_order)
        object.__setattr__(self, "xyz_orientation", final_orientation)
        object.__setattr__(self, "_omero", _omero)
    elif darr is not None:
        # Legacy signature - delegate to from_darr
        instance = self.from_darr(
            darr=darr,
            axes_order=axes_order,
            orientation=final_orientation,
            spacing=spacing,
            origin=origin,
            name=name,
            omero=_omero,
            **kwargs,
        )
        object.__setattr__(self, "ngff_image", instance.ngff_image)
        object.__setattr__(self, "axes_order", instance.axes_order)
        object.__setattr__(self, "xyz_orientation", instance.xyz_orientation)
        object.__setattr__(self, "_omero", instance._omero)
    else:
        raise ValueError("Must provide either ngff_image or darr")

Attributes

zarrnii.atlas.ZarrNiiAtlas.dseg property

Return self as the segmentation image (for compatibility with API).

Functions

zarrnii.atlas.ZarrNiiAtlas.create_from_dseg(dseg, labels_df, **kwargs) classmethod

Create ZarrNiiAtlas from a dseg ZarrNii and labels DataFrame.

Parameters:

  • dseg (ZarrNii) –

    ZarrNii segmentation image

  • labels_df (DataFrame) –

    DataFrame containing label information

  • **kwargs

    Additional keyword arguments for label/name/abbrev columns

Returns:

  • ZarrNiiAtlas instance

Source code in zarrnii/atlas.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
@classmethod
def create_from_dseg(cls, dseg: ZarrNii, labels_df: pd.DataFrame, **kwargs):
    """Create ZarrNiiAtlas from a dseg ZarrNii and labels DataFrame.

    Args:
        dseg: ZarrNii segmentation image
        labels_df: DataFrame containing label information
        **kwargs: Additional keyword arguments for label/name/abbrev columns

    Returns:
        ZarrNiiAtlas instance
    """
    if not isinstance(dseg, ZarrNii):
        raise TypeError(f"dseg must be a ZarrNii instance, got {type(dseg)}")

    # Note: attrs strips leading underscore from _omero in __init__ signature
    # so we pass it as 'omero' instead of '_omero'
    return cls(
        ngff_image=dseg.ngff_image,
        axes_order=dseg.axes_order,
        xyz_orientation=dseg.xyz_orientation,
        omero=getattr(dseg, "_omero", None),
        labels_df=labels_df,
        **kwargs,
    )
zarrnii.atlas.ZarrNiiAtlas.from_files(dseg_path, labels_path, **kwargs) classmethod

Load ZarrNiiAtlas from dseg image and labels TSV files.

Parameters:

  • dseg_path (Union[str, Path]) –

    Path to segmentation image (NIfTI or OME-Zarr)

  • labels_path (Union[str, Path]) –

    Path to labels TSV file

  • **kwargs

    Additional arguments passed to ZarrNii.from_file()

Returns:

  • ZarrNiiAtlas instance

Source code in zarrnii/atlas.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
@classmethod
def from_files(
    cls, dseg_path: Union[str, Path], labels_path: Union[str, Path], **kwargs
):
    """Load ZarrNiiAtlas from dseg image and labels TSV files.

    Args:
        dseg_path: Path to segmentation image (NIfTI or OME-Zarr)
        labels_path: Path to labels TSV file
        **kwargs: Additional arguments passed to ZarrNii.from_file()

    Returns:
        ZarrNiiAtlas instance
    """
    # Load segmentation image
    dseg = ZarrNii.from_file(str(dseg_path), **kwargs)

    # Load labels dataframe
    labels_df = pd.read_csv(str(labels_path), sep="\t")

    # Create atlas instance using create_from_dseg
    return cls.create_from_dseg(dseg, labels_df)
zarrnii.atlas.ZarrNiiAtlas.from_itksnap_lut(path, lut_path, **kwargs) classmethod

Construct from itksnap lut file.

Source code in zarrnii/atlas.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
@classmethod
def from_itksnap_lut(cls, path, lut_path, **kwargs):
    """
    Construct from itksnap lut file.
    """
    znii = super().from_file(path, **kwargs)
    labels_df = cls._import_itksnap_lut(lut_path)
    return cls(
        ngff_image=znii.ngff_image,
        axes_order=znii.axes_order,
        xyz_orientation=znii.xyz_orientation,
        labels_df=labels_df,
        omero=getattr(znii, "_omero", None),
    )
zarrnii.atlas.ZarrNiiAtlas.from_csv_lut(path, lut_path, **kwargs) classmethod

Construct from csv lut file.

Source code in zarrnii/atlas.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
@classmethod
def from_csv_lut(cls, path, lut_path, **kwargs):
    """
    Construct from csv lut file.
    """
    znii = super().from_file(path, **kwargs)
    labels_df = cls._import_csv_lut(lut_path)
    return cls(
        ngff_image=znii.ngff_image,
        axes_order=znii.axes_order,
        xyz_orientation=znii.xyz_orientation,
        labels_df=labels_df,
        omero=getattr(znii, "_omero", None),
    )
zarrnii.atlas.ZarrNiiAtlas.from_tsv_lut(path, lut_path, **kwargs) classmethod

Construct from tsv lut file.

Source code in zarrnii/atlas.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
@classmethod
def from_tsv_lut(cls, path, lut_path, **kwargs):
    """
    Construct from tsv lut file.
    """
    znii = super().from_file(path, **kwargs)
    labels_df = cls._import_tsv_lut(lut_path)
    return cls(
        ngff_image=znii.ngff_image,
        axes_order=znii.axes_order,
        xyz_orientation=znii.xyz_orientation,
        labels_df=labels_df,
        omero=getattr(znii, "_omero", None),
    )
zarrnii.atlas.ZarrNiiAtlas.from_labelmapper_lut(path, lut_path, **kwargs) classmethod

Construct from labelmapper lut file.

Source code in zarrnii/atlas.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
@classmethod
def from_labelmapper_lut(cls, path, lut_path, **kwargs):
    """
    Construct from labelmapper lut file.
    """
    znii = super().from_file(path, **kwargs)
    labels_df = cls._import_labelmapper_lut(lut_path)
    return cls(
        ngff_image=znii.ngff_image,
        axes_order=znii.axes_order,
        xyz_orientation=znii.xyz_orientation,
        labels_df=labels_df,
        omero=getattr(znii, "_omero", None),
    )
zarrnii.atlas.ZarrNiiAtlas.get_region_info(region_id)

Get information about a specific region.

Parameters:

  • region_id (Union[int, str]) –

    Region identifier (int label, name, or abbreviation)

Returns:

  • Dict[str, Any]

    Dictionary containing region information

Raises:

  • ValueError

    If region not found in atlas

Source code in zarrnii/atlas.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
def get_region_info(self, region_id: Union[int, str]) -> Dict[str, Any]:
    """Get information about a specific region.

    Args:
        region_id: Region identifier (int label, name, or abbreviation)

    Returns:
        Dictionary containing region information

    Raises:
        ValueError: If region not found in atlas
    """
    label = self._resolve_region_identifier(region_id)

    # Find the region in labels DataFrame
    region_row = self.labels_df[self.labels_df[self.label_column] == label]
    if region_row.empty:
        raise ValueError(f"Region with label {label} not found in atlas")

    return region_row.iloc[0].to_dict()
zarrnii.atlas.ZarrNiiAtlas.get_region_mask(region_id)

Create binary mask for a specific region.

Parameters:

  • region_id (Union[int, str]) –

    Region identifier (int label, name, or abbreviation)

Returns:

  • ZarrNii

    ZarrNii instance containing binary mask (1 for region, 0 elsewhere)

Raises:

  • ValueError

    If region not found in atlas

Source code in zarrnii/atlas.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def get_region_mask(self, region_id: Union[int, str]) -> ZarrNii:
    """Create binary mask for a specific region.

    Args:
        region_id: Region identifier (int label, name, or abbreviation)

    Returns:
        ZarrNii instance containing binary mask (1 for region, 0 elsewhere)

    Raises:
        ValueError: If region not found in atlas
    """
    label = self._resolve_region_identifier(region_id)

    # Validate that the region exists in our labels_df
    if not (self.labels_df[self.label_column] == label).any():
        raise ValueError(f"Region with label {label} not found in atlas")

    # Create binary mask
    mask_data = (self.dseg.data == label).astype(np.uint8)

    mask_ngff = _derive_ngff_image(
        self.dseg.ngff_image,
        data=mask_data,
        name=f"{self.name}_masked",
    )

    return ZarrNii.from_ngff_image(
        mask_ngff,
        xyz_orientation=self.dseg.xyz_orientation,
        axes_order=self.dseg.axes_order,
        omero=self.dseg.omero,
    )
zarrnii.atlas.ZarrNiiAtlas.get_region_volume(region_id)

Calculate volume of a specific region in mm³.

Parameters:

  • region_id (Union[int, str]) –

    Region identifier (int label, name, or abbreviation)

Returns:

  • float

    Volume in cubic millimeters

Raises:

  • ValueError

    If region not found in atlas

Source code in zarrnii/atlas.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
def get_region_volume(self, region_id: Union[int, str]) -> float:
    """Calculate volume of a specific region in mm³.

    Args:
        region_id: Region identifier (int label, name, or abbreviation)

    Returns:
        Volume in cubic millimeters

    Raises:
        ValueError: If region not found in atlas
    """
    label = self._resolve_region_identifier(region_id)

    # Count voxels with this label
    dseg_data = self.dseg.data
    if hasattr(dseg_data, "compute"):
        voxel_count = int((dseg_data == label).sum().compute())
    else:
        voxel_count = int((dseg_data == label).sum())

    # Calculate volume using voxel size from affine
    # Volume per voxel = abs(det(affine[:3, :3]))
    voxel_volume = abs(np.linalg.det(self.dseg.affine[:3, :3]))

    return float(voxel_count * voxel_volume)
zarrnii.atlas.ZarrNiiAtlas.aggregate_image_by_regions(image, aggregation_func='mean', background_label=0, column_name=None, column_suffix=None)

Aggregate image values by atlas regions.

Parameters:

  • image (ZarrNii) –

    Image to aggregate (must be compatible with atlas)

  • aggregation_func (str, default: 'mean' ) –

    Aggregation function ('mean', 'sum', 'std', 'median', 'min', 'max')

  • background_label (int, default: 0 ) –

    Label value to treat as background (excluded from results)

  • column_name (str, default: None ) –

    String to use for column name. If None, uses f"{aggregation_func}_value"

  • column_suffix (str, default: None ) –

    (Deprecated) String suffix to append to column name. Use column_name instead. If provided, column_name will be set to f"{aggregation_func}_{column_suffix}".

Returns:

  • DataFrame

    DataFrame with columns: index, name, {column_name}, volume

  • DataFrame

    (e.g., with defaults: index, name, mean_value, volume)

Raises:

  • ValueError

    If image and atlas are incompatible

.. deprecated:: 0.2.0 The column_suffix parameter is deprecated. Use column_name instead.

Source code in zarrnii/atlas.py
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
def aggregate_image_by_regions(
    self,
    image: ZarrNii,
    aggregation_func: str = "mean",
    background_label: int = 0,
    column_name: str = None,
    column_suffix: str = None,
) -> pd.DataFrame:
    """Aggregate image values by atlas regions.

    Args:
        image: Image to aggregate (must be compatible with atlas)
        aggregation_func: Aggregation function ('mean', 'sum', 'std', 'median', 'min', 'max')
        background_label: Label value to treat as background (excluded from results)
        column_name: String to use for column name. If None, uses f"{aggregation_func}_value"
        column_suffix: (Deprecated) String suffix to append to column name.
            Use column_name instead. If provided, column_name will be set to
            f"{aggregation_func}_{column_suffix}".

    Returns:
        DataFrame with columns: index, name, {column_name}, volume
        (e.g., with defaults: index, name, mean_value, volume)

    Raises:
        ValueError: If image and atlas are incompatible

    .. deprecated:: 0.2.0
        The `column_suffix` parameter is deprecated. Use `column_name` instead.
    """
    # Handle deprecated column_suffix parameter
    if column_suffix is not None:
        warnings.warn(
            "The 'column_suffix' parameter is deprecated and will be removed in a "
            "future version. Use 'column_name' instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        if column_name is None:
            column_name = f"{aggregation_func}_{column_suffix}"

    # Set default column name if not provided
    if column_name is None:
        column_name = f"{aggregation_func}_value"

    # Validate image compatibility
    if not np.array_equal(image.shape, self.dseg.shape):
        raise ValueError(
            f"Image shape {image.shape} doesn't match atlas shape {self.dseg.shape}"
        )

    if not np.allclose(image.affine, self.dseg.affine, atol=1e-6):
        warnings.warn(
            "Image and atlas affines don't match exactly. "
            "Results may be spatially inconsistent."
        )

    # Get all unique labels (excluding background)
    dseg_data = self.dseg.data
    if hasattr(dseg_data, "compute"):
        dseg_data = dseg_data.compute()
    unique_labels = np.unique(dseg_data)
    unique_labels = unique_labels[unique_labels != background_label]

    results = []
    for label in unique_labels:
        # Create mask for this region
        mask = self.dseg.data == label

        # Extract image values for this region
        region_values = image.data[mask]

        # Skip if no voxels (shouldn't happen with unique labels)
        if region_values.size == 0:
            continue

        # Compute aggregation
        if hasattr(region_values, "compute"):
            # Dask array - need to compute
            if aggregation_func == "mean":
                agg_value = float(region_values.mean().compute())
            elif aggregation_func == "sum":
                agg_value = float(region_values.sum().compute())
            elif aggregation_func == "std":
                agg_value = float(region_values.std().compute())
            elif aggregation_func == "median":
                agg_value = float(np.median(region_values.compute()))
            elif aggregation_func == "min":
                agg_value = float(region_values.min().compute())
            elif aggregation_func == "max":
                agg_value = float(region_values.max().compute())
            else:
                raise ValueError(
                    f"Unknown aggregation function: {aggregation_func}. "
                    "Supported: mean, sum, std, median, min, max"
                )
        else:
            # NumPy array - direct computation
            if aggregation_func == "mean":
                agg_value = float(region_values.mean())
            elif aggregation_func == "sum":
                agg_value = float(region_values.sum())
            elif aggregation_func == "std":
                agg_value = float(region_values.std())
            elif aggregation_func == "median":
                agg_value = float(np.median(region_values))
            elif aggregation_func == "min":
                agg_value = float(region_values.min())
            elif aggregation_func == "max":
                agg_value = float(region_values.max())
            else:
                raise ValueError(
                    f"Unknown aggregation function: {aggregation_func}. "
                    "Supported: mean, sum, std, median, min, max"
                )

        # Get region info
        try:
            region_info = self.get_region_info(int(label))
            region_name = region_info[self.name_column]
        except ValueError:
            region_name = f"Unknown_Region_{label}"

        # Calculate volume
        volume = self.get_region_volume(int(label))

        results.append(
            {
                self.label_column: int(label),
                self.name_column: region_name,
                column_name: agg_value,
                "volume": volume,
            }
        )

    return pd.DataFrame(results)
zarrnii.atlas.ZarrNiiAtlas.create_feature_map(feature_data, feature_column, label_column='index')

Create feature map by assigning values to atlas regions.

Parameters:

  • feature_data (DataFrame) –

    DataFrame with region labels and feature values. If multiple rows share the same label index (e.g., from regionprops tables), their feature values are aggregated using the mean before mapping.

  • feature_column (str) –

    Column name containing feature values to map

  • label_column (str, default: 'index' ) –

    Column name containing region labels

Returns:

  • ZarrNii

    ZarrNii instance with feature values mapped to regions

Raises:

  • ValueError

    If required columns are missing

Notes

When multiple rows in feature_data have the same atlas label, their feature values are aggregated using the mean. This is useful when working with regionprops tables where each region may have multiple entries.

Labels present in the dseg image but not in feature_data will be mapped to 0.0. This can occur with downsampled dseg images or small ROIs where some regions are not represented.

Performance: This method computes the maximum label in the dseg image to properly size the lookup table. For large images, this requires a single reduction pass over the data, which is acceptable given that the subsequent map_blocks operation will also scan the entire dataset.

Source code in zarrnii/atlas.py
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
def create_feature_map(
    self,
    feature_data: pd.DataFrame,
    feature_column: str,
    label_column: str = "index",
) -> ZarrNii:
    """Create feature map by assigning values to atlas regions.

    Args:
        feature_data: DataFrame with region labels and feature values.
            If multiple rows share the same label index (e.g., from
            regionprops tables), their feature values are aggregated
            using the mean before mapping.
        feature_column: Column name containing feature values to map
        label_column: Column name containing region labels

    Returns:
        ZarrNii instance with feature values mapped to regions

    Raises:
        ValueError: If required columns are missing

    Notes:
        When multiple rows in feature_data have the same atlas label,
        their feature values are aggregated using the mean. This is
        useful when working with regionprops tables where each region
        may have multiple entries.

        Labels present in the dseg image but not in feature_data will be
        mapped to 0.0. This can occur with downsampled dseg images or
        small ROIs where some regions are not represented.

        Performance: This method computes the maximum label in the dseg
        image to properly size the lookup table. For large images, this
        requires a single reduction pass over the data, which is
        acceptable given that the subsequent map_blocks operation will
        also scan the entire dataset.
    """
    # Validate input
    required_cols = [label_column, feature_column]
    missing_cols = [col for col in required_cols if col not in feature_data.columns]
    if missing_cols:
        raise ValueError(f"Missing columns in feature_data: {missing_cols}")

    # Aggregate feature values by label using mean when multiple rows exist
    aggregated_data = (
        feature_data.groupby(label_column)[feature_column].mean().reset_index()
    )

    dseg_data = self.dseg.data.astype("int")  # dask array of labels

    # Get max label from feature_data
    max_label_features = int(aggregated_data[label_column].max())

    # Get max label from dseg image to ensure LUT is large enough
    # for all labels that actually exist in the image.
    # This prevents IndexError when dseg contains labels not in feature_data.
    max_label_dseg = int(dseg_data.max().compute())

    # Use the larger of the two to size the LUT
    max_label = max(max_label_features, max_label_dseg)

    # make a dense lookup array sized to handle all labels in dseg
    lut = np.zeros(max_label + 1, dtype=np.float32)
    lut[aggregated_data[label_column].to_numpy(dtype=int)] = aggregated_data[
        feature_column
    ].to_numpy(dtype=float)

    # broadcast the mapping in one go
    feature_map = dseg_data.map_blocks(lambda block: lut[block], dtype=np.float32)

    feature_map_ngff = _derive_ngff_image(
        self.dseg.ngff_image,
        data=feature_map,
        name=f"{self.name}_feature_map",
    )

    return ZarrNii.from_ngff_image(
        feature_map_ngff,
        xyz_orientation=self.dseg.xyz_orientation,
        axes_order=self.dseg.axes_order,
        omero=self.dseg.omero,
    )
zarrnii.atlas.ZarrNiiAtlas.get_region_bounding_box(region_ids=None, regex=None)

Get bounding box in physical coordinates for selected regions.

This method computes the spatial extents (bounding box) of one or more atlas regions in physical/world coordinates. The returned bounding box can be used directly with the crop method to extract a subvolume containing the selected regions.

Parameters:

  • region_ids (Union[int, str, List[Union[int, str]]], default: None ) –

    Region identifier(s) to include in bounding box. Can be: - Single int: label index - Single str: region name or abbreviation - List[int/str]: multiple regions by index, name, or abbreviation - None: use regex parameter instead

  • regex (Optional[str], default: None ) –

    Regular expression to match region names. If provided, region_ids must be None. Case-insensitive matching.

Returns:

  • Tuple[float, float, float]

    Tuple of (bbox_min, bbox_max) where each is a tuple of (x, y, z)

  • Tuple[float, float, float]

    coordinates in physical/world space (mm). These can be passed

  • Tuple[Tuple[float, float, float], Tuple[float, float, float]]

    directly to ZarrNii.crop() method with physical_coords=True.

Raises:

  • ValueError

    If no regions match the selection criteria, or if both region_ids and regex are provided/omitted

  • TypeError

    If region_ids contains invalid types

Examples:

>>> # Get bounding box for single region
>>> bbox_min, bbox_max = atlas.get_region_bounding_box("Hippocampus")
>>> cropped = image.crop(bbox_min, bbox_max, physical_coords=True)
>>>
>>> # Get bounding box for multiple regions
>>> bbox_min, bbox_max = atlas.get_region_bounding_box(["Hippocampus", "Amygdala"])
>>>
>>> # Use regex to select regions
>>> bbox_min, bbox_max = atlas.get_region_bounding_box(regex="Hip.*")
>>>
>>> # Crop atlas itself to region
>>> cropped_atlas = atlas.crop(bbox_min, bbox_max, physical_coords=True)
Notes
  • Bounding box is in physical coordinates (mm), not voxel indices
  • Axes ordering is relative to self.axes_order (e.g. ZYX for ome zarr)
  • The bounding box is the union of all selected regions
  • Use the returned values with crop(physical_coords=True)
Source code in zarrnii/atlas.py
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
def get_region_bounding_box(
    self,
    region_ids: Union[int, str, List[Union[int, str]]] = None,
    regex: Optional[str] = None,
) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
    """Get bounding box in physical coordinates for selected regions.

    This method computes the spatial extents (bounding box) of one or more
    atlas regions in physical/world coordinates. The returned bounding box
    can be used directly with the crop method to extract a subvolume
    containing the selected regions.

    Args:
        region_ids: Region identifier(s) to include in bounding box. Can be:
            - Single int: label index
            - Single str: region name or abbreviation
            - List[int/str]: multiple regions by index, name, or abbreviation
            - None: use regex parameter instead
        regex: Regular expression to match region names. If provided,
            region_ids must be None. Case-insensitive matching.

    Returns:
        Tuple of (bbox_min, bbox_max) where each is a tuple of (x, y, z)
        coordinates in physical/world space (mm). These can be passed
        directly to ZarrNii.crop() method with physical_coords=True.

    Raises:
        ValueError: If no regions match the selection criteria, or if both
            region_ids and regex are provided/omitted
        TypeError: If region_ids contains invalid types

    Examples:
        >>> # Get bounding box for single region
        >>> bbox_min, bbox_max = atlas.get_region_bounding_box("Hippocampus")
        >>> cropped = image.crop(bbox_min, bbox_max, physical_coords=True)
        >>>
        >>> # Get bounding box for multiple regions
        >>> bbox_min, bbox_max = atlas.get_region_bounding_box(["Hippocampus", "Amygdala"])
        >>>
        >>> # Use regex to select regions
        >>> bbox_min, bbox_max = atlas.get_region_bounding_box(regex="Hip.*")
        >>>
        >>> # Crop atlas itself to region
        >>> cropped_atlas = atlas.crop(bbox_min, bbox_max, physical_coords=True)

    Notes:
        - Bounding box is in physical coordinates (mm), not voxel indices
        - Axes ordering is relative to self.axes_order (e.g. ZYX for ome zarr)
        - The bounding box is the union of all selected regions
        - Use the returned values with crop(physical_coords=True)
    """
    import re

    import dask.array as da

    # Validate input parameters
    if region_ids is None and regex is None:
        raise ValueError("Must provide either region_ids or regex parameter")
    if region_ids is not None and regex is not None:
        raise ValueError("Cannot provide both region_ids and regex parameters")

    # Determine which labels to include
    selected_labels = []

    if regex is not None:
        # Match regions using regex
        pattern = re.compile(regex, re.IGNORECASE)
        for _, row in self.labels_df.iterrows():
            region_name = str(row[self.name_column])
            if pattern.search(region_name):
                selected_labels.append(int(row[self.label_column]))

        if not selected_labels:
            raise ValueError(f"No regions matched regex pattern: {regex}")
    else:
        # Convert region_ids to list if single value
        if not isinstance(region_ids, list):
            region_ids = [region_ids]

        # Resolve each region identifier to label
        for region_id in region_ids:
            label = self._resolve_region_identifier(region_id)
            selected_labels.append(label)

    # Create union mask of all selected regions
    dseg_data = self.dseg.data
    mask = None
    for label in selected_labels:
        region_mask = dseg_data == label
        if mask is None:
            mask = region_mask
        else:
            mask = mask | region_mask

    # Find voxel coordinates where mask is True
    # da.where returns tuple of arrays (one per dimension in data array)
    indices = da.where(mask)

    # Compute the indices to get actual coordinates
    indices_computed = [idx.compute() for idx in indices]

    # Check if any voxels were found
    if any(idx.size == 0 for idx in indices_computed):
        raise ValueError(f"No voxels found for selected regions: {selected_labels}")

    # Get the spatial dimensions from dims (skip non-spatial like 'c', 't')
    spatial_dims_lower = [d.lower() for d in ["x", "y", "z"]]
    spatial_indices = []
    for i, dim in enumerate(self.dseg.dims):
        if dim.lower() in spatial_dims_lower:
            spatial_indices.append(i)

    # Extract spatial coordinates from indices
    # indices_computed has one array per dimension in data
    voxel_coords = []
    for spatial_idx in spatial_indices:
        voxel_coords.append(indices_computed[spatial_idx])

    # Get min and max for each spatial dimension
    voxel_mins = [int(coords.min()) for coords in voxel_coords]
    voxel_maxs = [
        int(coords.max()) + 1 for coords in voxel_coords
    ]  # +1 for inclusive max

    # Now we have voxel coordinates in the order they appear in dims
    # We don't need to convert to (x, y, z) order for physical coordinates
    #  since the affine should do this already..

    # make homog coords so we can matrix mult
    voxel_min_xyz = np.array(
        [
            voxel_mins[0],
            voxel_mins[1],
            voxel_mins[2],
            1.0,
        ]
    )
    voxel_max_xyz = np.array(
        [
            voxel_maxs[0],
            voxel_maxs[1],
            voxel_maxs[2],
            1.0,
        ]
    )

    # Transform to physical coordinates using affine
    affine_matrix = self.dseg.affine.matrix
    physical_min = affine_matrix @ voxel_min_xyz
    physical_max = affine_matrix @ voxel_max_xyz

    # Return as tuples of (x, y, z) in physical space
    bbox_min = tuple(physical_min[:3].tolist())
    bbox_max = tuple(physical_max[:3].tolist())

    return bbox_min, bbox_max
zarrnii.atlas.ZarrNiiAtlas.sample_region_patches(n_patches, region_ids=None, regex=None, seed=None)

Sample random coordinates (centers) within atlas regions.

This method generates a list of center coordinates by randomly sampling voxels within the selected atlas regions. The returned coordinates are in physical/world space (mm) and can be used with crop_centered() to extract fixed-size patches for machine learning training or other workflows.

Parameters:

  • n_patches (int) –

    Number of patch centers to sample

  • region_ids (Union[int, str, List[Union[int, str]]], default: None ) –

    Region identifier(s) to sample from. Can be: - Single int: label index - Single str: region name or abbreviation - List[int/str]: multiple regions by index, name, or abbreviation - None: use regex parameter instead

  • regex (Optional[str], default: None ) –

    Regular expression to match region names. If provided, region_ids must be None. Case-insensitive matching.

  • seed (Optional[int], default: None ) –

    Random seed for reproducibility. If None, patches are sampled randomly each time.

Returns:

  • List[Tuple[float, float, float]]

    List of (x, y, z) coordinates in physical/world space (mm).

  • List[Tuple[float, float, float]]

    Each coordinate represents the center of a potential patch and

  • List[Tuple[float, float, float]]

    can be used with crop_centered() to extract fixed-size regions.

Raises:

  • ValueError

    If no regions match the selection criteria, if both region_ids and regex are provided/omitted, or if n_patches is less than 1

  • TypeError

    If region_ids contains invalid types

Examples:

>>> # Sample 10 patch centers from hippocampus
>>> centers = atlas.sample_region_patches(
...     n_patches=10,
...     region_ids="Hippocampus",
...     seed=42
... )
>>> # Extract 256x256x256 voxel patches at each center
>>> patches = image.crop_centered(centers, patch_size=(256, 256, 256))
>>>
>>> # Sample from multiple regions using list
>>> centers = atlas.sample_region_patches(
...     n_patches=20,
...     region_ids=[1, 2, 3],
...     seed=42
... )
>>>
>>> # Sample using regex pattern
>>> centers = atlas.sample_region_patches(
...     n_patches=5,
...     regex=".*cortex.*",
... )
Notes
  • Coordinates are in physical space (mm), not voxel indices
  • Centers are sampled uniformly from voxels within selected regions
  • Use crop_centered() to extract fixed-size patches around these centers
  • For ML training with fixed patch sizes (e.g., 256x256x256 voxels), use a lower-resolution atlas to define masks, then crop at higher resolution using physical coordinates
Source code in zarrnii/atlas.py
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
def sample_region_patches(
    self,
    n_patches: int,
    region_ids: Union[int, str, List[Union[int, str]]] = None,
    regex: Optional[str] = None,
    seed: Optional[int] = None,
) -> List[Tuple[float, float, float]]:
    """Sample random coordinates (centers) within atlas regions.

    This method generates a list of center coordinates by randomly sampling
    voxels within the selected atlas regions. The returned coordinates are
    in physical/world space (mm) and can be used with crop_centered() to
    extract fixed-size patches for machine learning training or other workflows.

    Args:
        n_patches: Number of patch centers to sample
        region_ids: Region identifier(s) to sample from. Can be:
            - Single int: label index
            - Single str: region name or abbreviation
            - List[int/str]: multiple regions by index, name, or abbreviation
            - None: use regex parameter instead
        regex: Regular expression to match region names. If provided,
            region_ids must be None. Case-insensitive matching.
        seed: Random seed for reproducibility. If None, patches are sampled
            randomly each time.

    Returns:
        List of (x, y, z) coordinates in physical/world space (mm).
        Each coordinate represents the center of a potential patch and
        can be used with crop_centered() to extract fixed-size regions.

    Raises:
        ValueError: If no regions match the selection criteria, if both
            region_ids and regex are provided/omitted, or if n_patches is
            less than 1
        TypeError: If region_ids contains invalid types

    Examples:
        >>> # Sample 10 patch centers from hippocampus
        >>> centers = atlas.sample_region_patches(
        ...     n_patches=10,
        ...     region_ids="Hippocampus",
        ...     seed=42
        ... )
        >>> # Extract 256x256x256 voxel patches at each center
        >>> patches = image.crop_centered(centers, patch_size=(256, 256, 256))
        >>>
        >>> # Sample from multiple regions using list
        >>> centers = atlas.sample_region_patches(
        ...     n_patches=20,
        ...     region_ids=[1, 2, 3],
        ...     seed=42
        ... )
        >>>
        >>> # Sample using regex pattern
        >>> centers = atlas.sample_region_patches(
        ...     n_patches=5,
        ...     regex=".*cortex.*",
        ... )

    Notes:
        - Coordinates are in physical space (mm), not voxel indices
        - Centers are sampled uniformly from voxels within selected regions
        - Use crop_centered() to extract fixed-size patches around these centers
        - For ML training with fixed patch sizes (e.g., 256x256x256 voxels),
          use a lower-resolution atlas to define masks, then crop at higher
          resolution using physical coordinates
    """
    import re

    import dask.array as da

    # Validate input
    if n_patches < 1:
        raise ValueError(f"n_patches must be at least 1, got {n_patches}")

    if region_ids is None and regex is None:
        raise ValueError("Must provide either region_ids or regex parameter")
    if region_ids is not None and regex is not None:
        raise ValueError("Cannot provide both region_ids and regex parameters")

    # Set random seed if provided
    if seed is not None:
        np.random.seed(seed)

    # Determine which labels to include (reuse logic from get_region_bounding_box)
    selected_labels = []

    if regex is not None:
        # Match regions using regex
        pattern = re.compile(regex, re.IGNORECASE)
        for _, row in self.labels_df.iterrows():
            region_name = str(row[self.name_column])
            if pattern.search(region_name):
                selected_labels.append(int(row[self.label_column]))

        if not selected_labels:
            raise ValueError(f"No regions matched regex pattern: {regex}")
    else:
        # Convert region_ids to list if single value
        if not isinstance(region_ids, list):
            region_ids = [region_ids]

        # Resolve each region identifier to label
        for region_id in region_ids:
            label = self._resolve_region_identifier(region_id)
            selected_labels.append(label)

    # Create union mask of all selected regions
    dseg_data = self.dseg.data
    mask = None
    for label in selected_labels:
        region_mask = dseg_data == label
        if mask is None:
            mask = region_mask
        else:
            mask = mask | region_mask

    # Find voxel coordinates where mask is True
    indices = da.where(mask)

    # Compute the indices to get actual coordinates
    indices_computed = [idx.compute() for idx in indices]

    # Check if any voxels were found
    if any(idx.size == 0 for idx in indices_computed):
        raise ValueError(f"No voxels found for selected regions: {selected_labels}")

    # Get number of valid voxels
    n_voxels = indices_computed[0].size

    # Sample random voxels
    # If n_patches > n_voxels, sample with replacement
    replace = n_patches > n_voxels
    sampled_indices = np.random.choice(n_voxels, size=n_patches, replace=replace)

    # Get spatial dimensions (skip non-spatial like 'c', 't')
    spatial_dims_lower = [d.lower() for d in ["x", "y", "z"]]
    spatial_indices = []
    for i, dim in enumerate(self.dseg.dims):
        if dim.lower() in spatial_dims_lower:
            spatial_indices.append(i)

    # Build voxel coordinates for sampled centers
    sampled_coords = []
    for spatial_idx in spatial_indices:
        sampled_coords.append(indices_computed[spatial_idx][sampled_indices])

    # Map to x, y, z order
    dim_to_coords = {}
    for i, spatial_idx in enumerate(spatial_indices):
        dim_name = self.dseg.dims[spatial_idx].lower()
        dim_to_coords[dim_name] = sampled_coords[i]

    # Get affine matrix
    affine_matrix = self.dseg.affine.matrix

    # Generate center coordinates in physical space
    centers = []
    for i in range(n_patches):
        # Get center voxel coordinates in (x, y, z) order
        center_voxel_xyz = np.array(
            [
                dim_to_coords["x"][i],
                dim_to_coords["y"][i],
                dim_to_coords["z"][i],
                1.0,
            ]
        )

        # Transform to physical coordinates
        center_physical = affine_matrix @ center_voxel_xyz
        center_xyz = center_physical[:3]

        # Convert to tuple
        center = tuple(center_xyz.tolist())
        centers.append(center)

    return centers
zarrnii.atlas.ZarrNiiAtlas.label_region_properties(region_properties, include_names=True, coord_column_names=None)

Map region properties to atlas labels using nearest neighbor interpolation.

This method takes region properties (typically from compute_region_properties or compute_centroids) and determines which atlas region each object falls into based on its centroid coordinates. It uses nearest neighbor interpolation to assign labels, making it robust to small coordinate mismatches.

This is a generalized version of the labeling functionality that preserves all region properties in the output, not just centroid coordinates.

Parameters:

  • region_properties (Union[Dict[str, ndarray], ndarray]) –

    Either: - Dict[str, np.ndarray]: Output from compute_region_properties() with keys like 'centroid_x', 'centroid_y', 'centroid_z', 'area', etc. Must contain coordinate columns specified by coord_column_names for labeling. - np.ndarray: Nx3 array of centroid coordinates in physical space (for backward compatibility with compute_centroids output). Each row is [x, y, z] in physical/world coordinates (mm).

  • include_names (bool, default: True ) –

    If True, includes region names from the labels dataframe in the output (default: True).

  • coord_column_names (Optional[List[str]], default: None ) –

    List of column names for x, y, z coordinates respectively. Defaults to ['centroid_x', 'centroid_y', 'centroid_z']. Can be customized, e.g., ['pos_x', 'pos_y', 'pos_z'].

Returns:

  • tuple[DataFrame, DataFrame]

    tuple of two pandas DataFrames: 1. properties DataFrame with columns: - All input properties (centroid_x, centroid_y, centroid_z, area, etc.) OR x, y, z if input was an Nx3 array - index: Integer label index from the atlas - name (optional): Region name if include_names=True 2. counts DataFrame with columns: - index: Integer label index from the atlas - name (optional): Region name if include_names=True - count: Number of objects in each region

Notes
  • Input coordinates must be in the same physical space as the atlas
  • Points outside the atlas bounds receive index=0 (background)
  • Uses scipy.interpolate.interpn with method='nearest' for label lookup
  • All properties from the input dictionary are preserved in the output

Examples:

>>> # Using compute_region_properties output (preferred)
>>> props = binary_seg.compute_region_properties(
...     output_properties=['centroid', 'area', 'eccentricity']
... )
>>> df_props, df_counts = atlas.label_region_properties(props)
>>> print(df_props.columns)  # centroid_x, centroid_y, centroid_z, area, ...
>>>
>>> # Using compute_centroids output (backward compatible)
>>> centroids = binary_seg.compute_centroids()
>>> df_props, df_counts = atlas.label_region_properties(centroids)
>>>
>>> # Using custom coordinate column names
>>> df_props, df_counts = atlas.label_region_properties(
...     props, coord_column_names=['pos_x', 'pos_y', 'pos_z']
... )
>>>
>>> # Filter to specific regions
>>> hippocampus_objects = df_props[df_props['name'] == 'Hippocampus']
Source code in zarrnii/atlas.py
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
def label_region_properties(
    self,
    region_properties: Union[Dict[str, np.ndarray], np.ndarray],
    include_names: bool = True,
    coord_column_names: Optional[List[str]] = None,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Map region properties to atlas labels using nearest neighbor interpolation.

    This method takes region properties (typically from compute_region_properties
    or compute_centroids) and determines which atlas region each object falls
    into based on its centroid coordinates. It uses nearest neighbor interpolation
    to assign labels, making it robust to small coordinate mismatches.

    This is a generalized version of the labeling functionality that preserves
    all region properties in the output, not just centroid coordinates.

    Args:
        region_properties: Either:
            - Dict[str, np.ndarray]: Output from compute_region_properties()
              with keys like 'centroid_x', 'centroid_y', 'centroid_z', 'area', etc.
              Must contain coordinate columns specified by coord_column_names for labeling.
            - np.ndarray: Nx3 array of centroid coordinates in physical space
              (for backward compatibility with compute_centroids output).
              Each row is [x, y, z] in physical/world coordinates (mm).
        include_names: If True, includes region names from the labels dataframe
            in the output (default: True).
        coord_column_names: List of column names for x, y, z coordinates respectively.
            Defaults to ['centroid_x', 'centroid_y', 'centroid_z'].
            Can be customized, e.g., ['pos_x', 'pos_y', 'pos_z'].

    Returns:
        tuple of two pandas DataFrames:
            1. properties DataFrame with columns:
                - All input properties (centroid_x, centroid_y, centroid_z, area, etc.)
                  OR x, y, z if input was an Nx3 array
                - index: Integer label index from the atlas
                - name (optional): Region name if include_names=True
            2. counts DataFrame with columns:
                - index: Integer label index from the atlas
                - name (optional): Region name if include_names=True
                - count: Number of objects in each region

    Notes:
        - Input coordinates must be in the same physical space as the atlas
        - Points outside the atlas bounds receive index=0 (background)
        - Uses scipy.interpolate.interpn with method='nearest' for label lookup
        - All properties from the input dictionary are preserved in the output

    Examples:
        >>> # Using compute_region_properties output (preferred)
        >>> props = binary_seg.compute_region_properties(
        ...     output_properties=['centroid', 'area', 'eccentricity']
        ... )
        >>> df_props, df_counts = atlas.label_region_properties(props)
        >>> print(df_props.columns)  # centroid_x, centroid_y, centroid_z, area, ...
        >>>
        >>> # Using compute_centroids output (backward compatible)
        >>> centroids = binary_seg.compute_centroids()
        >>> df_props, df_counts = atlas.label_region_properties(centroids)
        >>>
        >>> # Using custom coordinate column names
        >>> df_props, df_counts = atlas.label_region_properties(
        ...     props, coord_column_names=['pos_x', 'pos_y', 'pos_z']
        ... )
        >>>
        >>> # Filter to specific regions
        >>> hippocampus_objects = df_props[df_props['name'] == 'Hippocampus']
    """
    # Set default coordinate column names
    if coord_column_names is None:
        coord_column_names = ["centroid_x", "centroid_y", "centroid_z"]

    # Validate coord_column_names length
    if len(coord_column_names) != 3:
        raise ValueError(
            f"coord_column_names must contain exactly 3 column names for x, y, z. "
            f"Got {len(coord_column_names)} names: {coord_column_names}"
        )

    # Determine input type and extract coordinates
    if isinstance(region_properties, dict):
        # Input is from compute_region_properties
        # Check for required centroid keys
        required_keys = coord_column_names
        missing_keys = [k for k in required_keys if k not in region_properties]
        if missing_keys:
            raise ValueError(
                f"region_properties dict must contain {required_keys}. "
                f"Missing: {missing_keys}. "
                "Ensure coordinate columns are present in the input dictionary."
            )

        # Get number of points
        n_points = len(region_properties[coord_column_names[0]])

        # Handle empty input
        if n_points == 0:
            columns_props = list(region_properties.keys()) + ["index"]
            columns_counts = ["index"]
            if include_names:
                columns_props.append("name")
                columns_counts.append("name")
            columns_counts.append("count")
            return (
                pd.DataFrame(columns=columns_props),
                pd.DataFrame(columns=columns_counts),
            )

        # Extract centroid coordinates for labeling
        centroids = np.column_stack(
            [
                region_properties[coord_column_names[0]],
                region_properties[coord_column_names[1]],
                region_properties[coord_column_names[2]],
            ]
        )

        # Store all properties for later
        extra_properties = {
            k: v for k, v in region_properties.items() if k not in required_keys
        }
        use_dict_output = True
    elif isinstance(region_properties, np.ndarray):
        # Input is an Nx3 centroid array (backward compatibility)
        centroids = region_properties

        # Handle empty centroids array
        if centroids.shape[0] == 0:
            columns_props = ["x", "y", "z", "index"]
            columns_counts = ["index"]
            if include_names:
                columns_props.append("name")
                columns_counts.append("name")
            columns_counts.append("count")
            return (
                pd.DataFrame(columns=columns_props),
                pd.DataFrame(columns=columns_counts),
            )

        # Validate input shape
        if centroids.ndim != 2 or centroids.shape[1] != 3:
            raise ValueError(
                f"When passing an array, it must be Nx3, got shape {centroids.shape}"
            )

        n_points = centroids.shape[0]
        extra_properties = {}
        use_dict_output = False
    else:
        raise TypeError(
            f"region_properties must be a dict or numpy array, "
            f"got {type(region_properties)}"
        )

    # Get atlas data and affine
    dseg_data = self.dseg.data
    if hasattr(dseg_data, "compute"):
        dseg_data = dseg_data.compute()

    affine_matrix = self.dseg.affine.matrix

    # Convert physical coordinates to voxel coordinates
    # centroids are in (x, y, z) order
    # Create homogeneous coordinates
    centroids_homogeneous = np.column_stack(
        [centroids, np.ones((n_points, 1), dtype=np.float64)]
    )

    # Apply inverse affine transform
    affine_inv = np.linalg.inv(affine_matrix)
    voxel_coords_homogeneous = centroids_homogeneous @ affine_inv.T
    voxel_coords = voxel_coords_homogeneous[:, :3]

    # Create grid for interpn
    # Grid should be in the order of the data array dimensions
    # For ZarrNii, this is typically (z, y, x), (c, z, y, x), or (t, c, z, y, x)
    # Remove time and/or channel dimensions if present
    if dseg_data.ndim == 5:
        # Validate that time and channel dimensions are singleton
        time_dim = dseg_data.shape[0]
        channel_dim = dseg_data.shape[1]
        if time_dim != 1 or channel_dim != 1:
            raise ValueError(
                f"5D atlas data must have singleton time and channel dimensions, "
                f"but got shape {dseg_data.shape} (t={time_dim}, c={channel_dim}). "
                "Please select a single timepoint and channel before calling "
                "label_region_properties."
            )
        # Remove singleton time and channel dimensions (t, c, z, y, x) -> (z, y, x)
        dseg_data = dseg_data[0, 0]
    elif dseg_data.ndim == 4:
        # Validate that channel dimension is singleton
        channel_dim = dseg_data.shape[0]
        if channel_dim != 1:
            raise ValueError(
                f"4D atlas data must have singleton channel dimension, "
                f"but got shape {dseg_data.shape} (c={channel_dim}). "
                "Please select a single channel before calling label_region_properties."
            )
        dseg_data = dseg_data[0]  # Remove channel dimension

    # Create coordinate grids for each dimension
    # interpn expects a tuple of 1D arrays representing the grid coordinates
    shape = dseg_data.shape
    grid = tuple(np.arange(s) for s in shape)

    # The inverse affine transform already converted physical (x, y, z) coordinates
    # to voxel coordinates in the order matching the data array axes_order.
    # So voxel_coords is already in the correct order for interpn!

    # Use interpn to get labels at the centroid locations
    label_at_points = interpn(
        grid,
        dseg_data,
        voxel_coords,
        method="nearest",
        bounds_error=False,
        fill_value=0,
    )

    # Convert to integer labels
    label_at_points = label_at_points.astype(int)

    # Create DataFrame with appropriate columns
    if use_dict_output:
        # Include all properties from the input dict
        df_data = {
            coord_column_names[0]: region_properties[coord_column_names[0]],
            coord_column_names[1]: region_properties[coord_column_names[1]],
            coord_column_names[2]: region_properties[coord_column_names[2]],
        }
        # Add extra properties (like area, eccentricity, etc.)
        df_data.update(extra_properties)
    else:
        # Use x, y, z for backward compatibility with centroid arrays
        df_data = {
            "x": centroids[:, 0],
            "y": centroids[:, 1],
            "z": centroids[:, 2],
        }

    # Add atlas index
    df_data["index"] = label_at_points

    # Add region names if requested
    if include_names and self.labels_df is not None:
        # Create a lookup from index to name
        label_to_name = dict(
            zip(
                self.labels_df[self.label_column],
                self.labels_df[self.name_column],
            )
        )
        # Map labels to names, use 'Unknown' for labels not in lookup table
        df_data["name"] = [
            label_to_name.get(label, f"Unknown_Label_{label}")
            for label in label_at_points
        ]

    df_props = pd.DataFrame(df_data)

    # Create counts DataFrame - group by index and optionally name
    if include_names and self.labels_df is not None:
        df_counts = (
            df_props.groupby(["index", "name"]).size().reset_index(name="count")
        )
    else:
        df_counts = df_props.groupby(["index"]).size().reset_index(name="count")

    return (df_props, df_counts)
zarrnii.atlas.ZarrNiiAtlas.label_centroids(centroids, include_names=True)

Map centroids to atlas labels using nearest neighbor interpolation.

.. deprecated:: Use :meth:label_region_properties instead. This method is provided for backward compatibility and will be removed in a future version.

This method takes a set of centroids (typically from compute_centroids) and determines which atlas region each centroid falls into. It uses nearest neighbor interpolation to assign labels, making it robust to small coordinate mismatches.

Parameters:

  • centroids (ndarray) –

    Nx3 numpy array of centroid coordinates in physical space (typically output from compute_centroids). Each row is [x, y, z] in physical/world coordinates (mm). Can also be an empty array (0, 3).

  • include_names (bool, default: True ) –

    If True, includes region names from the labels dataframe in the output (default: True).

Returns:

  • tuple[DataFrame, DataFrame]

    tuple of two pandas DataFrames: 1. centroids DataFrame with columns: - x, y, z: Physical coordinates (in mm) of each centroid - index: Integer label index from the atlas - name (optional): Region name if include_names=True 2. counts DataFrame with columns: - index: Integer label index from the atlas - name (optional): Region name if include_names=True - count: Number of centroids in each region

Notes
  • Input centroids must be in the same physical space as the atlas
  • Points outside the atlas bounds receive index=0 (background)
  • Uses scipy.interpolate.interpn with method='nearest' for label lookup

Examples:

>>> # Compute centroids from a segmentation
>>> centroids = binary_seg.compute_centroids()
>>>
>>> # Map centroids to atlas labels
>>> df_centroids, df_counts = atlas.label_centroids(centroids)
>>> print(df_centroids)
>>> print(df_counts)
>>>
>>> # Filter to specific regions
>>> hippocampus_points = df_centroids[
...     df_centroids['name'] == 'Hippocampus'
... ]
Source code in zarrnii/atlas.py
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
def label_centroids(
    self,
    centroids: np.ndarray,
    include_names: bool = True,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Map centroids to atlas labels using nearest neighbor interpolation.

    .. deprecated::
        Use :meth:`label_region_properties` instead. This method is provided
        for backward compatibility and will be removed in a future version.

    This method takes a set of centroids (typically from compute_centroids)
    and determines which atlas region each centroid falls into. It uses
    nearest neighbor interpolation to assign labels, making it robust to
    small coordinate mismatches.

    Args:
        centroids: Nx3 numpy array of centroid coordinates in physical space
            (typically output from compute_centroids). Each row is [x, y, z]
            in physical/world coordinates (mm). Can also be an empty array (0, 3).
        include_names: If True, includes region names from the labels dataframe
            in the output (default: True).

    Returns:
        tuple of two pandas DataFrames:
            1. centroids DataFrame with columns:
                - x, y, z: Physical coordinates (in mm) of each centroid
                - index: Integer label index from the atlas
                - name (optional): Region name if include_names=True
            2. counts DataFrame with columns:
                - index: Integer label index from the atlas
                - name (optional): Region name if include_names=True
                - count: Number of centroids in each region

    Notes:
        - Input centroids must be in the same physical space as the atlas
        - Points outside the atlas bounds receive index=0 (background)
        - Uses scipy.interpolate.interpn with method='nearest' for label lookup

    Examples:
        >>> # Compute centroids from a segmentation
        >>> centroids = binary_seg.compute_centroids()
        >>>
        >>> # Map centroids to atlas labels
        >>> df_centroids, df_counts = atlas.label_centroids(centroids)
        >>> print(df_centroids)
        >>> print(df_counts)
        >>>
        >>> # Filter to specific regions
        >>> hippocampus_points = df_centroids[
        ...     df_centroids['name'] == 'Hippocampus'
        ... ]
    """
    warnings.warn(
        "label_centroids is deprecated, use label_region_properties instead",
        DeprecationWarning,
        stacklevel=2,
    )
    return self.label_region_properties(centroids, include_names=include_names)

Functions

zarrnii.atlas.get(template, **kwargs)

Thin wrapper on templateflow.api.get() - preserves original signature.

Parameters:

  • template (str) –

    Template name (e.g., "MNI152NLin2009cAsym")

  • **kwargs

    Additional TemplateFlow parameters (suffix, resolution, etc.)

Returns:

  • Union[str, List[str]]

    String path or list of string paths as returned by TemplateFlow

Raises:

  • ImportError

    If TemplateFlow is not available

Source code in zarrnii/atlas.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def get(template: str, **kwargs) -> Union[str, List[str]]:
    """Thin wrapper on templateflow.api.get() - preserves original signature.

    Args:
        template: Template name (e.g., "MNI152NLin2009cAsym")
        **kwargs: Additional TemplateFlow parameters (suffix, resolution, etc.)

    Returns:
        String path or list of string paths as returned by TemplateFlow

    Raises:
        ImportError: If TemplateFlow is not available
    """
    if not TEMPLATEFLOW_AVAILABLE:
        raise ImportError(
            "TemplateFlow is required. Install with: pip install zarrnii[templateflow]"
        )

    return tflow.get(template, **kwargs)

zarrnii.atlas.get_template(template, suffix='SPIM', **kwargs)

Get Template object from TemplateFlow with single file validation.

Parameters:

  • template (str) –

    Template name (e.g., "MNI152NLin2009cAsym")

  • suffix (str, default: 'SPIM' ) –

    File suffix (e.g., "T1w", "SPIM")

  • **kwargs

    Additional TemplateFlow parameters (resolution, cohort, etc.)

Returns:

  • Template

    Template object with anatomical image

Raises:

  • AmbiguousTemplateFlowQueryError

    If query returns multiple files

  • FileNotFoundError

    If no matching files found

  • ImportError

    If TemplateFlow is not available

Source code in zarrnii/atlas.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def get_template(template: str, suffix: str = "SPIM", **kwargs) -> "Template":
    """Get Template object from TemplateFlow with single file validation.

    Args:
        template: Template name (e.g., "MNI152NLin2009cAsym")
        suffix: File suffix (e.g., "T1w", "SPIM")
        **kwargs: Additional TemplateFlow parameters (resolution, cohort, etc.)

    Returns:
        Template object with anatomical image

    Raises:
        AmbiguousTemplateFlowQueryError: If query returns multiple files
        FileNotFoundError: If no matching files found
        ImportError: If TemplateFlow is not available
    """
    if not TEMPLATEFLOW_AVAILABLE:
        raise ImportError(
            "TemplateFlow is required. Install with: pip install zarrnii[templateflow]"
        )

    result = tflow.get(template, suffix=suffix, **kwargs)

    # Handle TemplateFlow's variable return behavior
    if isinstance(result, list):
        if len(result) == 0:
            raise FileNotFoundError(
                f"No files found for template='{template}' suffix='{suffix}'"
            )
        elif len(result) > 1:
            raise AmbiguousTemplateFlowQueryError(template, suffix, result, **kwargs)
        else:
            result = result[0]  # Single item list

    # Load anatomical image - determine format from file extension
    result_path = Path(str(result))
    if result_path.suffix.lower() in [".nii", ".gz"]:
        anatomical_image = ZarrNii.from_nifti(str(result))
    elif result_path.suffix.lower() == ".zarr" or "ome.zarr" in str(result_path):
        anatomical_image = ZarrNii.from_ome_zarr(str(result))
    else:
        # Default to NIfTI for unknown extensions
        anatomical_image = ZarrNii.from_nifti(str(result))

    return Template(
        name=template,
        description=f"TemplateFlow template: {template}",
        anatomical_image=anatomical_image,
        resolution=str(kwargs.get("resolution", "Unknown")),
        dimensions=anatomical_image.shape,
        metadata=kwargs,
    )

zarrnii.atlas.get_atlas(template, atlas, **kwargs)

Load atlas directly from TemplateFlow by template and atlas name.

Parameters:

  • template (str) –

    Template name (e.g., 'MNI152NLin2009cAsym')

  • atlas (str) –

    Atlas name (e.g., 'DKT', 'Harvard-Oxford')

  • **kwargs

    Additional TemplateFlow query parameters

Returns:

Raises:

  • ImportError

    If templateflow is not available

  • FileNotFoundError

    If atlas files not found

Source code in zarrnii/atlas.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def get_atlas(template: str, atlas: str, **kwargs) -> "ZarrNiiAtlas":
    """Load atlas directly from TemplateFlow by template and atlas name.

    Args:
        template: Template name (e.g., 'MNI152NLin2009cAsym')
        atlas: Atlas name (e.g., 'DKT', 'Harvard-Oxford')
        **kwargs: Additional TemplateFlow query parameters

    Returns:
        Atlas object loaded from TemplateFlow

    Raises:
        ImportError: If templateflow is not available
        FileNotFoundError: If atlas files not found
    """
    if not TEMPLATEFLOW_AVAILABLE:
        raise ImportError(
            "TemplateFlow is required. Install with: pip install zarrnii[templateflow]"
        )

    # Get dseg file
    dseg_result = tflow.get(template, suffix="dseg", atlas=atlas, **kwargs)
    if isinstance(dseg_result, list):
        if len(dseg_result) == 0:
            raise FileNotFoundError(
                f"No dseg files found for template '{template}' atlas '{atlas}'"
            )
        dseg_file = dseg_result[0]  # Take first match
    else:
        dseg_file = dseg_result

    # Get corresponding TSV file
    tsv_result = tflow.get(
        template, suffix="dseg", atlas=atlas, extension=".tsv", **kwargs
    )
    if isinstance(tsv_result, list):
        if len(tsv_result) == 0:
            raise FileNotFoundError(
                f"No TSV files found for template '{template}' atlas '{atlas}'"
            )
        tsv_file = tsv_result[0]  # Take first match
    else:
        tsv_file = tsv_result

    return ZarrNiiAtlas.from_files(dseg_file, tsv_file)

zarrnii.atlas.save_atlas_to_templateflow(atlas, template_name, atlas_name)

Save atlas to TemplateFlow directory as BIDS-compliant files.

Parameters:

  • atlas (ZarrNiiAtlas) –

    Atlas object to save

  • template_name (str) –

    Template name (e.g., 'MyTemplate')

  • atlas_name (str) –

    Atlas name (e.g., 'MyAtlas')

Returns:

  • str

    Path to created template directory

Raises:

  • ImportError

    If templateflow is not available

Source code in zarrnii/atlas.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def save_atlas_to_templateflow(
    atlas: "ZarrNiiAtlas", template_name: str, atlas_name: str
) -> str:
    """Save atlas to TemplateFlow directory as BIDS-compliant files.

    Args:
        atlas: Atlas object to save
        template_name: Template name (e.g., 'MyTemplate')
        atlas_name: Atlas name (e.g., 'MyAtlas')

    Returns:
        Path to created template directory

    Raises:
        ImportError: If templateflow is not available
    """
    if not TEMPLATEFLOW_AVAILABLE:
        raise ImportError(
            "TemplateFlow is required. Install with: pip install zarrnii[templateflow]"
        )

    template_dir = Path(TF_HOME) / f"tpl-{template_name}"
    template_dir.mkdir(parents=True, exist_ok=True)

    # Save dseg.nii.gz file
    dseg_file = template_dir / f"tpl-{template_name}_atlas-{atlas_name}_dseg.nii.gz"
    atlas.image.to_nifti(str(dseg_file))

    # Save dseg.tsv file
    tsv_file = template_dir / f"tpl-{template_name}_atlas-{atlas_name}_dseg.tsv"
    atlas.lookup_table.to_csv(str(tsv_file), sep="\t", index=False)

    return str(template_dir)