Unable to keep image origin and orientation with Python ITK

(Paulo Freire) #1

Hello, everyone.

I’m trying to perform a very simple operation on an image using Python. I just want to read it as a NumPy array, change some values and then write it back as a new image. The problem is: when I write it back, I lose the original origin and orientation (that’s a mouthful). Is there any way I can keep them? The code is as simple as this:

import numpy as np
import itk

input_filename = "mask.nii"
input_img = itk.imread(input_filename)

np_copy = itk.GetArrayFromImage(input_img)
np_copy[np_copy != 0] = 255

itk_nb_img = itk.GetImageFromArray(np_copy)
itk.imwrite(itk_nb_img, "output_mask.nii")

I’ve uploaded a working example to make it easier to understand. Do any of you know how to deal with this? Thanks in advance!

itk_python.zip (4.6 KB)

1 Like
(Dženan Zukić) #2

I think the function you need it itk.GetArrayViewFromImage. That will modify ITK’s version of the image. Then just write that - all metadata will go along.

(Paulo Freire) #3

Thank you for your reply @dzenanz. Unfortunately, that didn’t work. I even tried replacing itk.GetImageFromArray with itk.GetImageViewFromArray, but that didn’t work either.

(Dženan Zukić) #4

Perhaps I was not clear enough. Try this:

import numpy as np
import itk

input_filename = "mask.nii"
input_img = itk.imread(input_filename)

np_ref = itk.GetArrayViewFromImage(input_img)
np_ref[np_ref != 0] = 255

itk.imwrite(input_img , "output_mask.nii")
3 Likes
(Paulo Freire) #5

As usual, spot on! Thank you. Sorry I didn’t get that the first time.