1、读写nii.gz文件
1 ## using simpleITK to load and save data.
2 import SimpleITK as sitk
3 itk_img = sitk.ReadImage('./nifti.nii.gz')
4 img = sitk.GetArrayFromImage(itk_img)
5 print("img shape:",img.shape)
6
7 ## save
8 out = sitk.GetImageFromArray(img)
9 # # out.SetSpacing(itk_img.GetSpacing())
10 # # out.SetOrigin(itk_img.GetOrigin())
11 sitk.WriteImage(out,'simpleitk_save.nii.gz')
2、对于神经网络输出概率生成二值图保存
1 import os
2 import SimpleITK as sitk
3 from glob import glob
4
5
6 def save_prob2label(prob_dir, save_labeldir):
7 all_prob_seg = glob(os.path.join(prob_dir, "*.nrrd"))
8 for index, file in enumerate(all_prob_seg):
9 print("processing", index, '/', len(all_prob_seg), file)
10 label_file = file.replace(prob_dir, save_labeldir).replace(".nrrd", ".nii.gz")
11 prob_img = sitk.ReadImage(file)
12 prob_arr = sitk.GetArrayFromImage(prob_img)
13 label_arr = (prob_arr > Dice_value) * 1
14 label_img = sitk.GetImageFromArray(label_arr)
15 sitk.WriteImage(label_img, label_file)
16
17
18 if __name__ == '__main__':
19
20 prob_nrrd_dir = r'C:\Users\wmz\Desktop\input'
21 save_label_dir = r'C:\Users\wmz\Desktop\test'
22 Dice_value = 0.5
23 save_prob2label(prob_nrrd_dir, save_label_dir)