pythonnumpynibabel

Problems with converting all slices into nii.gz at once


I'm using the following code to convert all my 332 npy slices into the nii.gz format:

import numpy as np
import nibabel as nib

file_dir = "D:/Volumes convertidos LIDC/"
fileNPY1 = "slice200.npy"
img_array1 = np.load(file_dir + fileNPY1) 
nifti_file = nib.Nifti1Image(img_array1 , np.eye(4))
nib.save(nifti_file, "D:/slices convertidos/slice200converted.nii.gz")

There are just too many slices for me (and tons of images) to keep doing it that way, is there a way to convert them all at once?


Solution

  • I don’t know nibabel, and I am not sure if I understand correctly what you are trying to do, but perhaps this will be helpful:

    import numpy as np
    import nibabel as nib
    
    file_dir = "D:/Volumes convertidos LIDC/"
    for i in range(332):
        fileNPY1 = f"slice{i}.npy"
        img_array1 = np.load(file_dir + fileNPY1) 
        nifti_file = nib.Nifti1Image(img_array1 , np.eye(4))
        nib.save(nifti_file, f"D:/slicesconvertidos/slice{i}converted.nii.gz")