FastSurferCNN.data_loader.conform¶
- FastSurferCNN.data_loader.conform.apply_orientation(arr, ornt)[source]¶
Apply transformations implied by
ornt
to the first n axes of the arrayarr
.- Parameters:
- arrarray_like or
torch
Tensor
of
data
with
ndim
>=n
The image/data to reorient.
- ornt(n,2)
orientation
array
Orientation transform.
ornt[N,1]` is flip of axis N of the array implied by `shape`, where 1 means no flip and -1 means flip. For example, if ``N==0
andornt[0,1] == -1
, and there’s an arrayarr
of shapeshape
, the flip would correspond to the effect ofnp.flipud(arr)
.ornt[:,0]
is the transpose that needs to be done to the implied array, as inarr.transpose(ornt[:,0])
.
- arrarray_like or
- Returns:
- t_arr
ndarray
orTensor
The data array
arr
transformed according toornt
.
- t_arr
See also
nibabel.orientations.apply_orientation
This function is an extension to
nibabel.orientations.apply_orientation
.
- FastSurferCNN.data_loader.conform.check_affine_in_nifti(img, logger=None)[source]¶
Check the affine in nifti Image.
Sets affine with qform, if it exists and differs from sform. If qform does not exist, voxel sizes between header information and information in affine are compared. In case these do not match, the function returns False (otherwise True).
- Parameters:
- img
nib.Nifti1Image
,nib.Nifti2Image
Loaded nifti-image.
- logger
logging.Logger
,optional
Logger object or None (default) to log or print an info message to stdout (for None).
- img
- Returns:
bool
False, if voxel sizes in affine and header differ.
- FastSurferCNN.data_loader.conform.conform(img, order=1, vox_size=1.0, img_size=256, dtype=<class 'numpy.uint8'>, orientation='lia', threshold_1mm=None, rescale=255, vox_eps=0.0001, rot_eps=1e-06, **kwargs)[source]¶
Python version of mri_convert -c.
mri_convert -c by default turns image intensity values into UCHAR, reslices images to standard position, fills up slices to standard 256x256x256 format and enforces 1mm or minimum isotropic voxel sizes.
- Parameters:
- img
nib.analyze.SpatialImage
Loaded source image.
- order
int
, default=1 Interpolation order (0=nearest, 1=linear, 2=quadratic, 3=cubic).
- vox_size
float
, “min”,None
, default=1.0 Conform the image to this voxel size, a specific smaller voxel size (0-1, for high-res), or automatically determine the ‘minimum voxel size’ from the image (value ‘min’). This assumes the smallest of the three voxel sizes.
None
disables this criterion.- img_size
int
, “fov”, “auto”,None
, default=256 Conform the image to this image size, e.g. a specific smaller size (for example for high-res), or automatically determine the image size from the field of view (‘fov’ or ‘auto’, the former may yield non-cube-images).
None
disables this criterion.- dtype
type
,None
, default=np.unit8 The dtype to enforce in the image (default: UCHAR, as mri_convert -c).
None
disregards this criterion.- orientation“soft-<orientationcode>”, “<orientationcode>”, “native”,
None
, default=”lia” Which orientation of the data/affine to force, <orientationcode> is [rlapsi]{3}, ie.e. any of lia, ras, etc., None disables this criterion.
- threshold_1mm
float
,optional
The threshold above which the image is conformed to 1mm. Ignore, if
None
(default).- rescale
int
,float
,None
, default=255 Whether intensity values should be rescaled, it will either be the upper limit or None to ignore rescaling.
- vox_eps
float
, default=1e-4 The epsilon for the voxelsize check.
- rot_eps
float
, default=1e-6 The epsilon for the affine rotation check.
- img
- Returns:
nib.MGHImage
Conformed image.
- Other Parameters:
Notes
Unlike mri_convert -c, we first interpolate (float image), and then rescale to uchar. mri_convert is doing it the other way around. However, we compute the scale factor from the input to increase similarity.
- FastSurferCNN.data_loader.conform.conformed_vox_img_size(img, vox_size, img_size, threshold_1mm=None, vox_eps=0.0001, **kwargs)[source]¶
Extract the voxel size and the image size.
This function only needs the header (not the data).
- Parameters:
- img
nib.analyze.SpatialImage
Loaded source image.
- vox_size
float
, “min”,None
The voxel size parameter to use: either a voxel size as float, or the string “min” to automatically find a suitable voxel size (smallest per-dimension voxel size). None disregards the criterion (output also None).
- img_size
int
, “fov”, “auto”,None
The image size parameter: either an image size as int, the string “fov” to automatically derive a suitable image size (field of view), or “auto” like “fov” but largest size in every direction.
None
disregards the criterion, if vox_size is alsoNone
, else like “auto”.- threshold_1mm
float
,optional
The threshold for which image voxel size should be conformed to 1mm instead of conformed to the smallest voxel size (default or None: do not apply the threshold).
- vox_eps
float
, default=1e-4 The threshold to compare vox_sizes (differences below this are ignored).
- img
- Returns:
numpy.typing.NDArray
[float
],None
The determined voxel size to conform the image to (still in native orientation), shape: 3.
numpy.typing.NDArray
[int
],None
The size of the image adjusted to the conformed voxel size (still in native orientation), shape: 3.
- FastSurferCNN.data_loader.conform.crop_transform(image, offsets=None, target_shape=None, out=None, pad=0)[source]¶
Perform a crop transform of the last N dimensions on the image data. Cropping does not interpolate the image, but “just removes” border pixels/voxels. Negative offsets lead to padding.
- Parameters:
- image
np.ndarray
,torch.Tensor
Image of size […, D_1, D_2, …, D_N], where D_1, D_2, …, D_N are the N image dimensions.
- offsets
Sequence
[int
],optional
Offset of the cropped region for the last N dimensions (default: center crop with less crop/pad towards index 0).
- target_shape
Sequence
[int
],optional
If defined, target_shape specifies the target shape of the “cropped region”, else the crop will be centered cropping offset[dim] voxels on each side (then the shape is derived by subtracting 2x the dimension-specific offset). target_shape should have the same number of elements as offsets. May be implicitly defined by out.
- out
np.ndarray
,torch.Tensor
,optional
Array to store the cropped image in (optional), can be a view on image for memory-efficiency.
- pad
int
,str
, default=0/zero-pad Padding strategy to use when padding is required, if int, pad with that value.
- image
- Returns:
- out
np.ndarray
,torch.Tensor
The image (stack) cropped in the last N dimensions by offsets to the shape target_shape, or if target_shape is not given image.shape[i+2] - 2*offset[i].
- out
- Raises:
ValueError
If neither offsets nor target_shape nor out are defined.
ValueError
If out is not target_shape.
TypeError
If the type of image is not an np.ndarray or a torch.Tensor.
RuntimeError
If the dimensionality of image, out, offset or target_shape is invalid or inconsistent.
See also
numpy.pad
For additional information refer to numpy.pad function.
Notes
Either offsets, target_shape or out must be defined.
- FastSurferCNN.data_loader.conform.does_vox2vox_rot_require_interpolation(vox2vox, vox_eps=0.0001, rot_eps=1e-06)[source]¶
Check whether the affine requires resampling/interpolation or whether reordering is sufficient.
- Parameters:
- vox2vox
np.ndarray
The affine matrix.
- vox_eps
float
, default=1e-4 The epsilon for the voxelsize check.
- rot_eps
float
, default=1e-6 The epsilon for the affine rotation check.
- vox2vox
- Returns:
bool
Whether the vox2vox matrix requires resampling.
- FastSurferCNN.data_loader.conform.getscale(data, dst_min, dst_max, f_low=0.0, f_high=0.999)[source]¶
Get offset and scale of image intensities to robustly rescale to dst_min..dst_max.
Equivalent to how mri_convert conforms images.
- Parameters:
- data
np.ndarray
Image data (intensity values).
- dst_min
float
,int
Future minimal intensity value.
- dst_max
float
,int
Future maximal intensity value.
- f_low
float
, default=0.0 Robust cropping at low end (0.0=no cropping).
- f_high
float
, default=0.999 Robust cropping at higher end (0.999=crop one thousandth of highest intensity).
- data
- Returns:
- FastSurferCNN.data_loader.conform.is_conform(img, vox_size=1.0, img_size=256, dtype=<class 'numpy.uint8'>, orientation='lia', verbose=True, vox_eps=0.0001, eps=1e-06, threshold_1mm=0.0, **kwargs)[source]¶
Check if an image is already conformed or not.
Defaults: Dimensions: 256x256x256, Voxel size: 1x1x1, LIA orientation, and data type UCHAR.
- Parameters:
- img
nib.analyze.SpatialImage
Loaded source image.
- vox_size
float
, “min”,None
, default=1.0 Which voxel size to conform to. Can either be a float between 0.0 and 1.0, ‘min’ (to check, whether the image is conformed to the minimal voxels size, i.e. conforming to smaller, but isotropic voxel sizes for high-res), or None to disable the criteria.
- img_size
int
, “fov”, “auto”,None
, default=256 Conform the image to this image size, a specific smaller size (0-1, for high-res), or automatically determine the target size: “fov”: derive from the fov per dimension; “auto”: get the largest “fov” and use this 3 times.
- dtype
Type
,None
, default=numpy.uint8 Specifies the intended target dtype, if None the dtype check is disabled.
- orientation“soft-XXX”, “XXX”, “native”,
None
, default=”lia” Whether to force the conforming to a specific orientation specified by XXX, e.g. LIA.
- verbose
bool
, default=True If True, details of which conformance conditions are violated (if any) are displayed.
- vox_eps
float
, default=1e-4 Allowed deviation from zero for voxel size check.
- eps
float
, default=1e-6 Allowed deviation from zero for the orientation check. Small inaccuracies can occur through the inversion operation. Already conformed images are thus sometimes not correctly recognized. The epsilon accounts for these small shifts.
- threshold_1mm
float
,optional
Above this threshold the image is conformed to 1mm (default: None = ignore).
- img
- Returns:
- bool:
Whether the image is already conformed.
Notes
This function only needs the header (not the data).
- FastSurferCNN.data_loader.conform.is_orientation(affine, target_orientation='lia', soft=False, eps=1e-06)[source]¶
Checks whether the affine is LIA-oriented.
- Parameters:
- affine
np.ndarray
The affine to check.
- target_orientation
OrientationType
, default=”lia” The target orientation for which to check the affine for.
- soft
bool
, default=True Whether the orientation is required to be “exactly” (strict) LIA or just similar (soft) (i.e. it is roughly oriented as
target_orientation
).- eps
float
, default=1e-6 The threshold in strict mode.
- affine
- Returns:
bool
Whether the affine is LIA-oriented.
- FastSurferCNN.data_loader.conform.make_parser()[source]¶
Create an Argument parser for the conform script.
- Returns:
argparse.ArgumentParser
The parser object.
- FastSurferCNN.data_loader.conform.map_image(img, out_affine, out_shape, ras2ras=None, order=1, dtype=None, vox_eps=0.0001, rot_eps=1e-06)[source]¶
Map image to new voxel space (RAS orientation).
- Parameters:
- img
nib.analyze.SpatialImage
The src 3D image with data and affine set.
- out_affine
np.ndarray
Trg image affine.
- out_shape
tuple
[int
, …],np.ndarray
The target shape information.
- ras2ras
np.ndarray
,optional
An additional mapping that should be applied (default=id to just reslice).
- order
int
, default=1 Order of interpolation (0=nearest,1=linear,2=quadratic,3=cubic).
- dtype
Type
,None
, default=None Target dtype of the resulting image (especially relevant for reorientation, None=keep dtype of img).
- vox_eps
float
, default=1e-4 The epsilon for the voxelsize check.
- rot_eps
float
, default=1e-6 The epsilon for the affine rotation check.
- img
- Returns:
np.ndarray
Mapped image data array.
- FastSurferCNN.data_loader.conform.options_parse()[source]¶
Command line option parser.
- Returns:
options
Object holding options.
- FastSurferCNN.data_loader.conform.prepare_mgh_header(img, target_vox_size=None, target_img_size=None, orientation='native', vox_eps=0.0001, rot_eps=1e-06)[source]¶
Prepare the header with affine by target voxel size, target image size and criteria - initialized from img.
This implicitly prepares the affine, which can be computed by
return_value.get_affine()
.- Parameters:
- img
nibabel.analyze.SpatialImage
The image object to base the header on.
- target_vox_size
npt.NDArray
[float
],None
, default=None The target voxel size, importantly still in native orientation (reordering after).
- target_img_size
npt.NDArray
[int
],None
, default=None The target image size, importantly still in native orientation (reordering after).
- orientation“native”, “soft-<orientation>”, “<orientation>”, default=”native”
How the affine should look like.
- vox_eps
float
, default=1e-4 The epsilon for the voxelsize check.
- rot_eps
float
, default=1e-6 The epsilon for the affine rotation check.
- img
- Returns:
nibabel.freesurfer.mghformat.MGHHeader
The header object to the “conformed” image based on img and the other parameters.
- FastSurferCNN.data_loader.conform.rescale(data, dst_min, dst_max, f_low=0.0, f_high=0.999)[source]¶
Rescale image intensity values (0-255).
- Parameters:
- data
np.ndarray
Image data (intensity values).
- dst_min
float
Future minimal intensity value.
- dst_max
float
Future maximal intensity value.
- f_low
float
, default=0.0 Robust cropping at low end (0.0=no cropping).
- f_high
float
, default=0.999 Robust cropping at higher end (0.999=crop one thousandth of highest intensity).
- data
- Returns:
np.ndarray
Scaled image data.
- FastSurferCNN.data_loader.conform.scalecrop(data, dst_min, dst_max, src_min, scale)[source]¶
Crop the intensity ranges to specific min and max values.
- Parameters:
- data
np.ndarray
Image data (intensity values).
- dst_min
float
Future minimal intensity value.
- dst_max
float
Future maximal intensity value.
- src_min
float
Minimal value to consider from source (crops below).
- scale
float
Scale value by which source will be shifted.
- data
- Returns:
np.ndarray
Scaled image data.
- FastSurferCNN.data_loader.conform.to_dtype(dtype)[source]¶
Make sure to convert dtype to a numpy compatible dtype.
- Parameters:
- dtype
str
,np.dtype
Use this to determine the dtype.
- dtype
- Returns:
numpy.typing.DTypeLike
The dtype extracted.
- FastSurferCNN.data_loader.conform.to_target_orientation(image_data, source_affine, target_orientation)[source]¶
Reorder and flip image_data such that the data is in orientation. This will always be without interpolation.
- Parameters:
- image_data
np.ndarray
,torch.Tensor
The image data to reorder/flip.
- source_affine
npt.NDArray
[float
] The affine to detect the reorientation operations.
- target_orientation
str
The target orientation to reorient to.
- image_data
- Returns:
np.ndarray
,torch.Tensor
The data flipped and reordered so it is close to LIA (same type as image_data).
Callable
[[np.ndarray
],np.ndarray
],Callable
[[torch.Tensor
],torch.Tensor
]A function that flips and reorders the data back (returns same type as output).