Search code examples
pythonarraysnumpyscipyitk

Python: Using a 3 dimensional numpy array in ITK


I have the following problem. I have a 3D numpy array full of floats called scoreMatrix. Now i want to use Itk filters on it like Thresholding filter. Is that generally possible? I tried to convert the numpy array to an itk image and then process it. Is there another way to do it?:

    scoreMatrixItk = itk.GetImageViewFromArray(scoreMatrix)

    itk.imwrite(scoreMatrixItk, "scoreMatrixItk")
    PixelType = itk.UC
    Dimension = 3

    ImageType = itk.Image[PixelType, Dimension]

    reader = itk.ImageFileReader[ImageType].New()
    reader.SetFileName('scoreMatrixItk')

    thresholdFilter = itk.OtsuMultipleThresholdsImageFilter[
            ImageType,
            ImageType].New()
    thresholdFilter.SetInput(reader.GetOutput())

    thresholdFilter.SetNumberOfHistogramBins(3)
    thresholdFilter.SetNumberOfThresholds(2)
    thresholdFilter.SetLabelOffset(4)

    rescaler = itk.RescaleIntensityImageFilter[ImageType, ImageType].New()
    rescaler.SetInput(thresholdFilter.GetOutput())
    rescaler.SetOutputMinimum(0)
    rescaler.SetOutputMaximum(255)

    writer = itk.ImageFileWriter[ImageType].New()
    writer.SetFileName('outputImage.tiff')
    writer.SetInput(rescaler.GetOutput())

    writer.Update()

But i get the error: KeyError: "itkTemplate : No template [ >] for the itk::ImageFileWriter class"

Do i have to pay attention of some things?


Solution

  • A short blog post about itk<->Numpy conversions. You should combine it with information from this one. I think that writing the scoreMatrixItk into a file is unnecessary. You should be able to do thresholdFilter.SetInput(scoreMatrixItk), after perhaps changing the type used in creation of thresholdFilter. Since you are using unsigned char, you don't need rescaler unless you want to increase intensity range from e.g. 0-50 into 0-255. I don't know why you currently get an error.