Sta Hamid
Sta Hamid

Reputation: 1

SimpleITK : How to change the shape of the image without changing the pixel spacing?

I am trying to change the shape of my 3d array from (66, 47, 21) to \[64, 64, 16\] with the following axis being ( X, Y , Z) . My 3d array came from CT scan , so the Z axis correspond to the number of slice in my image while X and Y are the 2d dimension

What I have currently done is simply :

image = sitk.ReadImage(filename)

image_array = sitk.GetArrayFromImage(image)

median_shape = \[64, 64, 16\]

resized_image = sitk.Resample(image, median_shape)

resized_array = sitk.GetArrayFromImage(resized_image)

However , apparently it's not how I am suppose to do, because i resample, and so I change my pixel spacing. I just want to find a way to change the shape of my image to median_shape, without changing anything, and without loosing information.

Upvotes: 0

Views: 1572

Answers (2)

Julius
Julius

Reputation: 11

It seems like you want to perform some type of cropping (where the shape is smaller) or padding (where the shape is larger). There are several methods in SimpleITK to achieve this: PasteImageFilter and CropImageFilter

In MONAI (a python library for AI applications on medical imaging) there is a very convenient function for this as well: ResizeWithPadOrCrop

So if you would define a pipeline to read the image, "resize" it, and write it, that should do the trick:

from monai import transforms
import glob
import os
img_glob_expr = "/path/to/imges/*.nii.gz"
output_dir = "./test"
os.makedirs(output_dir, exist_ok=True)
tfms = transforms.Compose([
    transforms.LoadImage(image_only=True, ensure_channel_first=True), 
    transforms.ResizeWithPadOrCrop(spatial_size=(64, 64, 16), mode="minimum"), 
    transforms.SaveImage(output_dir=output_dir, resample=False, output_ext="nii.gz", separate_folder=False)
])
imgs = glob.glob(img_glob_expr)
tfms(imgs)

Note: make sure you have Nibabel installed (pip install monai[nibabel]) before running this, because it will need that library to read and write the images.

Upvotes: 0

Dave Chen
Dave Chen

Reputation: 2085

SimpleITK considers an image to be an object in 3d space. So resampling that image with a different Z resolution (21 -> 16), is going to require a different Z spacing to compensate.

If you don't really care about the 3d nature of an image you can always over-write the Z spacing with the SetSpacing method. You would be losing the proper spacing, though.

Upvotes: 0

Related Questions