Skip to content

HistogramStandardization

Histogram standardization

HistogramStandardization

Bases: NormalizationTransform

Perform histogram standardization of intensity values.

Implementation of New variants of a method of MRI scale standardization .

See example in torchio.transforms.HistogramStandardization.train().

Parameters:

Name Type Description Default
landmarks TypeLandmarks

Dictionary (or path to a PyTorch file with .pt or .pth extension in which a dictionary has been saved) whose keys are image names in the subject and values are NumPy arrays or paths to NumPy arrays defining the landmarks after training with torchio.transforms.HistogramStandardization.train().

required
masking_method TypeMaskingMethod None
**kwargs

See Transform for additional keyword arguments.

{}

Examples:

>>> import torch
>>> import torchio as tio
>>> landmarks = {
...     't1': 't1_landmarks.npy',
...     't2': 't2_landmarks.npy',
... }
>>> transform = tio.HistogramStandardization(landmarks)
>>> torch.save(landmarks, 'path_to_landmarks.pth')
>>> transform = tio.HistogramStandardization('path_to_landmarks.pth')

probability = self.parse_probability(p) instance-attribute

copy = copy instance-attribute

keep = keep instance-attribute

parse_input = parse_input instance-attribute

label_keys = label_keys instance-attribute

name property

masking_method = masking_method instance-attribute

landmarks = landmarks instance-attribute

landmarks_dict = self._parse_landmarks(landmarks) instance-attribute

args_names = ['landmarks', 'masking_method'] instance-attribute

__call__(data)

Transform data and return a result of the same type.

Parameters:

Name Type Description Default
data InputType

Instance of torchio.Subject, 4D torch.Tensor or numpy.ndarray with dimensions \((C, W, H, D)\), where \(C\) is the number of channels and \(W, H, D\) are the spatial dimensions. If the input is a tensor, the affine matrix will be set to identity. Other valid input types are a SimpleITK image, a torchio.Image, a NiBabel Nifti1 image or a dict. The output type is the same as the input type.

required

__repr__()

get_base_args()

Provides easy access to the arguments used to instantiate the base class (Transform) of any transform.

This method is particularly useful when a new transform can be represented as a variant of an existing transform (e.g. all random transforms), allowing for seamless instantiation of the existing transform with the same arguments as the new transform during apply_transform.

Note

The p argument (probability of applying the transform) is excluded to avoid multiplying the probability of both existing and new transform.

add_base_args(arguments, overwrite_on_existing=False)

Add the init args to existing arguments

apply_transform(subject)

add_transform_to_subject_history(subject)

to_range(n, around) staticmethod

parse_params(params, around, name, make_ranges=True, **kwargs)

_parse_range(nums_range, name, min_constraint=None, max_constraint=None, type_constraint=None) staticmethod

Adapted from [torchvision.transforms.RandomRotation][].

Parameters:

Name Type Description Default
nums_range TypeNumber | tuple[TypeNumber, TypeNumber]

Tuple of two numbers \((n_{min}, n_{max})\), where \(n_{min} \leq n_{max}\). If a single positive number \(n\) is provided, \(n_{min} = -n\) and \(n_{max} = n\).

required
name str

Name of the parameter, so that an informative error message can be printed.

required
min_constraint TypeNumber | None

Minimal value that \(n_{min}\) can take, default is None, i.e. there is no minimal value.

None
max_constraint TypeNumber | None

Maximal value that \(n_{max}\) can take, default is None, i.e. there is no maximal value.

None
type_constraint type | None

Precise type that \(n_{max}\) and \(n_{min}\) must take.

None

Returns:

Type Description
tuple[TypeNumber, TypeNumber]

A tuple of two numbers \((n_{min}, n_{max})\).

Raises:

Type Description
ValueError

if nums_range is negative

ValueError

if \(n_{max}\) or \(n_{min}\) is not a number

ValueError

if \(n_{max} \lt n_{min}\)

ValueError

if min_constraint is not None and \(n_{min}\) is smaller than min_constraint

ValueError

if max_constraint is not None and \(n_{max}\) is greater than max_constraint

ValueError

if type_constraint is not None and \(n_{max}\) and \(n_{max}\) are not of type type_constraint.

parse_interpolation(interpolation) staticmethod

parse_probability(probability) staticmethod

parse_include_and_exclude_keys(include, exclude, label_keys) staticmethod

validate_keys_sequence(keys, name) staticmethod

Ensure that the input is not a string but a sequence of strings.

nib_to_sitk(data, affine) staticmethod

sitk_to_nib(image) staticmethod

_get_reproducing_arguments()

Return a dictionary with the arguments that would be necessary to reproduce the transform exactly.

is_invertible()

inverse()

_use_seed(seed) staticmethod

Perform an operation using a specific seed for the PyTorch RNG.

get_sitk_interpolator(interpolation) staticmethod

parse_bounds(bounds_parameters) staticmethod

ones(tensor) staticmethod

mean(tensor) staticmethod

get_mask_from_masking_method(masking_method, subject, tensor, labels=None)

get_mask_from_anatomical_label(anatomical_label, tensor) staticmethod

get_mask_from_bounds(bounds_parameters, tensor)

_get_name_with_module()

Return the name of the transform including its module.

_tuples_to_lists(obj) staticmethod

to_hydra_config()

Return a dictionary representation of the transform for Hydra instantiation.

get_images_dict(subject)

get_images(subject)

arguments_are_dict()

Check if main arguments are dict.

Return True if the type of all attributes specified in the args_names have dict type.

__init__(landmarks, masking_method=None, **kwargs)

_parse_landmarks(landmarks) staticmethod

apply_normalization(subject, image_name, mask)

train(images_paths, cutoff=None, mask_path=None, masking_function=None, output_path=None, *, progress=True) classmethod

Extract average histogram landmarks from images used for training.

Parameters:

Name Type Description Default
images_paths Sequence[TypePath]

List of image paths used to train.

required
cutoff tuple[float, float] | None

Optional minimum and maximum quantile values, respectively, that are used to select a range of intensity of interest. Equivalent to \(pc_1\) and \(pc_2\) in Nyúl and Udupa's paper .

None
mask_path Sequence[TypePath] | TypePath | None

Path (or list of paths) to a binary image that will be used to select the voxels use to compute the stats during histogram training. If None, all voxels in the image will be used.

None
masking_function Callable | None

Function used to extract voxels used for histogram training.

None
output_path TypePath | None

Optional file path with extension .txt or .npy, where the landmarks will be saved.

None

Examples:

>>> import torch
>>> import numpy as np
>>> from pathlib import Path
>>> from torchio.transforms import HistogramStandardization
>>>
>>> t1_paths = ['subject_a_t1.nii', 'subject_b_t1.nii.gz']
>>> t2_paths = ['subject_a_t2.nii', 'subject_b_t2.nii.gz']
>>>
>>> t1_landmarks_path = Path('t1_landmarks.npy')
>>> t2_landmarks_path = Path('t2_landmarks.npy')
>>>
>>> t1_landmarks = (
...     t1_landmarks_path
...     if t1_landmarks_path.is_file()
...     else HistogramStandardization.train(t1_paths)
... )
>>> np.save(t1_landmarks_path, t1_landmarks)
>>>
>>> t2_landmarks = (
...     t2_landmarks_path
...     if t2_landmarks_path.is_file()
...     else HistogramStandardization.train(t2_paths)
... )
>>> np.save(t2_landmarks_path, t2_landmarks)
>>>
>>> landmarks_dict = {
...     't1': t1_landmarks,
...     't2': t2_landmarks,
... }
>>>
>>> transform = HistogramStandardization(landmarks_dict)