Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

utils.images

utils.images

Functions

NameDescription
extract_brainExtract the brain from an image file using HD-BET.

extract_brain

utils.images.extract_brain(
    file,
    device='cuda',
    use_tta=True,
    save_mask=True,
    extract_brain=True,
    verbose=False,
)

Extract the brain from an image file using HD-BET.

This function processes NIfTI files or directories containing a NIfTI to extract the brain region using the HD-BET (HD-Brain Extraction Tool). It supports optional test-time augmentation (TTA) and allows saving the brain mask and/or the brain-extracted image.

Parameters

NameTypeDescriptionDefault
filestr | Path | list[str | Path]The path(s) to the image file(s) or directories containing a NIfTI to extract the brain from. If a directory is provided, the NIfTI inside it is used.required
devicestrThe device to use for processing. Default is “cuda”.'cuda'
use_ttaboolWhether to use test-time augmentation (TTA) during brain extraction. Default is True.True
save_maskboolWhether to save the brain mask. Default is True.True
extract_brainboolWhether to compute and save the brain-extracted image. Default is True.True
verboseboolWhether to enable verbose logging. Default is False.False

Returns

NameTypeDescription
Path | list[Path]The path(s) to the brain-extracted NIfTI file(s). If a single file is provided as input, a single Path object is returned. If a list of files is provided, a list of Path objects is returned.

Raises

NameTypeDescription
ValueErrorIf the input file does not have a “.nii.gz” suffix or if the input is invalid.
ImportErrorIf the required dependencies (torch, HD-BET) are not installed.

Notes

Examples

Extract the brain from a single NIfTI file:

>>> extract_brain("path/to/image.nii.gz")
Extract the brain from multiple NIfTI files:
>>> extract_brain(["path/to/image1.nii.gz", "path/to/image2.nii.gz"])
Extract the brain from the NIfTI inside a directory:
>>> extract_brain("path/to/series_directory")