# N4 Bias Field Correction in sitk

**URL:** <https://discourse.slicer.org/t/n4-bias-field-correction-in-sitk/12837>\
**Category:** Support\
**Created:** [August 3, 2020, 7:03pm UTC](https://discourse.slicer.org/t/n4-bias-field-correction-in-sitk/12837 "2020-08-03T19:03:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![xlucox](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/xlucox/32/6381_2.png) [@xlucox](https://discourse.slicer.org/u/xlucox)\
**Post date:** [August 3, 2020, 7:03pm UTC](https://discourse.slicer.org/t/n4-bias-field-correction-in-sitk/12837/1 "2020-08-03T19:03:28Z")

</div>

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()  
corrector.SetNumberOfControlPoints([4,4,4])  
corrector.SetConvergenceThreshold(0.0001)  
corrector.SetMaximumNumberOfIterations([50,40,30])  
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.

---

<div class="post-metadata">

**Author:** ![lassoan](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/lassoan/32/13_2.png) [@lassoan](https://discourse.slicer.org/u/lassoan)\
**Post date:** [August 3, 2020, 7:18pm UTC](https://discourse.slicer.org/t/n4-bias-field-correction-in-sitk/12837/2 "2020-08-03T19:18:31Z")

</div>

You can find the Slicer module’s source code here: [https://github.com/Slicer/Slicer/blob/master/Modules/CLI/N4ITKBiasFieldCorrection/N4ITKBiasFieldCorrection.cxx](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](https://www.slicer.org/wiki/Documentation/Nightly/Developers/Python_scripting#Running_a_CLI_from_Python).
