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

**URL:** <https://discourse.itk.org/t/in-python-how-to-convert-between-simpleitk-and-itk-images/1922>\
**Category:** Beginner Questions\
**Created:** [May 30, 2019, 3:41pm UTC](https://discourse.itk.org/t/in-python-how-to-convert-between-simpleitk-and-itk-images/1922 "2019-05-30T15:41:57Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![zivy](https://discourse.itk.org/user_avatar/discourse.itk.org/zivy/32/1726_2.png) [@zivy](https://discourse.itk.org/u/zivy)\
**Post date:** [May 30, 2019, 8:24pm UTC](https://discourse.itk.org/t/in-python-how-to-convert-between-simpleitk-and-itk-images/1922/2 "2019-05-30T20:24:10Z")

</div>

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):

```auto
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]))

```

---

_[View the full topic](https://discourse.itk.org/t/in-python-how-to-convert-between-simpleitk-and-itk-images/1922)._
