Skip to content

CropOrPad

CropOrPad

Bases: SpatialTransform

Modify the field of view by cropping or padding to match a target shape.

This transform modifies the affine matrix associated to the volume so that physical positions of the voxels are maintained.

Parameters:

Name Type Description Default
target_shape TypeTargetShape | None

Tuple \((W, H, D)\). If a single value \(N\) is provided, then \(W = H = D = N\). If None, the shape will be computed from the mask_name (and the labels, if labels is not None).

None
padding_mode str | float

Same as padding_mode in Pad.

0
mask_name str | None

If None, the centers of the input and output volumes will be the same. If a string is given, the output volume center will be the center of the bounding box of non-zero values in the image named mask_name.

None
labels Sequence[int] | None

If a label map is used to generate the mask, sequence of labels to consider.

None
only_crop bool

If True, padding will not be applied, only cropping will be done. only_crop and only_pad cannot both be True.

False
only_pad bool

If True, cropping will not be applied, only padding will be done. only_crop and only_pad cannot both be True.

False
location TypeLocation

Where to place the crop window when an axis of the input is larger than the target. 'center' (default) splits the cropped amount evenly between both sides; 'random' picks a uniformly random start position per axis using torch.randint, so seeding with torch.manual_seed makes the result reproducible. Padding is always centered, regardless of this parameter. location='random' cannot be combined with mask_name.

'center'
units TypeUnits

Coordinate system for target_shape. One of 'voxels' (default), 'mm', or 'cm'. When 'mm' or 'cm' is used, target_shape may contain floats representing the physical extent along each axis; the target is converted to voxels at transform time using the image spacing. When 'voxels' is used, all values must be positive integers. Use None for an axis to leave it unchanged (e.g., target_shape=(256, 256, None)).

'voxels'
**kwargs

See Transform for additional keyword arguments.

{}

Examples:

>>> import torchio as tio
>>> subject = tio.Subject(
...     chest_ct=tio.ScalarImage('subject_a_ct.nii.gz'),
...     heart_mask=tio.LabelMap('subject_a_heart_seg.nii.gz'),
... )
>>> subject.chest_ct.shape
torch.Size([1, 512, 512, 289])
>>> transform = tio.CropOrPad(
...     (120, 80, 180),
...     mask_name='heart_mask',
... )
>>> transformed = transform(subject)
>>> transformed.chest_ct.shape
torch.Size([1, 120, 80, 180])
>>> # Random crop window (useful for data augmentation):
>>> transform = tio.CropOrPad((96, 96, 96), location='random')
>>> # Target specified in physical units:
>>> transform = tio.CropOrPad((150.0, 200.0, 180.0), units='mm')
>>> # Keep the depth axis unchanged:
>>> transform = tio.CropOrPad((256, 256, None))
Warning

If target_shape is None, subjects in the dataset will probably have different shapes. This is probably fine if you are using patch-based training . If you are using full volumes for training and a batch size larger than one, an error will be raised by the DataLoader while trying to collate the batches.

_get_six_bounds_parameters(parameters) staticmethod

Compute bounds parameters for ITK filters.

Parameters:

Name Type Description Default
parameters ndarray

Tuple \((w, h, d)\) with the number of voxels to be cropped or padded.

required

Returns:

Type Description
TypeSixBounds

Tuple \((w_{ini}, w_{fin}, h_{ini}, h_{fin}, d_{ini}, d_{fin})\),

TypeSixBounds

where \(n_{ini} = \left \lceil \frac{n}{2} \right \rceil\) and

TypeSixBounds

\(n_{fin} = \left \lfloor \frac{n}{2} \right \rfloor\).

Examples:

>>> p = np.array((4, 0, 7))
>>> CropOrPad._get_six_bounds_parameters(p)
(2, 2, 0, 0, 4, 3)

plot

Source code
import torchio as tio
t1 = tio.datasets.Colin27().t1
crop_pad = tio.CropOrPad((512, 512, 32))
t1_pad_crop = crop_pad(t1)
subject = tio.Subject(t1=t1, crop_pad=t1_pad_crop)
subject.plot()