Skip to content

Instantly share code, notes, and snippets.

@mrajchl
Created June 12, 2018 17:16
Show Gist options
  • Save mrajchl/ccbd5ed12eb68e0c1afc5da116af614a to your computer and use it in GitHub Desktop.
Save mrajchl/ccbd5ed12eb68e0c1afc5da116af614a to your computer and use it in GitHub Desktop.
Resampling an itk image object with SimpleITK
def resample_img(itk_image, out_spacing=[2.0, 2.0, 2.0], is_label=False):
# Resample images to 2mm spacing with SimpleITK
original_spacing = itk_image.GetSpacing()
original_size = itk_image.GetSize()
out_size = [
int(np.round(original_size[0] * (original_spacing[0] / out_spacing[0]))),
int(np.round(original_size[1] * (original_spacing[1] / out_spacing[1]))),
int(np.round(original_size[2] * (original_spacing[2] / out_spacing[2])))]
resample = sitk.ResampleImageFilter()
resample.SetOutputSpacing(out_spacing)
resample.SetSize(out_size)
resample.SetOutputDirection(itk_image.GetDirection())
resample.SetOutputOrigin(itk_image.GetOrigin())
resample.SetTransform(sitk.Transform())
resample.SetDefaultPixelValue(itk_image.GetPixelIDValue())
if is_label:
resample.SetInterpolator(sitk.sitkNearestNeighbor)
else:
resample.SetInterpolator(sitk.sitkBSpline)
return resample.Execute(itk_image)
# Assume to have some sitk image (itk_image) and label (itk_label)
resampled_sitk_img = resample_img(itk_image, out_spacing=[2.0, 2.0, 2.0], is_label=False)
resampled_sitk_lbl = resample_img(itk_label, out_spacing=[2.0, 2.0, 2.0], is_label=True)
@pangyuteng
Copy link

thanks for sharing!! been back here 3+ times now! 🚀

@inikishev
Copy link

inikishev commented May 31, 2024

is that different from

sitk.Resample(input, reference,)

?

@prowontheus
Copy link

thanks a lot!! i've been working on this over quite a few hours.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment