nii格式转化为png格式或者img格式

import cv2 import numpy as np import os #遍历文件夹 import nibabel as nib import imageio #转换成图像def nii_to_image(filepath,flag="image"): filenames = os.listdir(filepath)#读取nii文件 slice_trans = []for f in filenames: #开始读取nii文件 img_path = os.path.join(filepath, f) img = nib.load(img_path)#读取nii img_fdata = https://www.it610.com/article/img.get_fdata() fname = f.replace('.nii', '') #去掉nii的后缀名 img_f_path = os.path.join(newfilepath, fname) # 创建nii对应图像的文件夹 if not os.path.exists(img_f_path): os.mkdir(img_f_path)#新建文件夹 if(flag=="image"): img_fdata=https://www.it610.com/article/(img_fdata-img_fdata.min())/(img_fdata.max()-img_fdata.min())*255 #开始转换图像 (x,y,z) = img.shape for i in range(z):#是z的图象序列 slice = img_fdata[:, :, i]#选择哪个方向的切片自己决定 print(os.path.join(img_f_path,'{}.png'.format(i))) cv2.imwrite(os.path.join(img_f_path, '{}.png'.format(i)), slice)if __name__ == '__main__': oldfilepath = 'D:\FLARE2022\label'#nii文件所在的文件夹路径 newfilepath = 'D:/test/label'#转化后的png文件存放的文件路径 nii_to_image(oldfilepath,"label")

    推荐阅读