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_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
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
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: None | int = 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
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 | |
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: None | int = 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
879 880 881 882 883 884 885 886 887 888 889 890 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 | |
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
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 | |
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
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 | |
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 |