General utililities¶
General utilities for nnU-Net serving and command-line workflows.
This module collects small, reusable helpers for argument parsing, DICOM and image I/O, metadata handling, simple type conversions, and GPU/wall-clock utility functions. They are shared across the FastAPI service and CLI entry points to keep higher-level code focused on orchestration rather than low- level plumbing.
calculate_iou(a, b)
¶
Calculates the intersection of the union between arrays a and b.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ndarray
|
array. |
required |
b
|
ndarray
|
array. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
float value for the intersection over the union. |
Source code in src/nnunet_serve/utils.py
calculate_iou_a_over_b(a, b)
¶
Calculates how much of a overlaps with b.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
ndarray
|
array. |
required |
b
|
ndarray
|
array. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
float value for the intersection over the union. |
Source code in src/nnunet_serve/utils.py
copy_information_nd(target_image, source_image)
¶
Copies information from a source image to a target image. Unlike the standard CopyInformation method in SimpleITK, the source image can have fewer axes than the target image as long as the first n axes of each are identical (where n is the number of axes in the source image).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_image
|
Image
|
target image. |
required |
source_image
|
Image
|
source information for metadata. |
required |
Raises:
| Type | Description |
|---|---|
Exception
|
if the source image has more dimensions than the target image. |
Returns:
| Type | Description |
|---|---|
Image
|
sitk.Image: target image with metadata copied from source image. The metadata information for the additional axes is set to 0 in the case of the origin, 1.0 in the case of the spacing and to the identity in the case of the direction. |
Source code in src/nnunet_serve/utils.py
dicom_orientation_to_sitk_direction(orientation)
¶
Converts the DICOM orientation to SITK orientation. Based on the nibabel code that does the same. DICOM uses a more economic encoding as one only needs to specify two of the three cosine directions as they are all orthogonal. SITK does the more verbose job of specifying all three components of the orientation.
This is based on the Nibabel documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
orientation
|
Sequence[float]
|
DICOM orientation. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: SITK (flattened) orientation. |
Source code in src/nnunet_serve/utils.py
export_to_dicom_seg_dcmqi(mask_path, metadata_path, file_paths, output_dir, output_file_name='prediction')
¶
Exports a SITK image mask as a DICOM segmentation object with dcmqi.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_path
|
str
|
path to (S)ITK mask. |
required |
metadata_path
|
str
|
path to metadata template file. |
required |
file_paths
|
Sequence[str]
|
list of DICOM file paths corresponding to the original series. |
required |
output_dir
|
str
|
path to output directory. |
required |
output_file_name
|
str
|
output file name. Defaults to "prediction". |
'prediction'
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
"success" if the process was successful, "empty mask" if the SITK mask contained no values. |
Source code in src/nnunet_serve/utils.py
extract_lesion_candidates(softmax, threshold=0.1, min_confidence=None, min_voxels_detection=10, max_prob_round_decimals=4, intersect_with=None, min_intersection=0.1)
¶
Lesion candidate protocol as implemented in [1]. Essentially:
1. Clips probabilities to be above a threshold
2. Detects connected components
3. Filters based on candidate size
4. Filters based on maximum probability value
5. Returns the connected components
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
softmax
|
ndarray
|
array with softmax probability values. |
required |
threshold
|
float
|
threshold below which values are set to 0. Defaults to 0.10. |
0.1
|
min_confidence
|
float
|
minimum maximum probability value for each object after connected component analysis. Defaults to None (no filtering). |
None
|
min_voxels_detection
|
int
|
minimum object size in voxels. Defaults to 10. |
10
|
max_prob_round_decimals
|
int
|
maximum number of decimal places. Defaults to 4. |
4
|
intersect_with
|
str | Image
|
calculates the intersection of each candidate with the image specified in intersect_with. If the intersection is larger than min_intersection, the candidate is kept; otherwise it is discarded. Defaults to None. |
None
|
min_intersection
|
float
|
minimum intersection over the union to keep candidate. Defaults to 0.1. |
0.1
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, list[tuple[int, float]], ndarray]
|
tuple[np.ndarray, list[tuple[int, float]], np.ndarray]: the output probability map, a list of confidence values, and the connected components array as returned by ndimage.label. |
Source code in src/nnunet_serve/utils.py
666 667 668 669 670 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 | |
filter_by_bvalue(dicom_files, target_bvalue, exact=False)
¶
Selects the DICOM values with a b-value which is exactly or closest to target_bvalue (depending on whether exact is True or False).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dicom_files
|
list
|
list of pydicom file objects. |
required |
target_bvalue
|
int
|
the expected b-value. |
required |
exact
|
bool
|
whether the b-value matching is to be exact (raises error if exact target_bvalue is not available) or approximate returns the b-value which is closest to target_bvalue. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
list of b-value-filtered pydicom file objects. |
Source code in src/nnunet_serve/utils.py
filter_by_bvalue_from_dict(dicom_files, target_bvalue, exact=False)
¶
Selects the DICOM values with a b-value which is exactly or closest to target_bvalue (depending on whether exact is True or False).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dicom_files
|
list
|
list of pydicom file objects. |
required |
target_bvalue
|
int
|
the expected b-value. |
required |
exact
|
bool
|
whether the b-value matching is to be exact (raises error if exact target_bvalue is not available) or approximate returns the b-value which is closest to target_bvalue. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
list of b-value-filtered pydicom file objects. |
Source code in src/nnunet_serve/utils.py
float_or_none(x)
¶
Converts a string to float if it is different from "none"; if that is the case, the function returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str
|
string to be converted. |
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: None or the converted float. |
Source code in src/nnunet_serve/utils.py
get_contiguous_arr_idxs(positions, ranking)
¶
Uses the ranking to find breaks in positions and returns the elements in L which belong to the first contiguous array. Assumes that positions is an array of positions (a few of which may be overlapping), ranking is the order by which each slice was acquired and d is a dict whose keys will be filtered according to this.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
positions
|
ndarray
|
positions with shape [N,3]. |
required |
ranking
|
ndarray
|
ranking used to sort slices. |
required |
Returns:
| Type | Description |
|---|---|
ndarray | None
|
np.ndarray: an index vector with the instance numbers of the slices to be kept. |
Source code in src/nnunet_serve/utils.py
get_gpu_memory()
¶
Utility to retrieve value for free GPU memory.
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: list of available GPU memory (each one corresponds to a GPU index). |
Source code in src/nnunet_serve/utils.py
get_origin(positions, z_axis=2)
¶
Returns the origin position from an array of positions (minimum for a given z-axis).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
positions
|
ndarray
|
array containing all the positions in a given set of arrays. |
required |
z_axis
|
int
|
index corresponding to the z-axis. Defaults to 2. |
2
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: origin of the array. |
Source code in src/nnunet_serve/utils.py
get_study_uid(dicom_dir)
¶
Returns the study UID field from a random file in dicom_dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dicom_dir
|
str
|
directory with dicom (.dcm) files. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
string corresponding to study UID. |
Source code in src/nnunet_serve/utils.py
int_or_float(x)
¶
Parses a string into an integer when possible, otherwise a float.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str
|
String representation of a numeric value. |
required |
Returns:
| Type | Description |
|---|---|
int | float
|
int | float: The parsed integer if conversion to |
int | float
|
otherwise the parsed |
Source code in src/nnunet_serve/utils.py
int_or_list_of_ints(x)
¶
Converts a comma-separated string of integers into an int or list.
The input string is first stripped of spaces and trailing commas. If the
value is "all" (case-insensitive), the function returns None. If the
string contains commas, it is split into a list of unique integers.
Otherwise, it is converted to a single integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
str
|
String encoding an integer, a comma-separated list of
integers, or the special value |
required |
Returns:
| Type | Description |
|---|---|
int | list[int]
|
int | list[int] | None: |
int | list[int]
|
list of unique integers. |
Source code in src/nnunet_serve/utils.py
list_of_str(x)
¶
make_parser(description='Entrypoint for nnUNet prediction. Handles all data format conversions and cascades of predictions.', exclude=None)
¶
Convenience function to generate argparse CLI parser. Helps with
consistent inputs when dealing with multiple entrypoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
str
|
description for the
|
'Entrypoint for nnUNet prediction. Handles all data format conversions and cascades of predictions.'
|
Returns:
| Type | Description |
|---|---|
ArgumentParser
|
argparse.ArgumentParser: parser with specific args. |
Source code in src/nnunet_serve/utils.py
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 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 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 | |
mode(a)
¶
read_dicom_as_sitk(file_path, metadata={}, bvalue_for_filtering=None)
¶
Reads a DICOM series as an SITK file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
list of DICOM files or directory containing DICOM files. |
required |
metadata
|
dict[str, str]
|
metadata to be added to the SITK image. |
{}
|
Returns:
| Type | Description |
|---|---|
Image
|
sitk.Image: SITK image. |
Source code in src/nnunet_serve/utils.py
read_dicom_seg_as_volume(path)
¶
Reads a DICOM SEG object from disk and returns it as a volume image.
The function accepts either a directory containing a single DICOM SEG
file or a direct path to a DICOM file. It validates that the input file
has the expected SEG SOP Class UID and then uses MultiClassReader to
convert it into a SimpleITK.Image volume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to a DICOM SEG file or a directory containing exactly one such file. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provided directory contains more than one file. |
AssertionError
|
If the DICOM file does not have the SEG SOP Class UID
|
Returns:
| Type | Description |
|---|---|
Image
|
sitk.Image: The decoded segmentation volume. |
Source code in src/nnunet_serve/utils.py
small_object_removal(image, min_size=0.99)
¶
Removes small objects from a multi-label image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
ndarray
|
Input multi-label image. |
required |
min_size
|
float | int
|
Minimum size of objects to keep in voxels. If it is a float, computes the minimum size as a percentage of the maximum object size. Defaults to 0.99. |
0.99
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: Image with small objects removed. |
Source code in src/nnunet_serve/utils.py
wait_for_gpu(min_mem, timeout_s=120)
¶
Waits for a GPU with at least min_mem free memory to be free.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_mem
|
int
|
minimum amount of memory. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
GPU ID corresponding to freest GPU. |