In Python, how to convert between SimpleITK and ITK Images?

The safe way to do this is through numpy as the compiled versions of ITK and SimpleITK are not necessarily compatible. Also, be aware that the supported pixel types may differ, so some image types supported by SimpleITK are not supported by ITK and vice versa.

Below is a code snippet that does what you want (written so it is agnostic of the image dimensions):

import SimpleITK as sitk
import itk
import numpy as np


image_dimension = 2
index = [15]*image_dimension

test_arr = np.ones([32]*image_dimension, dtype=np.int16)
test_arr[index] = 999

# Create a simpleitk image from the numpy array
sitk_image = sitk.GetImageFromArray(test_arr)
print('SimpleITK image value at {0}: {1}'.format(index, sitk_image[index]))

# Create an itk image from the simpleitk image via numpy array
itk_image = itk.GetImageFromArray(sitk.GetArrayFromImage(sitk_image), is_vector = sitk_image.GetNumberOfComponentsPerPixel()>1)
itk_image.SetOrigin(sitk_image.GetOrigin())
itk_image.SetSpacing(sitk_image.GetSpacing())   
itk_image.SetDirection(itk.GetMatrixFromArray(np.reshape(np.array(sitk_image.GetDirection()), [image_dimension]*2)))
print('ITK image value at {0}: {1}'.format(index, itk_image.GetPixel(index)))

# Change the pixel value
itk_image.SetPixel(index, 888)

# Back to a simpleitk image from the itk image
new_sitk_image = sitk.GetImageFromArray(itk.GetArrayFromImage(itk_image), isVector=itk_image.GetNumberOfComponentsPerPixel()>1)
new_sitk_image.SetOrigin(tuple(itk_image.GetOrigin()))
new_sitk_image.SetSpacing(tuple(itk_image.GetSpacing()))
new_sitk_image.SetDirection(itk.GetArrayFromMatrix(itk_image.GetDirection()).flatten()) 
print('New SimpleITK image value at {0}: {1}'.format(index, new_sitk_image[index]))

3 Likes