NumPy Utilities¶
Low-level array helpers used throughout TPTBox for label extraction, morphological operations, connected components, centre-of-mass computation, and more.
TPTBox.core.np_utils
¶
np_isin
¶
Fast np.isin for non-negative integer label arrays via a boolean lookup table.
For unsigned-integer segmentation masks this is ~3-6x faster than np.isin when testing
membership in more than one label, because it replaces the general algorithm with a single
lut[arr] gather. Falls back to np.isin for non-unsigned dtypes, negative labels, or
very large label ranges; uses arr == label for the single-label case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input array. |
required |
labels
|
A label or iterable of labels to test membership against. |
required | |
invert
|
bool
|
If True, return the complement (equivalent to
|
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Boolean mask, same shape as |
Source code in TPTBox/core/np_utils.py
np_extract_label
¶
np_extract_label(arr: ndarray, label: int | list[int], to_label: int = 1, inplace: bool = True) -> np.ndarray
Extracts a label from an given arr (works with zero as well!).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
input arr |
required |
label
|
int
|
label to be extracted (all other values are set to zero, label will be set to one, even if label==0!) |
required |
to_label
|
int
|
the value of the entries that had the |
1
|
inplace
|
bool
|
If False, will make a copy of the arr. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Binary array where the selected label is set to |
Source code in TPTBox/core/np_utils.py
cc3dstatistics
¶
Computes connected component statistics for a labeled array using connected components 3D (cc3d).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
A 3D array of unsigned integers or booleans where each connected component is labeled with a unique integer. Typically output from a labeling function. |
required |
use_crop
|
bool
|
If True, the function attempts to crop the input array around non-zero regions to improve performance and focus statistics on the area of interest. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A dictionary containing statistics of the connected components, such as their sizes,
bounding boxes, and possibly centroids, depending on implementation of |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input array is not of an unsigned integer or boolean dtype. |
Source code in TPTBox/core/np_utils.py
np_volume
¶
Returns a dictionary mapping each label in the array to its voxel count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input unsigned-integer label array. |
required |
include_zero
|
bool
|
If True, also counts voxels with label 0 (background). Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[int, int]
|
dict[int, int]: Mapping from label value to number of voxels with that label. |
Source code in TPTBox/core/np_utils.py
np_is_empty
¶
Returns true if the array is empty (only zeros).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
input uint array |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if array is empty |
ON UINT and INT:¶
is faster than np_count_nonzero(arr) > 0¶
is faster than arr.nonzero()[0].size == 0¶
is faster than arr.sum() > 0¶
Source code in TPTBox/core/np_utils.py
np_count_nonzero
¶
Returns number of nonzero entries in the array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input array. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of elements in |
Source code in TPTBox/core/np_utils.py
old_np_unique
¶
Returns each existing label in the array (including zero!).
Uses cc3d statistics for unsigned-integer arrays for speed, and falls back
to numpy.unique for other dtypes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input label array. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: Sorted list of every distinct label value present in |
Source code in TPTBox/core/np_utils.py
np_unique
¶
Returns each existing label in the array (including zero!).
Uses cc3d statistics for unsigned-integer arrays for speed, and falls back
to numpy.unique for other dtypes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input label array. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: Sorted list of every distinct label value present in |
Source code in TPTBox/core/np_utils.py
np_unique_withoutzero
¶
Returns each existing non-zero label in the array (excluding background zero).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input unsigned-integer label array. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: Sorted list of every distinct label value present in |
Source code in TPTBox/core/np_utils.py
old_np_unique_withoutzero
¶
Returns each existing non-zero label in the array (excluding background zero).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input unsigned-integer label array. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: Sorted list of every distinct label value present in |
Source code in TPTBox/core/np_utils.py
np_center_of_mass
¶
Calculates center of mass for each non-zero label in the array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input unsigned-integer label array. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, COORDINATE]
|
dict[int, COORDINATE]: Mapping from each non-zero label to its (x, y, z) center-of-mass coordinate as floats. |
Source code in TPTBox/core/np_utils.py
np_bounding_boxes
¶
Calculates tight axis-aligned bounding boxes for each non-zero label in the array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input unsigned-integer label array. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, tuple[slice, slice, slice]]
|
dict[int, tuple[slice, slice, slice]]: Mapping from each non-zero label to a 3-tuple of slices representing the bounding box of that label in each spatial dimension. |
Source code in TPTBox/core/np_utils.py
np_contacts
¶
Calculates the contacting labels and the amount of touching voxels based on connectivity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input 2D or 3D label array. |
required |
connectivity
|
int
|
Connectivity level in range [1, 3]. 1 = face-only, 2 = face+edge, 3 = face+edge+corner adjacency. |
required |
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], int]
|
dict[tuple[int, int], int]: Mapping from a pair of touching labels to the number of voxels where they touch. |
Source code in TPTBox/core/np_utils.py
np_region_graph
¶
Returns the unique pairs of different labels that are adjacent in the array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input 2D or 3D label array. |
required |
connectivity
|
int
|
Connectivity level in range [1, 3]. 1 = face-only, 2 = face+edge, 3 = face+edge+corner adjacency. |
required |
Returns:
| Type | Description |
|---|---|
set[tuple[int, int]]
|
set[tuple[int, int]]: Set of (label_a, label_b) pairs where each pair indicates two labels that share at least one adjacent voxel. |
Source code in TPTBox/core/np_utils.py
np_voxel_connectivity_graph
¶
Returns a voxel connectivity graph of the input array.
For 2D connectivity, the output is an 8-bit unsigned integer.
edges (4,8 way)
5-8: corners (8 way only, zeroed in 4 way)
8 7 6 5 4 3 2 1
-x-y x-y -xy xy -x +y -x +x
For a 3D 26 and 18 connectivity, the output requires 32-bit unsigned integers, for 6-way the output are 8-bit unsigned integers.
faces (6,18,26 way)
7-19: edges (18,26 way) 18-26: corners (26 way) 26-32: unused (zeroed)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input 2D or 3D label array. |
required |
connectivity
|
int
|
Connectivity level in range [1, 3]. 1 = face-only, 2 = face+edge, 3 = face+edge+corner adjacency. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: uint8 or uint32 array the same shape as the input, where each value encodes which neighbors share the same label as that voxel. |
Source code in TPTBox/core/np_utils.py
np_dice
¶
Calculates the dice similarity between two numpy arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seg
|
ndarray
|
segmentation array |
required |
gt
|
ndarray
|
other segmentation array |
required |
binary_compare
|
bool
|
if the should be binarized before (0/1) |
False
|
label
|
int
|
if not binary_compare, use this label for dice score |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
dice value |
Source code in TPTBox/core/np_utils.py
np_erode_msk_euclid
¶
np_erode_msk_euclid(arr: ndarray, n_pixel: int = 3, use_crop=True, labels=None, mask=None) -> np.ndarray
Euclidean erosion: shrink each foreground label by n_pixel voxels via distance transform.
Removes voxels whose Euclidean distance to background is ≤ n_pixel.
Source code in TPTBox/core/np_utils.py
np_dilate_msk_euclid
¶
np_dilate_msk_euclid(arr: ndarray, n_pixel: int = 3, use_crop=True, labels=None, mask=None) -> np.ndarray
Euclidean dilation: expand each foreground label by n_pixel voxels via distance transform.
Assigns each newly covered voxel to the nearest existing label.
Source code in TPTBox/core/np_utils.py
np_dilate_msk
¶
np_dilate_msk(arr: ndarray, label_ref: LABEL_REFERENCE = None, n_pixel: int = 5, connectivity: int = 3, use_crop: bool = True, mask: ndarray | None = None, ignore_axis: int | None = None) -> np.ndarray
Dilates the given array by the specified number of voxels (not including the zero label).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input label array. |
required |
label_ref
|
LABEL_REFERENCE
|
Label or list of labels to dilate. If None, all non-zero labels are dilated. Defaults to None. |
None
|
n_pixel
|
int
|
Number of voxels to dilate by. Defaults to 5. |
5
|
connectivity
|
int
|
Elements up to a squared distance of
|
3
|
use_crop
|
bool
|
If True, crops to a bounding box before dilating for speed. Defaults to True. |
True
|
mask
|
ndarray | None
|
If set, after each iteration all voxels outside this mask are zeroed out. Defaults to None. |
None
|
ignore_axis
|
int | None
|
If set, dilation is performed in 2D along all slices of this axis (e.g., 0 for slice-wise axial dilation). Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The dilated label array. |
Source code in TPTBox/core/np_utils.py
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | |
np_erode_msk
¶
np_erode_msk(arr: ndarray, label_ref: LABEL_REFERENCE = None, n_pixel: int = 5, use_crop: bool = True, connectivity: int = 3, border_value=0, ignore_axis: int | None = None) -> np.ndarray
Erodes the given array by the specified number of voxels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input label array. |
required |
label_ref
|
LABEL_REFERENCE
|
Label or list of labels to erode. If None, all non-zero labels are eroded. Defaults to None. |
None
|
n_pixel
|
int
|
Number of voxels to erode by. Defaults to 5. |
5
|
use_crop
|
bool
|
If True, crops to a bounding box before eroding for speed. Defaults to True. |
True
|
connectivity
|
int
|
Elements up to a squared distance of
|
3
|
border_value
|
int
|
Value to pad the border with during erosion. Defaults to 0. |
0
|
ignore_axis
|
int | None
|
If set, erosion is performed in 2D along all slices of this axis. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The eroded label array. |
Source code in TPTBox/core/np_utils.py
np_map_labels
¶
Maps labels in the given array according to a label-map dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input unsigned-integer label array to remap. |
required |
label_map
|
LABEL_MAP
|
Dictionary mapping original label values (int or str) to new label values (int or str). Labels not present in the map are left unchanged. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A new array with labels remapped according to |
Source code in TPTBox/core/np_utils.py
np_calc_crop_around_centerpoint
¶
np_calc_crop_around_centerpoint(poi: tuple[int, ...] | tuple[float, ...], arr: ndarray, cutout_size: tuple[int, ...], pad_to_size: Sequence[int] | ndarray | int = 0) -> tuple[np.ndarray, tuple[slice, slice, slice], tuple]
Crops a fixed-size region centred on a given point, optionally padding near-edge regions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poi
|
tuple[int, ...] | tuple[float, ...]
|
Center point of the cutout, one coordinate per dimension. |
required |
arr
|
ndarray
|
Input array to crop. |
required |
cutout_size
|
tuple[int, ...]
|
Desired size of the cutout in each dimension. |
required |
pad_to_size
|
Sequence[int] | ndarray | int
|
Additional symmetric padding to add around the cutout. Can be a single int (same for all dims) or a per-dim sequence. Defaults to 0. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[ndarray, tuple[slice, slice, slice], tuple]
|
A 3-element tuple containing:
- np.ndarray: The cropped (and padded) sub-array.
- tuple[slice, ...]: Slices used to extract the cutout from |
Source code in TPTBox/core/np_utils.py
np_bbox_binary
¶
np_bbox_binary(img: ndarray, px_dist: int | Sequence[int] | ndarray = 0, raise_error=True) -> tuple[slice, ...]
Calculates a bounding box in n dimensions given a image (factor ~2 times faster than compute_crop).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
ndarray
|
input array |
required |
px_dist
|
int | Sequence[int] | ndarray
|
int | tuple[int]: dist (int): The amount of padding to be added to the cropped image. If int, will apply the same padding to each dim. Default value is 0. |
0
|
Returns:
| Type | Description |
|---|---|
tuple[slice, ...]
|
list of boundary coordinates as slices tuple |
Source code in TPTBox/core/np_utils.py
np_center_of_bbox_binary
¶
Calculates the center coordinates of the bounding box around non-zero regions in a binary image.
This function determines the bounding box of non-zero regions in a binary image, optionally expanding it by a specified pixel distance. It then computes and returns the center coordinates of each dimension of the bounding box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
ndarray
|
A binary image represented as a NumPy array, where non-zero values indicate points of interest. |
required |
px_dist
|
int | Sequence[int] | ndarray
|
The pixel distance by which to expand the bounding box in each dimension. Can be a single integer or a sequence of integers corresponding to each dimension. Default is 0, meaning no expansion. |
0
|
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: A list of center coordinates for each dimension of the bounding box. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input image is empty or not a valid binary array. |
Source code in TPTBox/core/np_utils.py
np_find_index_of_k_max_values
¶
Calculates the indices of the k-highest values in the given arr.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
input array |
required |
k
|
int
|
number of higest values to calculate the index for |
2
|
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: list of indices sorted. First entry corresponds to the index of the highest value in arr, ... |
Source code in TPTBox/core/np_utils.py
np_compute_surface
¶
np_compute_surface(arr: UINTARRAY, connectivity: int = 3, dilated_surface: bool = False) -> UINTARRAY
Computes the surface of a binary array based on connectivity and dilation options.
This function identifies the surface voxels of a binary array. If dilated_surface
is True, it computes a dilated surface by expanding the array and subtracting the
original. Otherwise, it computes a contracted surface by eroding the array and
subtracting the result from the original.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
A binary array representing the segmentation or mask. |
required |
connectivity
|
int
|
The connectivity used to define neighbors for surface computation, where 1 represents face-connectivity, and 3 represents full connectivity. Default is 3. |
3
|
dilated_surface
|
bool
|
Whether to compute a dilated surface. If True, expands the surface; if False, contracts the surface. Default is False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
UINTARRAY |
UINTARRAY
|
An array representing the computed surface voxels. |
Source code in TPTBox/core/np_utils.py
np_point_coordinates
¶
Extracts the coordinates of non-zero points from a 3D binary array.
This function locates all non-zero voxels within a 3D binary array and returns their coordinates as a list of tuples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
A 3-dimensional binary array representing the segmentation or mask. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int, int]]
|
list[tuple[int, int, int]]: A list of (X, Y, Z) coordinate tuples for each non-zero |
list[tuple[int, int, int]]
|
point in the array. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the input array does not have three dimensions. |
Source code in TPTBox/core/np_utils.py
np_connected_components
¶
np_connected_components(arr: UINTARRAY, label_ref: LABEL_REFERENCE | None = None, connectivity: int = 3, include_zero: bool = False) -> tuple[UINTARRAY, int]
Calculates the connected components of a given array (works with zeros as well!).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
input arr |
required |
connectivity
|
int
|
in range [1,3]. For 2D images, 2 and 3 is the same. |
3
|
include_zero
|
bool
|
If true, will treat the background (0) as another label to calculate connected components from. Significantly slower! Defaults to False. |
False
|
verbose
|
If true, will print out if the array does not have any CC |
required |
Returns:
| Name | Type | Description |
|---|---|---|
arr_cc |
tuple[UINTARRAY, int]
|
UINTARRAY, N: number of cc |
Source code in TPTBox/core/np_utils.py
np_connected_components_per_label
¶
np_connected_components_per_label(arr: UINTARRAY, connectivity: int = 3, label_ref: LABEL_REFERENCE = None, include_zero: bool = False) -> dict[int, UINTARRAY]
Calculates the connected components for each label in label_ref.
Returns a dictionary mapping each label to its connected-component mask.
Supports zero labels when include_zero=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
input arr |
required |
connectivity
|
int
|
in range [1,3]. For 2D images, 2 and 3 is the same. |
3
|
labels
|
int | list[int] | None
|
Labels that the connected components algorithm should be applied to. If none, applies on all labels found in arr. Defaults to None. |
required |
include_zero
|
bool
|
If true, will treat the background (0) as another label to calculate connected components from. Significantly slower! Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
subreg_cc |
dict[int, UINTARRAY]
|
dict[label, cc_idx, arr], subreg_cc_N: dict[label, n_connected_components] |
Source code in TPTBox/core/np_utils.py
np_filter_connected_components
¶
np_filter_connected_components(arr: UINTARRAY, largest_k_components: int | None = None, label_ref: LABEL_REFERENCE = None, connectivity: int = 3, return_original_labels: bool = True, min_volume: float = 0, max_volume: float | None = None, removed_to_label=0, k_larges_global=False) -> UINTARRAY
Finds the largest k connected components in a given array (does NOT work with zero as label!).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
input array |
required |
k
|
int | None
|
finds the k-largest components. If k is None, will find all connected components and still sort them by size |
required |
labels
|
int | list[int] | None
|
Labels that the algorithm should be applied to. If none, applies on all labels found in arr. Defaults to None. |
required |
connectivity
|
int
|
in range [1,3]. For 2D images, 2 and 3 is the same. |
3
|
return_original_labels
|
bool
|
If set to False, will label the components from 1 to k. Defaults to True |
True
|
k_larges_global
|
bool
|
If true largest_k_components is filterd over all labels instead of each lable individualy |
False
|
Returns: np.ndarray: array with the largest k connected components
Source code in TPTBox/core/np_utils.py
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 | |
np_get_connected_components_center_of_mass
¶
np_get_connected_components_center_of_mass(arr: UINTARRAY, label: int, connectivity: int = 3, sort_by_axis: int | None = None) -> list[COORDINATE]
Calculates the center of mass of each connected component of a given label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input label array. |
required |
label
|
int
|
The label whose connected components are analysed. |
required |
connectivity
|
int
|
Connectivity for connected components in range [1, 3]. Defaults to 3. |
3
|
sort_by_axis
|
int | None
|
If not None, the returned list is sorted in ascending order of the coordinate along this axis. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
list[COORDINATE]
|
list[COORDINATE]: List of (x, y, z) center-of-mass coordinates, one per
connected component of |
Source code in TPTBox/core/np_utils.py
np_translate_to_center_of_array
¶
Moves the nonzero values of an array so its center of mass is in the center of the array shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ndarray
|
input array |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: array of the same shape translated to the center |
Source code in TPTBox/core/np_utils.py
np_translate_arr
¶
np_translate_arr(arr: ndarray, translation_vector: tuple[int, int] | tuple[int, int, int]) -> np.ndarray
Translates values of an input array according to a 2D or 3D translation vector. Values that would be shifted beyond the boundary are removed!
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
input array |
required |
translation_vector
|
tuple[int, int] | tuple[int, int, int]
|
vector to translated the array with (2D or 3D) |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: the translated array |
Examples:
>>> a = np.array([[0, 1, 0], [0, 2, 1], [1, 0, 0]])
>>> b = np_translate_arr(a, translation_vector=(1, 0))
>>> print(b)
>>> [[0 0 0],[0 1 0],[0 2 1]]
Source code in TPTBox/core/np_utils.py
np_fill_holes
¶
np_fill_holes(arr: ndarray, label_ref: LABEL_REFERENCE = None, slice_wise_dim: int | None = None, use_crop: bool = True, pbar: bool = False) -> np.ndarray
Fills holes in segmentations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input segmentation array |
required |
labels
|
int | list[int] | None
|
Labels that the hole-filling should be applied to. If none, applies on all labels found in arr. Defaults to None. |
required |
slice_wise_dim
|
int | None
|
If the input is 3D, the specified dimension here cna be used for 2D slice-wise filling. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The array with holes filled |
Source code in TPTBox/core/np_utils.py
np_smooth_gaussian_labelwise
¶
np_smooth_gaussian_labelwise(arr: UINTARRAY, label_to_smooth: list[int] | int, label_weights: dict[int, float] | None = None, sigma: float = 3.0, radius: int = 6, truncate: int = 4, boundary_mode: str = 'nearest', dilate_prior: int = 0, dilate_connectivity: int = 3, dilate_channelwise: bool = False, smooth_background: bool = True, background_threshold: float | None = None) -> UINTARRAY
Smooth selected labels in a segmentation mask using Gaussian filtering, leaving other labels unaffected.
Internal Description
- Ensures label(s) to be smoothed are present in the segmentation.
- Optionally dilates specified labels prior to smoothing (if
dilate_prior > 0). - Iterates over each label:
- Creates a binary mask for that label.
- Applies Gaussian smoothing only if the label is in
label_to_smooth. - Optionally applies a weight from
label_weights.
- Adds background as a separate smoothed or fixed mask depending on
smooth_background. - Stacks all label probability-like maps and computes a new segmentation by taking the
argmaxover the stacked array, i.e., the label with the highest value wins per voxel. - Replaces the indices in the argmax map with the original label values to preserve semantics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
Input Segmentation Mask Array |
required |
label_to_smooth
|
list[int] | int
|
Which labels to smooth in the mask. Every other label will be untouched |
required |
sigma
|
float
|
Sigma of the gaussian blur. Defaults to 3.0. |
3.0
|
radius
|
int
|
Radius of the gaussian blur. Defaults to 6. |
6
|
truncate
|
int
|
Truncate of the gaussian blur. Defaults to 4. |
4
|
boundary_mode
|
str
|
Boundary Mode of the gaussian blur. Defaults to "nearest". |
'nearest'
|
dilate_prior
|
int
|
Dilate this many voxels before starting the gaussian blur algorithm. Defaults to 0. |
0
|
dilate_connectivity
|
int
|
Connectivity of the dilation process, if applied. Defaults to 3. |
3
|
smooth_background
|
bool
|
If true, will also smooth the background. If False, the background voxels stay the same and the segmentation cannot add voxels. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
UINTARRAY |
UINTARRAY
|
The resulting smoothed array of the segmentation (with the same labels as the input) |
Source code in TPTBox/core/np_utils.py
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 1227 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 | |
np_calc_convex_hull
¶
Calculates the convex hull of a given array and returns a filled binary mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
INTARRAY
|
Input integer array (non-zero voxels define the point set). |
required |
axis
|
int | None
|
If given, computes the convex hull slice-by-slice along this axis (remaining dimensions must be at least 2D). If None, computes the hull over the full 2D or 3D volume. Defaults to None. |
None
|
verbose
|
bool
|
If True, prints warnings for degenerate cases. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
INTARRAY |
INTARRAY
|
Binary array of the same shape as |
Source code in TPTBox/core/np_utils.py
np_calc_boundary_mask
¶
np_calc_boundary_mask(img: ndarray, threshold: float = 0, adjust_intensity_for_ct=False) -> np.ndarray
Calculate a boundary mask based on the input image.
Parameters: - img (NII): The image used to create the boundary mask. - threshold(float): threshold - adjust_intensity_for_ct (bool): If True, adjust the image intensity by adding 1000.
Returns: NII: A segmentation of the boundary.
This function takes a NII and generates a boundary mask by marking specific regions. The intensity of the image can be adjusted for CT scans by adding 1000. The boundary mask is created by initializing corner points and using an "infect" process to mark neighboring points. The boundary mask is initiated with zeros, and specific boundary points are set to 1. The "infect" function iteratively marks neighboring points in the mask. The process starts from the initial points and corner points of the image. The infection process continues until the infect_list is empty. The resulting boundary mask is modified by subtracting 1 from all non-zero values and setting the remaining zeros to 2. The sum of the boundary mask values is printed before returning the modified NII object.
Source code in TPTBox/core/np_utils.py
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 | |
np_betti_numbers
¶
Calculates the Betti numbers B0, B1, and B2 for a 3D binary image.
Uses the Euler characteristic to derive the counts from connected-component analysis of both the foreground (26-connected) and background (6-connected).
B0: Number of connected components. B1: Number of loops / handles (tunnels). B2: Number of fully enclosed voids.
Code prototyped by Martin Menten (Imperial College), Suprosanna Shit (TU Munich), and Johannes C. Paetzold (Imperial College). Source: https://github.com/CoWBenchmark/TopCoW_Eval_Metrics/blob/master/metric_functions.py
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
ndarray
|
3D binary array (values must be 0 or 1). |
required |
verbose
|
bool
|
If True, prints the Betti numbers. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[int, int, int]
|
tuple[int, int, int]: |
Source code in TPTBox/core/np_utils.py
np_calc_overlapping_labels
¶
np_calc_overlapping_labels(reference_arr: ndarray, prediction_arr: ndarray) -> list[tuple[int, int]]
Calculates the pairs of labels that are overlapping in at least one voxel (fast).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction_arr
|
ndarray
|
Numpy array containing the prediction labels. |
required |
reference_arr
|
ndarray
|
Numpy array containing the reference labels. |
required |
ref_labels
|
list[int]
|
List of unique reference labels. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
list[tuple[int, int]]: List of tuples of labels that overlap in at least one voxel |
Source code in TPTBox/core/np_utils.py
np_normalize_to_range
¶
Normalize array values so the minimum maps to min_value and the maximum is capped at max_value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Input array to normalize. Modified in-place. |
required |
min_value
|
float
|
Target minimum value after shift. Defaults to 0. |
0
|
max_value
|
float
|
Upper bound; if the original maximum exceeds this, values are scaled down proportionally. Defaults to 1500. |
1500
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The normalized array (same object as input, modified in-place). |
Source code in TPTBox/core/np_utils.py
np_fill_holes_global_with_majority_voting
¶
np_fill_holes_global_with_majority_voting(arr: UINTARRAY, connectivity: int = 3, inplace: bool = False, verbose=False) -> UINTARRAY
Fill holes globaly (across labels) and resolves inter-label conflicts with majority voting of neighbors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
input array |
required |
connectivity
|
int
|
connectivity of connected components of the holes. Defaults to 3. |
3
|
inplace
|
bool
|
Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
arr |
UINTARRAY
|
Array with all global holes filled |
Source code in TPTBox/core/np_utils.py
np_map_labels_based_on_majority_label_mask_overlap
¶
np_map_labels_based_on_majority_label_mask_overlap(arr: UINTARRAY, label_mask: ndarray, label_ref: LABEL_REFERENCE = None, dilate_pixel: int = 1, inplace: bool = False, no_match_label=0) -> UINTARRAY
Relabels all individual labels from input array to the majority labels of a given label_mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
UINTARRAY
|
input array to be relabeled |
required |
label_mask
|
ndarray
|
the mask from which to pull the target labels. |
required |
labels
|
int | list[int] | None
|
Which labels in the input to process. Defaults to None. |
required |
dilate_pixel
|
int
|
If true, will dilate the input to calculate the overlap. Defaults to 1. |
1
|
inplace
|
bool
|
Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
arr |
UINTARRAY
|
input array with all labels in labels relabeled |