How to load and save nii and dicom file

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")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值