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/__init__.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/__init__.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/__init__.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/__init__.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/__init__.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/__init__.py
411 412 413 414 415 416 417 418 419 420 421 422 423 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 501 502 | |
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/__init__.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/__init__.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/__init__.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/__init__.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/__init__.py
mode(a)
¶
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/__init__.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. |