N4BiasFieldCorrection -- folders and subfolders

Hello,
Hopefully you can help me with this…

I’m want to run ants N4BiasFieldCorrection command from the terminal to correct the bias of lots of images, the thing is that I want it to look through folders and subfolders to find the desired image and correct it, naming the output same as the input image plus N4 (or something that allows me identify the bias-corrected version)

For example, my directories look like this:
`

  • T1
    – 10_S_10
    ------ 10_S_10.json
    ------ 10_S_10.nii
    ------ 10_S_10_crop.nii
    – 10_S_14
    ------ 10_S_14.json
    ------ 10_S_14.nii
    ------ 10_S_14_crop.nii

And I want to run N4BiasFieldCorrection, look into each subfolder of T1 and correct the xx_S_xx_crop.nii image, and the output to be named xx_S_xx_crop_N4.nii

Is this possible?

I tried:
N4BiasFieldCorrection -i */* -o ./n4.nii

but this code just corrects one image (I suppose the last one it looks at) and the output name of course is just n4.nii and is located in the mother folder and not the subfolder from where it got the original image.

I hope I was clear, thank you.

Al.

  1. cd in to T1
  2. for file in */*S*crop.nii; do outpath=${file%.nii}_n4.nii; N4BiasFieldCorrection -i $file -o $outpath; done
    This loops over all S crop images in each folder, sets the out name as the same but ending with _n4.nii, then runs the bias correction.

Hope this works for you!

Best,
Steven

Thank you Steven, it works!

1 Like