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 int | TypeTripletInt | 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
**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])
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()