code: from glob import glob
  import pydicom
  from pydicom import dcmread
  import os
  import numpy as np
  import nibabel as nib
  
  
  def dicom_to_nifti(folder):
      dicoms = None
      return
  
  
  def read_a_dicom(dicom_file):
      ds = dcmread(dicom_file)
  
  
  def get_array(dcm_file):
      ds = dcmread(dcm_file)
      location = float(ds[0x0020, 0x1041].value)
      array = ds.pixel_array
      return (array, location)
  
  
  def stack_dicoms(dicoms):
      pool = []
      for file in dicoms:
          pool.append(get_array(file))
      pool.sort(key=lambda x : x[1])
      return np.stack([x[0] for x in pool], axis=0)
  
  
  def find_subfolders(root_dir):
      count = 0
      for root, dirs, files in os.walk(root_dir):
          if 't1' in root and len(files) and '.dcm' in files[0]:
              full_path = [os.path.join(root, file) for file in files]
              count += 1
              identifier = full_path[0].split('/')[5]
              print(identifier)
              try:
                  volume = stack_dicoms(full_path)
                  print(volume.shape)
                  nifti = nib.Nifti1Image(volume, affine=np.eye(4))
                  nib.save(nifti, '/data_2/FHS/nifti/{}.nii'.format(identifier))
              except ValueError:
                  print('value error')
                  pass
              except RuntimeError:
                  print('runtime error')
                  pass
      print(count)
  
  
  if __name__ == "__main__":
      path = '/data_2/FHS/20200819/'
      find_subfolders(path)
  
apis: numpy.stack numpy.eye