Reputation: 2236
I want to write the image [that I have loaded into array] after changing the values of array into a SimpleITK Image. How can I set the spacing and origin?
[res_file_dir
is the path to the nii.gz
file]
segmentation_result=sitk.ReadImage(res_file_dir,sitk.sitkUInt8) #segmentation_result.GetSpacing() (0.3645833432674408, 0.3645833432674408, 0.699999988079071)
seg=sitk.GetArrayFromImage(segmentation_result) #shape (105, 242, 176)
seg[seg!=obj_label]=0
#segmentation=sitk.Image(segmentation_result.GetSize(),sitk.sitkUInt8)
numpyOrigin = np.array(list(reversed(segmentation_result.GetOrigin())))
numpySpacing = np.array(list(reversed(segmentation_result.GetSpacing())))
segmentation = sitk.GetImageFromArray(seg, sitk.sitkVectorUInt8).SetSpacing(numpySpacing)
once I check the spacing of new image, it shows the following:
segmentation.GetSpacing()
*** AttributeError: 'NoneType' object has no attribute 'GetSpacing'
Upvotes: 1
Views: 3417
Reputation: 2085
There are two problems with your last line. The first problem is that segmentation
is getting set to the result of the call to SetSpacing
, which has a return type of void
.
The second problem is your second parameter to sitk.GetImageFromArray
. It is a boolean for the named parameter isVector
. In your case you want it to be False
, which is the default value.
In your code, you are passing sitk.sitkVectorUInt8
, which turns out to be an integer of value 13, to isVector
. So isVector
is getting True
, the opposite of what you really want. With True
you are getting a 2-d image with each pixel being a vector of length 176.
To double check, I would print out the results of the call to sitk.GetImageFromArray
before doing the call to SetSpacing
.
So here's what your code should be:
segmentation = sitk.GetImageFromArray(seg, isVector=False)
segmentation.SetSpacing(numpySpacing)
Note that if you want to mask out values in you image, you can do it in SimpleITK without converting to numpy and back. Here's how you could do that:
# create a binary mask image of
seg = (segmentation_result==obj_label)
# create an image with pixel values of obj_label
segmentation = seg * obj_label
Upvotes: 2