SimpleITK读写nii.gz文件

SimpleITK读写nii.gz文件

  • 1、读写nii.gz文件
  • 2、对于神经网络输出概率生成二值图保存

1、读写nii.gz文件

## using simpleITK to load and save data.
import SimpleITK as sitk
itk_img = sitk.ReadImage('./nifti.nii.gz')
img = sitk.GetArrayFromImage(itk_img)
print("img shape:",img.shape)
 
## save 
out = sitk.GetImageFromArray(img)
# # out.SetSpacing(itk_img.GetSpacing())
# # out.SetOrigin(itk_img.GetOrigin())
sitk.WriteImage(out,'simpleitk_save.nii.gz')

参考:使用SimpleITK读取和保存Nii.gz文件

2、对于神经网络输出概率生成二值图保存

import os
import SimpleITK as sitk
from glob import glob


def save_prob2label(prob_dir, save_labeldir):
    all_prob_seg = glob(os.path.join(prob_dir, "*.nrrd"))
    for index, file in enumerate(all_prob_seg):
        print("processing", index, '/', len(all_prob_seg), file)
        label_file = file.replace(prob_dir, save_labeldir).replace(".nrrd", ".nii.gz")
        prob_img = sitk.ReadImage(file)
        prob_arr = sitk.GetArrayFromImage(prob_img)
        label_arr = (prob_arr > Dice_value) * 1
        label_img = sitk.GetImageFromArray(label_arr)
        sitk.WriteImage(label_img, label_file)


if __name__ == '__main__':

    prob_nrrd_dir = r'C:\Users\wmz\Desktop\input'
    save_label_dir = r'C:\Users\wmz\Desktop\test'
    Dice_value = 0.5
    save_prob2label(prob_nrrd_dir, save_label_dir)

你可能感兴趣的:(ITK,ITK)