Python ITK convert mha image to png image


I am using itk with python for the first time. I am trying to convert a mha image (2d) to a png image. To be perfectly honest I am not sure how to use pixel types, I hope you can point me into the right direction
My code looks like this:

        pixelType = itk.F
        imageType = itk.Image[pixelType, 2]
        writerType = itk.ImageFileWriter[imageType]

        reader = itk.ImageFileReader.New(FileName=mha_file)
        input_image_type = itk.template(reader.GetOutput())

        image_filter = itk.CastImageFilter[input_image_type,      itk.Image[itk.UC,3]].New(reader.GetOutput())

The error I get is quite long:

 `KeyError: ((<itkTemplate itk::Image>, (<itkCType float>, 3)), <class 'itkImagePython.itkImageUC3'>)

     itkTemplate.TemplateTypeError: itk.CastImageFilter is not    wrapped for input type `tuple, itk.Image[itk.UC,3]`.

Can you start from this example from the documentation? This easier syntax is available with ITKv5. In the example you might need to replace median by cast, or you might not need any filter - just read and write the image with different file names.

ITK Python can convert image images without type specification with:

import itk
image = itk.imread('image.mha')
itk.imwrite(image, 'image.png')
1 Like