N4 Bias Field Correction in sitk

Hi everyone,

I’ve been trying to automatize the application of N4 Bias Field Correction in python. I though it would be a good idea to use sitk. The fact is when I configure the class N4BiasFieldCorrectionImageFilter with the same parameters as it is programmed by default in the Slicer module “N4ITK MRI Bias correction”, the image output lose quality. Does anyone know how to get the same result in the same amount of time using python?

Here is the code I’m using:

shrinkFactor = 4
inputImage = sitk.ReadImage(sys.argv[1])
maskImage = sitk.OtsuThreshold(inputImage, 0, 1, 200)
inputImage = sitk.Shrink(inputImage, [shrinkFactor] * inputImage.GetDimension())
maskImage = sitk.Shrink(maskImage,[shrinkFactor] * inputImage.GetDimension())

inputImage = sitk.Cast(inputImage, sitk.sitkFloat32)
corrector = sitk.N4BiasFieldCorrectionImageFilter()
inputImage = sitk.Cast(inputImage, sitk.sitkFloat32)
output = corrector.Execute(inputImage, maskImage)
sitk.WriteImage(output, name)

I know the shrinkFactor is making the quality poorer but if I turn it 1, then the algorithm takes to much time running.

You can find the Slicer module’s source code here: https://github.com/Slicer/Slicer/blob/master/Modules/CLI/N4ITKBiasFieldCorrection/N4ITKBiasFieldCorrection.cxx

Based on this, you can reimplement the module in pure Python and SimpleITK, but you can save some time by using the Slicer CLI module from Python as described here.