Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Resize transform #642

Merged
merged 2 commits into from
Sep 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/source/transforms/preprocessing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ Spatial
:show-inheritance:


:class:`Resize`
~~~~~~~~~~~~~~~

.. autoclass:: Resize
:show-inheritance:


:class:`EnsureShapeMultiple`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand Down
31 changes: 31 additions & 0 deletions tests/transforms/preprocessing/test_resize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import torch
import numpy as np
import torchio as tio
from ...utils import TorchioTestCase


class TestResize(TorchioTestCase):
"""Tests for `Resize`."""
def test_one_dim(self):
target_shape = 5
transform = tio.Resize(target_shape)
transformed = transform(self.sample_subject)
for image in transformed.get_images(intensity_only=False):
self.assertEqual(image.spatial_shape, 3 * (target_shape,))

def test_all_dims(self):
target_shape = 11, 6, 7
transform = tio.Resize(target_shape)
transformed = transform(self.sample_subject)
for image in transformed.get_images(intensity_only=False):
self.assertEqual(image.spatial_shape, target_shape)

def test_fix_shape(self):
# We use values that are known to need cropping
tensor = torch.rand(1, 8, 180, 320)
affine = np.diag((5, 1, 1, 1))
im = tio.ScalarImage(tensor=tensor, affine=affine)
target = 12
with self.assertWarns(UserWarning):
result = tio.Resize(target)(im)
self.assertEqual(result.spatial_shape, 3 * (target,))
4 changes: 3 additions & 1 deletion tests/transforms/test_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,18 @@ def get_transform(self, channels, is_3d=True, labels=True):
disp = 1 if is_3d else (1, 1, 0.01)
elastic = tio.RandomElasticDeformation(max_displacement=disp)
cp_args = (9, 21, 30) if is_3d else (21, 30, 1)
resize_args = (10, 20, 30) if is_3d else (10, 20, 1)
flip_axes = axes_downsample = (0, 1, 2) if is_3d else (0, 1)
swap_patch = (2, 3, 4) if is_3d else (3, 4, 1)
pad_args = (1, 2, 3, 0, 5, 6) if is_3d else (0, 0, 3, 0, 5, 6)
crop_args = (3, 2, 8, 0, 1, 4) if is_3d else (0, 0, 8, 0, 1, 4)
remapping = {1: 2, 2: 1, 3: 20, 4: 25}
transforms = [
tio.CropOrPad(cp_args),
tio.EnsureShapeMultiple(2, method='crop'),
tio.Resize(resize_args),
tio.ToCanonical(),
tio.RandomAnisotropy(downsampling=(1.75, 2), axes=axes_downsample),
tio.EnsureShapeMultiple(2, method='crop'),
tio.CopyAffine(channels[0]),
tio.Resample((1, 1.1, 1.25)),
tio.RandomFlip(axes=flip_axes, flip_probability=1),
Expand Down
2 changes: 2 additions & 0 deletions torchio/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
# Preprocessing
from .preprocessing import Pad
from .preprocessing import Crop
from .preprocessing import Resize
from .preprocessing import Resample
from .preprocessing import CropOrPad
from .preprocessing import CopyAffine
Expand Down Expand Up @@ -82,6 +83,7 @@
'LabelsToImage',
'Pad',
'Crop',
'Resize',
'Resample',
'ToCanonical',
'ZNormalization',
Expand Down
2 changes: 2 additions & 0 deletions torchio/transforms/preprocessing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from .spatial.pad import Pad
from .spatial.crop import Crop
from .spatial.resize import Resize
from .spatial.resample import Resample
from .spatial.crop_or_pad import CropOrPad
from .spatial.to_canonical import ToCanonical
Expand All @@ -23,6 +24,7 @@
__all__ = [
'Pad',
'Crop',
'Resize',
'Resample',
'ToCanonical',
'CropOrPad',
Expand Down
2 changes: 1 addition & 1 deletion torchio/transforms/preprocessing/spatial/crop_or_pad.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


class CropOrPad(BoundsTransform):
"""Crop and/or pad an image to a target shape.
"""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.
Expand Down
58 changes: 58 additions & 0 deletions torchio/transforms/preprocessing/spatial/resize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import warnings

import numpy as np

from ....utils import to_tuple
from ....data.subject import Subject
from ....typing import TypeSpatialShape
from ... import SpatialTransform
from .resample import Resample
from .crop_or_pad import CropOrPad


class Resize(SpatialTransform):
"""Resample images so the output shape matches the given target shape.

The field of view remains the same.

Args:
target_shape: Tuple :math:`(W, H, D)`. If a single value :math:`N` is
provided, then :math:`W = H = D = N`.
image_interpolation: See :ref:`Interpolation`.
"""
def __init__(
self,
target_shape: TypeSpatialShape,
image_interpolation: str = 'linear',
**kwargs
):
super().__init__(**kwargs)
self.target_shape = np.asarray(to_tuple(target_shape, length=3))
self.image_interpolation = self.parse_interpolation(
image_interpolation)
self.args_names = (
'target_shape',
'image_interpolation',
)

def apply_transform(self, subject: Subject) -> Subject:
shape_in = np.asarray(subject.spatial_shape)
shape_out = self.target_shape
spacing_in = np.asarray(subject.spacing)
spacing_out = shape_in / shape_out * spacing_in
resample = Resample(
spacing_out,
image_interpolation=self.image_interpolation,
)
resampled = resample(subject)
# Sometimes, the output shape is one voxel too large
# Probably because Resample uses np.ceil to compute the shape
if not resampled.spatial_shape == tuple(shape_out):
message = (
f'Output shape {resampled.spatial_shape}'
f' != target shape {tuple(shape_out)}. Fixing with CropOrPad'
)
warnings.warn(message)
crop_pad = CropOrPad(shape_out)
resampled = crop_pad(resampled)
return resampled