Resample only one axis#

In this example, we create a custom preprocessing transfom that changes the image spacing across one axis only.

Inspired by this discussion.

original (sagittal), original (coronal), original (axial), transformed (sagittal), transformed (coronal), transformed (axial)
Downloading https://github.com/fepegar/torchio-data/raw/main/data/fernando/t1.nii.gz to /home/user/.cache/torchio/fpg/t1.nii.gz

0it [00:00, ?it/s]
  0%|          | 0/10860389 [00:00<?, ?it/s]
  4%|▍         | 450560/10860389 [00:01<00:02, 4484849.72it/s]
 10%|█         | 1097728/10860389 [00:01<00:01, 5647567.53it/s]
 16%|█▋        | 1785856/10860389 [00:01<00:01, 6201000.60it/s]
 23%|██▎       | 2498560/10860389 [00:01<00:01, 6549957.02it/s]
 29%|██▉       | 3145728/10860389 [00:01<00:01, 6372007.85it/s]
 36%|███▌      | 3899392/10860389 [00:01<00:01, 6665502.98it/s]
 43%|████▎     | 4636672/10860389 [00:01<00:00, 6891314.02it/s]
 49%|████▉     | 5308416/10860389 [00:01<00:00, 6744821.62it/s]
 55%|█████▍    | 5971968/10860389 [00:01<00:00, 6678820.86it/s]
 62%|██████▏   | 6725632/10860389 [00:01<00:00, 6863579.61it/s]
 68%|██████▊   | 7413760/10860389 [00:02<00:00, 6849150.40it/s]
 75%|███████▍  | 8118272/10860389 [00:02<00:00, 6895047.24it/s]
 82%|████████▏ | 8863744/10860389 [00:02<00:00, 7051335.45it/s]
 88%|████████▊ | 9568256/10860389 [00:02<00:00, 6926182.93it/s]
 95%|█████████▍| 10297344/10860389 [00:02<00:00, 7022097.30it/s]
10862592it [00:02, 4233264.51it/s]
Downloading https://github.com/fepegar/torchio-data/raw/main/data/fernando/t1_seg_gif.nii.gz to /home/user/.cache/torchio/fpg/t1_seg_gif.nii.gz

0it [00:00, ?it/s]
  0%|          | 0/544126 [00:01<?, ?it/s]
 66%|██████▌   | 360448/544126 [00:01<00:00, 3586543.45it/s]
548864it [00:01, 479093.35it/s]
Downloading https://github.com/fepegar/torchio-data/raw/main/data/fernando/t1_to_mni.tfm to /home/user/.cache/torchio/fpg/t1_to_mni.tfm

0it [00:00, ?it/s]
  0%|          | 0/329 [00:00<?, ?it/s]
8192it [00:00, 8997.95it/s]
Downloading https://github.com/fepegar/torchio-data/raw/main/data/fernando/t1_to_mni_affine.h5 to /home/user/.cache/torchio/fpg/t1_to_mni_affine.h5

0it [00:00, ?it/s]
  0%|          | 0/8392 [00:01<?, ?it/s]
16384it [00:01, 14928.70it/s]

import torch
import torchio as tio


class ResampleZ:
    def __init__(self, spacing_z):
        self.spacing_z = spacing_z

    def __call__(self, subject):
        # We'll assume all images in the subject have the same spacing
        sx, sy, _ = subject.spacing
        resample = tio.Resample((sx, sy, self.spacing_z))
        resampled = resample(subject)
        return resampled


torch.manual_seed(42)
image = tio.datasets.FPG().t1
transforms = tio.ToCanonical(), ResampleZ(spacing_z=7)
transform = tio.Compose(transforms)
transformed = transform(image)
subject = tio.Subject(original=image, transformed=transformed)
subject.plot()

Total running time of the script: (0 minutes 6.961 seconds)

Gallery generated by Sphinx-Gallery