pythonimageniftinibabel

How can I obtain 2D slices from a 3D NIfti volume?


I'm currently using the following code to convert DCM slices into NIfti images:

import dicom2nifti
import os

dicom2nifti.convert_directory("input_path", "output_path", compression=True, reorient=True)

This code will generate a 3D NIfti volume.

How can I obtain all the slices from this 3D NIfti volume?


Solution

  • Use the package nibabel. A simple working example opens your NIfTI file as a numpy 3D matrix, which can use for your processing needs:

    import nibabel as nib
    import numpy as np
    import matplotlib.plot as plt
    
    
    my_nifti = nib.load('YOURNIFTIFILE.nii').get_fdata()
    
    # get the shape of your NIfTI
    my_nifti.shape
    
    # access it as 3D numpy array
    nifti_slice = my_nifti[:,:,59]
    
    # display the slice
    plt.imshow(nifti_slice)
    plt.show()