python converts batch nii files into png images

  • 2021-07-22 10:44:44
  • OfStack

Converting a single nii file to an png image was described earlier:

https://www.ofstack.com/article/165693.htm

Converting multiple nii files (saved in one folder) into png images is described here. And the image individual folder name is the same as the nii name.


import numpy as np
import os    # Traverse folders 
import nibabel as nib #nii Format 1 This bag will be used in general 
import imageio   # Convert to an image 
 
def nii_to_image(niifile):
 filenames = os.listdir(filepath) # Read nii Folder 
 slice_trans = []
 
 for f in filenames:
  # Start reading nii Documents 
  img_path = os.path.join(filepath, f)
  img = nib.load(img_path)    # Read nii
  img_fdata = img.get_fdata()
  fname = f.replace('.nii','')   # Remove nii Suffix name of 
  img_f_path = os.path.join(imgfile, fname)
  # Create nii The folder of the corresponding image 
  if not os.path.exists(img_f_path):
   os.mkdir(img_f_path)    # New Folder 
 
  # Start converting to an image 
  (x,y,z) = img.shape
  for i in range(z):      #z Is a sequence of images 
   silce = img_fdata[i, :, :]   # You can choose which direction of slice 
   imageio.imwrite(os.path.join(img_f_path,'{}.png'.format(i)), silce)
            # Save an image 
 
if __name__ == '__main__':
 filepath = 'nii Folder of '
 imgfile = 'image Folder of '
 nii_to_image(filepath)

I wrote the code myself, and the nii format used to handle ADNI works perfectly.


Related articles: