nii data
import nibabel as nib
import numpy as np
#=========load the data===============
# create the object
label_nii = nib.load("your_nii_name.nii")
# extract the data from the dataobj attribute
label = label_nii.dataobj
# or extract data from the get_data() method
# label = label_nii.get_data()
# convert the shape of WHD to DWH
label = np.transpose(label,(2,1,0)
# now you can play with the data
......
#=========save the edited data to nii file==========
# convert the shape back to WHD
out = np.transpose(label,(2,1,0))
# copy the head from the label_nii object
new_header = header = label_nii.header.copy()
# fill the data and head to a new object
out = nib.nifti1.Nifti1Image(out,None,header=new_header)
# save the nii file
nib.save(out,"new_nii_name.nii")
Dicom data
import pydicom
import numpy as np
#==========load the data==================
# create the object
image = pydicom.read_file("your_dicom_name.dcm")
# extract the data from the pixel_array attribute
image_data = image.pixel_array
# now you can play with your data
output_data=......
#=========save the dicom file=============
# change the pixel data in the image object
image.PixelData = output_data.tobytes()
# (optional):
# if you change the shape of the pixel data you should
# change the shape attribute in image object
image.Rows,image.Columns = output_data.shape
# then change the pixel spacing
#(following code show how to reduce the pixel spacing by half)
pixel_spacing = img.PixelSpacing
ps1 = float(pixel_spacing[0])/2
ps2 = float(pixel_spacing[1])/2
pixel_spacing = [str(ps1),str(ps2)]
# save the change to dicom file
image.save_as("your_dicom_name.dcm")
SimpleItk
import SimpleITK as sitk
image = sitk.ReadImage("image.dcm")
image_array = sitk.GetArrayFromImage(image)
# ....play with the image_array
sitk_out = sitk.GetImageFromArray(image_array)
sitk.WriteImage(sitk_out, "yourname.nii.gz or .dcm")