I have a lot of 2D nibabel (.nii) slices and I need to create a 3D nibabel (.nii) image from those slices, is there any way to do it?
1 Answers
If you use numpy to hold 2D slice data as arrays, you can combine the 2D arrays that represent each slice into a 3D array and perform whatever processing you need in python:
import nibabel
import numpy as np
#The variable imgs here represent a list of your 2D .nii nibabel data
#initialize an empty 3D array with shape
# determined by your 2D slice shape and the number of slices
num_imgs = len(imgs)
dims_single_2D = imgs[0].shape
dim_1 = dims_single_2D[0]
dim_2 = dims_single_2D[1]
stack_of_slices = np.zeros((dim_1, dim_2, num_imgs))
stack_id = 0
for img in imgs:
img_data = img.get_data()
# Convert to numpy ndarray (dtype: uint16)
img_data_arr = np.asarray(img_data)
stack_of_slices[stack_id] = img_data_arr
stack_id = stack_id + 1
# followed by the rest of your processing on the 3D array stack_of_slices
Note that if the .nii you are working with are NIFTI files (I have not seen 2D NIFTI files in use since this is usually a volume format), this is a more complex operation. If you want to save out NIFTIs, you will need the headers and affine matrix to form a complete file:
https://nipy.org/nibabel/nifti_images.html?highlight=dim#working-with-nifti-images
https://nipy.org/nibabel/reference/nibabel.nifti2.html#module-nibabel.nifti2
A more common 2D image format is DICOM (https://nipy.org/nibabel/dicom/dicom_intro.html?highlight=dicom), for which nibabel also has tools to read and convert to arrays: https://nipy.org/nibabel/reference/nibabel.nicom.html?highlight=dicom#module-nibabel.nicom
https://nipy.org/nibabel/reference/nibabel.nicom.html?highlight=dicom#module-nibabel.nicom

- 443
- 2
- 13