 # Convert from 3D numpy array to simple ITK

Hello,
I have a NumPy array (`image_array`) with the size of 400 * 100 * 800 (`spacing`: [1, 4, 0.1]).

I used the below code to convert it to `sitk` image for registration:

``````image = sitk.GetImageFromArray(image_array)
image.SetOrigin((0, 0, 0))
image.SetSpacing(spacing)
``````

When I read the spacing from `sitk` image using `image.GetSpacing()` it is ok but the size (`image.GetSize()`) is different: 800 * 100 * 400

Do I need to reshape the NumPy array before importing it to the `SITK` and then just use the `sitk.GetArrayFromImage` to convert it to the NumPy array and have the same `Spacing` and `Size`?

I tried to inspect the image in`SITK` using `FIJI` but it didn’t show the spacing correctly (all are equal to one)

Thank you

Hello @Moha_data,

Welcome to SimpleITK!

SimpleITK and numpy use a different indexing order. SimpleITK uses x-y-z. Numpy uses z-y-x. The `GetImageFromArray` method accounts for this. Thus when you inspect the image size afterwards the reported order is x-y-z which matches your original numpy size. With respect to `SetSpacing`, it should also follow the x-y-z order. For additional details see this jupyter notebook.

Fiji is not aware of variable image spacing, assumes isotropic pixels/voxels ([1,1,1]). Other programs that do account for image spacing can be used via the `Show` method (e.g. ITK-SNAP, 3D Slicer). See this jupyter notebook for details.

1 Like

Thanks @zivy for the comment.
So, assuming we have an `Image_array` with corresponding `spacing`, we can use the below code to convert it to `sitk image`:

`image_sitk = sitk.GetImageFromArray(image_array)`
` image_sitk.SetOrigin((0, 0, 0))`
`spacing.reverse()`
`image_sitk.SetSpacing(spacing)`

and after any modification in sitk, we can use:

modified_image = sitk.GetArrayFromImage(modified_image_sitk)`

and `spacing.reverse()` to reorder the `spacing` to be used in NumPy.

Hello @Moha_data,

Yes (assuming `spacing` is a list associated with the numpy data so `spacing.reverse()` changes it in place).

1 Like