Python - Write a three dimensional image from 3D a

2019-08-04 11:28发布

问题:

I'm trying to obtain an image from 3D array and convert it to TIF 3D. I'm using simple ITK but it doesn't work. I obtain this error message : 'in method 'WriteImage', argument 1 of type 'itk::simple::Image const &'

Here's my code:

import numpy as np
import SimpleITK as sitk

test = np.ones((20,20,20))

sitk.WriteImage(test,'test.tif')

-------------------- EDIT LATER ----------------------------

I try by working with "GetImageFromArray" it seems work as i keep the same size and finally i try to save but an error :

"itk::ERROR: TIFFImageIO(0x43e8740): TIFF supports unsigned/signed char, unsigned/signed short, and float"

Here's my code:

test2 = sitk.GetImageFromArray(test)
test2.GetSize()
(20, 20, 20)
sitk.WriteImage(test2, "prout.tif")

回答1:

It looks like your sitk::Image pixel type is not supported by the TIFF ImageIO. You need to cast to one of the pixel types listed, i.e. sitk.UInt8, sitk.UInt16, sitk.Float32.

You can inspect what your current pixel type is with something like:

print("pixel id: {0} ({2})".format(test2.GetPixelID(), test2.GetPixelIDTypeAsString())

Then you can convert the pixel type of your image:

test2 = sitk.Cast(test2, sitk.Float32)

or

test2 = sitk.Cast(test2, sitk.UInt16)

etc...