brainles_preprocessing
Modality
- class brainles_preprocessing.modality.CenterModality(modality_name: str, input_path: str | Path, normalizer: Normalizer | None = None, raw_bet_output_path: str | Path | None = None, raw_skull_output_path: str | Path | None = None, raw_defaced_output_path: str | Path | None = None, normalized_bet_output_path: str | Path | None = None, normalized_skull_output_path: str | Path | None = None, normalized_defaced_output_path: str | Path | None = None, atlas_correction: bool = True, n4_bias_correction: bool = False, bet_mask_output_path: str | Path | None = None, defacing_mask_output_path: str | Path | None = None)
Bases:
ModalityRepresents a medical image center modality with associated preprocessing information.
- Parameters:
modality_name (str) – Name of the modality, e.g., “T1”, “T2”, “FLAIR”.
input_path (str or Path) – Path to the input modality data.
normalizer (Normalizer, optional) – An optional normalizer for intensity normalization.
raw_bet_output_path (str or Path, optional) – Path to save the raw brain extracted modality data.
raw_skull_output_path (str or Path, optional) – Path to save the raw modality data with skull.
raw_defaced_output_path (str or Path, optional) – Path to save the raw defaced modality data.
normalized_bet_output_path (str or Path, optional) – Path to save the normalized brain extracted modality data. Requires a normalizer.
normalized_skull_output_path (str or Path, optional) – Path to save the normalized modality data with skull. Requires a normalizer.
normalized_defaced_output_path (str or Path, optional) – Path to save the normalized defaced modality data. Requires a normalizer.
atlas_correction (bool, optional) – Indicates whether atlas correction should be performed.
n4_bias_correction (bool, optional) – Indicates whether N4 bias correction should be performed.
bet_mask_output_path (str or Path, optional) – Path to save the brain extraction mask.
defacing_mask_output_path (str or Path, optional) – Path to save the defacing mask.
- modality_name
Name of the modality.
- Type:
str
- input_path
Path to the input modality data.
- Type:
str or Path
- normalizer
An optional normalizer for intensity normalization.
- Type:
Normalizer, optional
- raw_bet_output_path
Path to save the raw brain extracted modality data.
- Type:
str or Path, optional
- raw_skull_output_path
Path to save the raw modality data with skull.
- Type:
str or Path, optional
- raw_defaced_output_path
Path to save the raw defaced modality data.
- Type:
str or Path, optional
- normalized_bet_output_path
Path to save the normalized brain extracted modality data. Requires a normalizer.
- Type:
str or Path, optional
- normalized_skull_output_path
Path to save the normalized modality data with skull. Requires a normalizer.
- Type:
str or Path, optional
- normalized_defaced_output_path
Path to save the normalized defaced modality data. Requires a normalizer.
- Type:
str or Path, optional
- bet
Indicates whether brain extraction is enabled.
- Type:
bool
- atlas_correction
Indicates whether atlas correction should be performed.
- Type:
bool
- n4_bias_correction
Indicates whether N4 bias correction should be performed.
- Type:
bool
- bet_mask_output_path
Path to save the brain extraction mask.
- Type:
Path, optional
- defacing_mask_output_path
Path to save the defacing mask.
- Type:
Path, optional
Example
>>> t1_modality = CenterModality( ... modality_name="T1", ... input_path="/path/to/input_t1.nii", ... normalizer=PercentileNormalizer(), ... raw_bet_output_path="/path/to/raw_bet_t1.nii", ... normalized_bet_output_path="/path/to/norm_bet_t1.nii", ... bet_mask_output_path="/path/to/bet_mask_t1.nii", ... )
- deface(defacer: Defacer, defaced_dir_path: str | Path, registrator: Registrator | None = None) Path | None
Deface the current modality using the specified defacer.
- Parameters:
defacer (Defacer) – The defacer object.
defaced_dir_path (str or Path) – Directory to store defacing results.
registrator (Registrator, optional) – The registrator object for atlas registration.
- Returns:
Path to the defacing mask if successful, None otherwise.
- Return type:
Path | None
- extract_brain_region(brain_extractor: BrainExtractor, bet_dir_path: str | Path, use_gpu: bool = True) Path
Extract the brain region using the specified brain extractor.
- Parameters:
brain_extractor (BrainExtractor) – The brain extractor object.
bet_dir_path (str or Path) – Directory to store brain extraction results.
use_gpu (bool) – Whether to use GPU for brain extraction if available.
- Returns:
Path to the extracted brain mask.
- Return type:
Path
- save_mask(mask_path: str | Path, output_path: Path) None
Save the mask to the specified output path.
- Parameters:
mask_path (Union[str, Path]) – Mask NifTI file path.
output_path (Path) – Output NifTI file path.
- class brainles_preprocessing.modality.Modality(modality_name: str, input_path: str | Path, normalizer: Normalizer | None = None, raw_bet_output_path: str | Path | None = None, raw_skull_output_path: str | Path | None = None, raw_defaced_output_path: str | Path | None = None, normalized_bet_output_path: str | Path | None = None, normalized_skull_output_path: str | Path | None = None, normalized_defaced_output_path: str | Path | None = None, atlas_correction: bool = True, n4_bias_correction: bool = False)
Bases:
objectRepresents a medical image modality with associated preprocessing information.
- Parameters:
modality_name (str) – Name of the modality, e.g., “T1”, “T2”, “FLAIR”.
input_path (str or Path) – Path to the input modality data.
normalizer (Normalizer, optional) – An optional normalizer for intensity normalization.
raw_bet_output_path (str or Path, optional) – Path to save the raw brain extracted modality data.
raw_skull_output_path (str or Path, optional) – Path to save the raw modality data with skull.
raw_defaced_output_path (str or Path, optional) – Path to save the raw defaced modality data.
normalized_bet_output_path (str or Path, optional) – Path to save the normalized brain extracted modality data. Requires a normalizer.
normalized_skull_output_path (str or Path, optional) – Path to save the normalized modality data with skull. Requires a normalizer.
normalized_defaced_output_path (str or Path, optional) – Path to save the normalized defaced modality data. Requires a normalizer.
atlas_correction (bool, optional) – Indicates whether atlas correction should be performed.
n4_bias_correction (bool, optional) – Indicates whether N4 bias correction should be performed.
- modality_name
Name of the modality.
- Type:
str
- input_path
Path to the input modality data.
- Type:
str or Path
- normalizer
An optional normalizer for intensity normalization.
- Type:
Normalizer, optional
- raw_bet_output_path
Path to save the raw brain extracted modality data.
- Type:
str or Path, optional
- raw_skull_output_path
Path to save the raw modality data with skull.
- Type:
str or Path, optional
- raw_defaced_output_path
Path to save the raw defaced modality data.
- Type:
str or Path, optional
- normalized_bet_output_path
Path to save the normalized brain extracted modality data. Requires a normalizer.
- Type:
str or Path, optional
- normalized_skull_output_path
Path to save the normalized modality data with skull. Requires a normalizer.
- Type:
str or Path, optional
- normalized_defaced_output_path
Path to save the normalized defaced modality data. Requires a normalizer.
- Type:
str or Path, optional
- bet
Indicates whether brain extraction is enabled.
- Type:
bool
- atlas_correction
Indicates whether atlas correction should be performed.
- Type:
bool
- n4_bias_correction
Indicates whether N4 bias correction should be performed.
- Type:
bool
- coregistration_transform_path
Path to the coregistration transformation matrix, will be set after coregistration.
- Type:
str or None
Example
>>> t1_modality = Modality( ... modality_name="T1", ... input_path="/path/to/input_t1.nii", ... normalizer=PercentileNormalizer(), ... raw_bet_output_path="/path/to/raw_bet_t1.nii", ... normalized_bet_output_path="/path/to/norm_bet_t1.nii", ... )
- _find_transformation_matrix(transform_incomplete_path: Path) Path | None
- apply_bet_mask(brain_extractor: BrainExtractor, mask_path: str | Path, bet_dir: str | Path) None
Apply a brain mask to the current modality using the specified brain extractor.
- Parameters:
brain_extractor (BrainExtractor) – The brain extractor object.
mask_path (str or Path) – Path to the brain mask.
bet_dir (str or Path) – Directory to store computed bet images.
- Returns:
None
- apply_deface_mask(defacer: Defacer, mask_path: str | Path, deface_dir: str | Path) None
Apply a deface mask to the current modality using the specified brain extractor.
- Parameters:
defacer (Defacer) – The Defacer object.
mask_path (str or Path) – Path to the deface mask.
defaced_masked_dir_path (str or Path) – Directory to store masked images.
- property bet: bool
Check if any brain extraction output is specified.
- Returns:
True if any brain extraction output is specified, False otherwise.
- Return type:
bool
- deface(defacer, defaced_dir_path: str | Path, registrator: Registrator | None = None) Path | None
WARNING: Legacy method. Please Migrate to use the CenterModality Class. Will be removed in future versions.
- extract_brain_region(brain_extractor: BrainExtractor, bet_dir_path: str | Path) Path
WARNING: Legacy method. Please Migrate to use the CenterModality Class. Will be removed in future versions.
Extract the brain region using the specified brain extractor.
- Parameters:
brain_extractor (BrainExtractor) – The brain extractor object.
bet_dir_path (str or Path) – Directory to store brain extraction results.
- Returns:
Path to the extracted brain mask.
- Return type:
Path
- normalize(temporary_directory: str | Path, store_unnormalized: str | Path | None = None) None
Normalize the image using the specified normalizer.
- Parameters:
temporary_directory (str or Path) – Path to the temporary directory.
store_unnormalized (str or Path, optional) – Path to store unnormalized images.
- Returns:
None
- register(registrator: Registrator, fixed_image_path: str | Path, registration_dir: str | Path, moving_image_name: str, step: PreprocessorSteps) Path
Register the current modality to a fixed image using the specified registrator.
- Parameters:
registrator (Registrator) – The registrator object.
fixed_image_path (str or Path) – Path to the fixed image.
registration_dir (str or Path) – Directory to store registration results.
moving_image_name (str) – Name of the moving image.
step (PreprocessorSteps) – The current preprocessing step.
- Returns:
Path to the registration matrix.
- Return type:
Path
- property requires_deface: bool
Check if any defacing output is specified.
- Returns:
True if any defacing output is specified, False otherwise.
- Return type:
bool
- save_current_image(output_path: str | Path, normalization: bool = False) None
Save the current image to the specified output path.
- Parameters:
output_path (str or Path) – The output file path.
normalization (bool, optional) – If True, apply normalization before saving.
- Returns:
None
- transform(registrator: Registrator, fixed_image_path: str | Path, registration_dir_path: str | Path, moving_image_name: str, transformation_matrix_path: str | Path, step: PreprocessorSteps) None
Transform the current modality using the specified registrator and transformation matrix.
- Parameters:
registrator (Registrator) – The registrator object.
fixed_image_path (str or Path) – Path to the fixed image.
registration_dir_path (str or Path) – Directory to store transformation results.
moving_image_name (str) – Name of the moving image.
transformation_matrix_path (str or Path) – Path to the transformation matrix.
step (PreprocessorSteps) – The current preprocessing step.
- Returns:
None
Preprocessor
- class brainles_preprocessing.preprocessor.preprocessor.BasePreprocessor(center_modality: CenterModality, moving_modalities: List[Modality], registrator: Registrator = None, brain_extractor: BrainExtractor | None = None, defacer: Defacer | None = None, n4_bias_corrector: N4BiasCorrector | None = None, temp_folder: str | Path | None = None, use_gpu: bool = True, limit_cuda_visible_devices: str | None = None)
Bases:
ABCBase class to preprocesses medical image modalities.
- Parameters:
center_modality (CenterModality) – The central modality for coregistration.
moving_modalities (List[Modality]) – List of modalities to be coregistered to the central modality.
registrator (Registrator) – The registrator object for coregistration and registration to the atlas.
brain_extractor (Optional[BrainExtractor]) – The brain extractor object for brain extraction.
defacer (Optional[Defacer]) – The defacer object for defacing images.
n4_bias_corrector (Optional[N4BiasCorrector]) – The N4 bias corrector object for bias field correction. Defaults to SitkN4BiasCorrector with Otsu Thresholding.
temp_folder (Optional[str or Path]) – Path to a folder for storing intermediate results.
use_gpu (Optional[bool]) – Use GPU for processing if True, CPU if False, or automatically detect if None.
limit_cuda_visible_devices (Optional[str]) – Limit CUDA visible devices to a specific GPU ID.
- _abc_impl = <_abc._abc_data object>
- _add_log_file_handler(log_file: str | Path | None) int
Add a log file handler to the logger.
- Parameters:
log_file (Optional[Path | str]) – Path to the log file. If None, a default log file will be created (brainles_preprocessing_{timestamp}.log).
- Returns:
The logger id
- Return type:
int
- _check_for_name_conflicts()
Checks for name conflicts in the provided modalities.
- Raises:
ValueError – If any modality name is non-unique.
- _configure_gpu(use_gpu: bool, limit_cuda_visible_devices: str | None = None) None
Configures the environment for GPU usage based on the use_gpu parameter and CUDA availability.
- Parameters:
use_gpu (Optional[bool]) – Determines the GPU usage strategy.
- static _cuda_is_available() bool
Checks if CUDA is available on the system by attempting to run ‘nvidia-smi’.
- Returns:
True if ‘nvidia-smi’ can be executed successfully, indicating CUDA is available.
- Return type:
bool
- _save_output(src: str | Path, save_dir: str | Path | None)
Save the output from a source directory to the specified save directory.
- property all_modalities: List[Modality]
Returns a list of all modalities including the center modality.
- property requires_defacing: bool
Returns True if any modality requires defacing otherwise returns False.
- abstract run(*args, **kwargs)
Execute the preprocessing pipeline, encompassing
- run_brain_extraction(save_dir_brain_extraction: str | Path | None = None) None
Extract brain regions using specified BrainExtractor.
- Parameters:
save_dir_brain_extraction (Optional[str or Path], optional) – Directory path to save intermediate brain extraction results. Defaults to None.
- run_coregistration(save_dir_coregistration: str | Path | None = None) None
Coregister moving modalities to center modality.
- Parameters:
save_dir_coregistration (str, optional) – Directory path to save intermediate coregistration results.
- run_n4_bias_correction(save_dir_n4_bias_correction: str | Path | None = None) None
Apply optional N4 bias correction to modalities.
- Parameters:
save_dir_n4_bias_correction (Optional[Union[str, Path]], optional) – Directory path to save intermediate N4 bias correction results. Defaults to None.
- class brainles_preprocessing.preprocessor.atlas_centric_preprocessor.AtlasCentricPreprocessor(center_modality: CenterModality, moving_modalities: List[Modality], registrator: Registrator | None = None, brain_extractor: BrainExtractor | None = None, defacer: Defacer | None = None, atlas_image_path: str | Path | Atlas = Atlas.BRATS_SRI24, n4_bias_corrector: N4BiasCorrector | None = None, temp_folder: str | Path | None = None, use_gpu: bool = True, limit_cuda_visible_devices: str | None = None)
Bases:
BasePreprocessorPreprocesses medical image modalities using coregistration, atlas-registration, atlas-correction, normalization, brain extraction, and more.
- Parameters:
center_modality (CenterModality) – The central modality for coregistration.
moving_modalities (List[Modality]) – List of modalities to be coregistered to the central modality.
registrator (Registrator) – The registrator object for coregistration and registration to the atlas.
brain_extractor (Optional[BrainExtractor]) – The brain extractor object for brain extraction.
defacer (Optional[Defacer]) – The defacer object for defacing images.
atlas_image_path (Optional[str or Path]) – Path to the atlas image for registration (default is the T1 atlas).
n4_bias_corrector (Optional[N4BiasCorrector]) – The N4 bias corrector object for bias field correction. Defaults to SitkN4BiasCorrector with Otsu Thresholding.
temp_folder (Optional[str or Path]) – Path to a folder for storing intermediate results.
use_gpu (Optional[bool]) – Use GPU for processing if True, CPU if False, or automatically detect if None.
limit_cuda_visible_devices (Optional[str]) – Limit CUDA visible devices to a specific GPU ID.
- _abc_impl = <_abc._abc_data object>
- run(save_dir_coregistration: str | Path | None = None, save_dir_atlas_registration: str | Path | None = None, save_dir_atlas_correction: str | Path | None = None, save_dir_n4_bias_correction: str | Path | None = None, save_dir_brain_extraction: str | Path | None = None, save_dir_defacing: str | Path | None = None, save_dir_transformations: str | Path | None = None, log_file: str | Path | None = None)
Execute the atlas-centric preprocessing pipeline
- Parameters:
save_dir_coregistration (str or Path, optional) – Directory path to save intermediate coregistration results.
save_dir_atlas_registration (str or Path, optional) – Directory path to save intermediate atlas registration results.
save_dir_atlas_correction (str or Path, optional) – Directory path to save intermediate atlas correction results.
save_dir_n4_bias_correction (str or Path, optional) – Directory path to save intermediate N4 bias correction results.
save_dir_brain_extraction (str or Path, optional) – Directory path to save intermediate brain extraction results.
save_dir_defacing (str or Path, optional) – Directory path to save intermediate defacing results.
save_dir_transformations (str or Path, optional) – Directory path to save transformation matrices. Defaults to None.
log_file (str or Path, optional) – Path to save the log file. Defaults to a timestamped file in the current directory.
This method orchestrates the entire preprocessing workflow by sequentially performing:
Co-registration: Aligning moving modalities to the central modality.
Atlas Registration: Aligning the central modality to a predefined atlas.
(Optional) Atlas Correction: Applying additional correction in atlas space if specified.
(Optional) N4 Bias Correction: Applying N4 bias field correction if specified.
(Optional) Brain Extraction: Optionally extracting brain regions using specified masks. Only executed if any modality requires a brain extraction output (or a defacing output that requires prior brain extraction).
(Optional) Defacing: Optionally deface images to remove facial features. Only executed if any modality requires a defacing output.
Results are saved in the specified directories, allowing for modular and configurable output storage.
- run_atlas_correction(save_dir_atlas_correction: str | Path | None = None) None
Apply optional atlas correction to moving modalities.
- Parameters:
save_dir_atlas_correction (Optional[str or Path], optional) – Directory path to save intermediate atlas correction results. Defaults to None.
- run_atlas_registration(save_dir_atlas_registration: str | Path | None = None) None
Register center modality to atlas.
- Parameters:
save_dir_atlas_registration (Optional[str or Path], optional) – Directory path to save intermediate atlas registration results. Defaults to None.
- run_defacing(save_dir_defacing: str | Path | None = None) None
Deface images to remove facial features using specified Defacer.
- Parameters:
save_dir_defacing (Optional[str or Path], optional) – Directory path to save intermediate defacing results. Defaults to None.
- class brainles_preprocessing.preprocessor.native_space_preprocessor.NativeSpacePreprocessor(center_modality: CenterModality, moving_modalities: List[Modality], registrator: Registrator = None, brain_extractor: BrainExtractor | None = None, defacer: Defacer | None = None, n4_bias_corrector: N4BiasCorrector | None = None, temp_folder: str | Path | None = None, use_gpu: bool = True, limit_cuda_visible_devices: str | None = None)
Bases:
BasePreprocessorPreprocesses medical image modalities using coregistration, atlas-registration, atlas-correction, normalization, brain extraction, and more.
- Parameters:
center_modality (CenterModality) – The central modality for coregistration.
moving_modalities (List[Modality]) – List of modalities to be coregistered to the central modality.
registrator (Registrator) – The registrator object for coregistration and registration to the atlas.
brain_extractor (Optional[BrainExtractor]) – The brain extractor object for brain extraction.
defacer (Optional[Defacer]) – The defacer object for defacing images.
n4_bias_corrector (Optional[N4BiasCorrector]) – The N4 bias corrector object for bias field correction. Defaults to SitkN4BiasCorrector with Otsu Thresholding.
temp_folder (Optional[str or Path]) – Path to a folder for storing intermediate results.
use_gpu (Optional[bool]) – Use GPU for processing if True, CPU if False, or automatically detect if None.
limit_cuda_visible_devices (Optional[str]) – Limit CUDA visible devices to a specific GPU ID.
- _abc_impl = <_abc._abc_data object>
- run(save_dir_coregistration: str | Path | None = None, save_dir_n4_bias_correction: str | Path | None = None, save_dir_brain_extraction: str | Path | None = None, save_dir_defacing: str | Path | None = None, save_dir_transformations: str | Path | None = None, log_file: str | Path | None = None)
Execute the native space preprocessing pipeline
- Parameters:
save_dir_coregistration (str or Path, optional) – Directory path to save intermediate coregistration results.
save_dir_n4_bias_correction (str or Path, optional) – Directory path to save intermediate N4 bias correction results.
save_dir_brain_extraction (str or Path, optional) – Directory path to save intermediate brain extraction results.
save_dir_defacing (str or Path, optional) – Directory path to save intermediate defacing results.
save_dir_transformations (str or Path, optional) – Directory path to save transformation matrices. Defaults to None.
log_file (str or Path, optional) – Path to save the log file. Defaults to a timestamped file in the current directory.
This method orchestrates the entire preprocessing workflow by sequentially performing:
Co-registration: Aligning moving modalities to the central modality.
(Optional) N4 Bias Correction: Applying N4 bias field correction if specified.
(Optional) Brain Extraction: Optionally extracting brain regions using specified masks. Only executed if any modality requires a brain extraction output (or a defacing output that requires prior brain extraction).
(Optional) Defacing: Optionally deface images to remove facial features. Only executed if any modality requires a defacing output.
Results are saved in the specified directories, allowing for modular and configurable output storage.
- run_defacing(save_dir_defacing: str | Path | None = None) None
Deface images to remove facial features using specified Defacer.
- Parameters:
save_dir_defacing (Optional[str or Path], optional) – Directory path to save intermediate defacing results. Defaults to None.
Constants
- class brainles_preprocessing.constants.Atlas(value)
Bases:
str,EnumAn enumeration.
- BRATS_MNI152 = 'brats_MNI152lin_T1_1mm.nii.gz'
Slightly modified MNI152 atlas as found in the BraTS challenges
- BRATS_SRI24 = 'brats_sri24.nii'
Slightly modified SRI24 atlas as found in the BraTS challenges
- BRATS_SRI24_SKULLSTRIPPED = 'brats_sri24_skullstripped.nii'
Slightly modified SRI24 skull stripped atlas as found in the BraTS challenges
- MNI152 = 'mni_icbm152_t1_tal_nlin_sym_09c.nii'
//nist.mni.mcgill.ca/icbm-152-nonlinear-atlases-2009/
- Type:
MNI_ICBM_2009c_Nonlinear_Symmetric atlas from https
- SRI24 = 'sri24.nii'
//www.nitrc.org/frs/download.php/4502/sri24_anatomy_unstripped_nifti.zip
- Type:
SRI24 atlas from https
- SRI24_SKULLSTRIPPED = 'sri24_skullstripped.nii'
//www.nitrc.org/frs/download.php/4499/sri24_anatomy_nifti.zip
- Type:
SRI24 skull stripped atlas from https
Transform
- class brainles_preprocessing.transform.Transform(transformations_dir: str | Path, registrator: Registrator | None = None)
Bases:
objectClass to apply precomputed transformations based on the registration process. Common use case is to apply inverse transformations to transform e.g. segmentations in atlas space back to native space or transform existing labels in native space to atlas space.
- apply(target_modality_name: str, target_modality_img: str | Path, moving_image: str | Path, output_img_path: str | Path, log_file_path: str | Path, interpolator: str | None = None, inverse: bool = False) None
Apply forward/ inverse transformation to a moving image to align it with a target modality.
- Parameters:
target_modality_name (str) – Name of the target modality. Must match the name used to create the transformations.
target_modality_img (Union[str, Path]) – Path to the target modality image.
moving_image (Union[str, Path]) – Path to the moving image. E.g., this could be a segmentation in atlas space.
output_img_path (Union[str, Path]) – Path where the transformed image will be saved.
log_file_path (Union[str, Path]) – Path to the log file where transformation details will be written.
interpolator (Optional[str]) – Interpolation method used during transformation.
inverse (bool) –
If True, applies the inverse transformation. Default is False. Available options depend on the chosen registrator:
- ANTsRegistrator:
”linear”
”nearestNeighbor” (default)
”multiLabel” (deprecated, prefer “genericLabel”)
”gaussian”
”bSpline”
”cosineWindowedSinc”
”welchWindowedSinc”
”hammingWindowedSinc”
”lanczosWindowedSinc”
”genericLabel” (recommended for label images)
- NiftyReg:
”0”: nearest neighbor (default)
”1”: linear
”3”: cubic spline
”4”: sinc
- Raises:
AssertionError – If the transformations directory for the given modality does not exist.