sanitize.py 776 B

12345678910111213141516171819202122232425
  1. import nibabel as nb
  2. from pathlib import Path
  3. def sanitize(input_fname):
  4. im = nb.as_closest_canonical(nb.load(str(input_fname)))
  5. hdr = im.header.copy()
  6. dtype = 'int16'
  7. if str(input_fname).endswith('_mask.nii.gz') or str(input_fname).endswith('_dseg.nii.gz'):
  8. dtype = 'uint8'
  9. hdr.set_data_dtype(dtype)
  10. nii = nb.Nifti1Image(im.get_data().astype(dtype), im.affine, hdr)
  11. sform = nii.header.get_sform()
  12. nii.header.set_sform(sform, 4)
  13. nii.header.set_qform(sform, 4)
  14. nii.header.set_slope_inter(slope=1.0, inter=0.0)
  15. nii.header.set_xyzt_units(xyz='mm')
  16. # print(nii.shape)
  17. # print(nii.affine)
  18. nii.to_filename(str(input_fname))
  19. for f in Path().glob('tpl-*.nii.gz'):
  20. print('Sanitizing file %s' % f)
  21. sanitize(f)