Skip to content

Instantly share code, notes, and snippets.

@ashkanpakzad
Created August 14, 2020 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashkanpakzad/da88aeede29dd06a43875da73122c4a8 to your computer and use it in GitHub Desktop.
Save ashkanpakzad/da88aeede29dd06a43875da73122c4a8 to your computer and use it in GitHub Desktop.
import nibabel as nib
import dicom_numpy
import os
import numpy as np
pathtodicom = '/path/to/dicom/'
# get list of dicom images from directory that make up the 3D image
dicomlist = [pathtodicom + f for f in os.listdir(pathtodicom)]
# load dicom volume
vol, affine_LPS = dicom_numpy.combine_slices(dicomlist)
# convert the LPS affine to RAS
affine_RAS = np.diagflat([-1,-1,1,1]).dot(affine_LPS)
# create nibabel nifti object
niiimg = nib.Nifti1Image(vol, affine_RAS)
nib.save(niiimg, '/path/to/save')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment