Last active
          March 3, 2022 09:58 
        
      - 
      
 - 
        
Save nanaHa1003/6719d60c9d220988a73c2c29d7b6d12f to your computer and use it in GitHub Desktop.  
    How to convert a Nifti image affine.
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import os | |
| from argparse import ArgumentParser | |
| import numpy as np | |
| import nibabel as nib | |
| import nibabel.orientations as ornts | |
| def main(args): | |
| image = nib.load(args.input) | |
| src_ornt = ornts.io_orientation(image.affine) | |
| dst_ornt = ornts.axcodes2ornt(args.axcodes) | |
| # Get orientation transform | |
| ornt_t = ornts.ornt_transform(src_ornt, dst_ornt) | |
| # Apply orientation transform on image data | |
| data = ornts.apply_orientation(image.dataobj, ornt_t) | |
| # Apply orientation transform on image affine | |
| inv_ornt_t = ornts.ornt_transform(dst_ornt, src_ornt) # may be unnecessary | |
| affine_t = ornts.inv_ornt_aff(inv_ornt_t, image.shape) | |
| affine = np.matmul(image.affine, affine_t) | |
| output = nib.Nifti1Image(data, affine) | |
| nib.save(output, args.output) | |
| if __name__ == "__main__": | |
| parser = ArgumentParser() | |
| parser.add_argument("--input", "-i", type=str, help="Input Nifti image for affine transform") | |
| parser.add_argument("--output", "-o", type=str, help="Path to save transformed Nifti image") | |
| parser.add_argument("--axcodes", "-a", type=str, help="Target orientation axis codes") | |
| args = parser.parse_args() | |
| main(args) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment