fepegar / torchio

Medical imaging toolkit for deep learning
https://torchio.org
Apache License 2.0
2.08k stars 239 forks source link

Resample an image by providing only the target affine #1174

Closed RomStriker closed 5 months ago

RomStriker commented 5 months ago

Hi,

I have the following ct volume

orientation: ('L', 'P', 'S')
spacing: (0.8203125, 0.8203125, 0.5)
spatial_shape: (512, 512, 679)
affine: [[ -0.8203125    0.           0.         222.17999268], 
[  0.          -0.8203125    0.          81.40000153], 
[  0.           0.           0.5        478.61999512], 
[  0.           0.           0.           1.        ]]

I want to resample to the following target affine

affine: [[ 0.5    0.           0.         1.], 
[  0.          0.5          0.          1.], 
[  0.           0.           0.5        1.], 
[  0.           0.           0.          1.]]

There is no option to do this with the current Resample function or I don't know how to do this. Please add this option or if there is a simple way to do this with the current function, please tell me how to do it.

RomStriker commented 5 months ago

The following code does this.

# Define resampling parameters
target_spacing = [0.5, 0.5, 0.5]  # isotropic 0.5mm
target_affine = np.array([
    [0.5, 0, 0, 0],
    [0, 0.5, 0, 0],
    [0, 0, 0.5, 0],
    [0, 0, 0, 1]
])

# Define the resampling transform
resample_ct = tio.Resample(target_spacing, image_interpolation='lanczos')

ct_volume = tio.ScalarImage(ct_file_path)

# Apply the transforms
resampled_ct_volume = resample_ct(ct_volume)
resampled_ct_volume.affine = target_affine