How to use PyImageFilter

Is there a working example of how to use the itk.PyImageFilter class? It seems like the key is using the SetPyGenerateData method to set a python function to do the work. I have the below toy example working, but I can’t figure out how to access the input data or set the output data within the passed python function. It does appear to get called upon “Update” however.

import itk
import sys

def myFunc():

    print("myFunc is running")
    # Fun stuff goes here?
    return(None)

img = itk.imread("in.nii.gz")
InputImageType = type(img)
OutputPixelType = itk.ctype("unsigned char")
OutputImageType = itk.Image[OutputPixelType, img.GetImageDimension()]

# PyImageFilter only wrapped for UC (2D,3D) and US (2D,3D)
caster = itk.CastImageFilter[InputImageType, OutputImageType].New(img)

filter = itk.PyImageFilter[OutputImageType, OutputImageType].New()
filter.SetPyGenerateData( myFunc )
filter.SetInput( caster.GetOutput() )
filter.Update()
outImg = filter.GetOutput()

print(type(outImg))
print(outImg)
print(itk.size(outImg))

I could not find it. Considering that class was contributed more than 10 years ago, I am not sure that an example exists, much less works. @matt.mccormick @Tom_Birdsong @brad-t-moore or @blowekamp might know more.

In some cases, a closure could possibly be used, but that is non-optimal.

Please take a look at this patch, which passes the filter instance to the callable:

Then, we can do:

def my_func(py_image_filter):
    print('the fun has started')
    input = py_image_filter.GetInput()

    output = py_image_filter.GetOutput()
    # process input, populate output
1 Like