import numpy as npimport os # 遍历文件夹import nibabel as nib # nii格式一般都会用到这个包import imageio # 转换成图像center = -500 //肺部的窗宽窗位width = 1500def nii_to_image(filepath):filenames = os.listdir(filepath) # 读取nii文件夹for f in filenames:# 开始读取nii文件img_path = os.path.join(filepath, f)img = nib.load(img_path) # 读取niiimg_fdata = img.get_fdata() # api 已完成转换,读出来的即为CT值fname = f.replace('.nii.gz', '') # 去掉nii的后缀名img_f_path = os.path.join(filepath, fname)# 创建nii对应的图像的文件夹if not os.path.exists(img_f_path):os.mkdir(img_f_path) # 新建文件夹# 转换成窗宽窗位min = (2 * center - width) / 2.0 + 0.5max = (2 * center + width) / 2.0 + 0.5dFactor = 255.0 / (max - min)# 开始转换为图像(x, y, z) = img.shapefor i in range(z): # z是图像的序列silce = img_fdata[:, :, i] # 选择哪个方向的切片都可以silce = silce - minsilce =np.trunc( silce * dFactor)silce[silce < 0.0] = 0silce[silce > 255.0] = 255 # 转换为窗位窗位之后的数据maskimg_slice = maskimg_fdata[:,:,i]temp = fname+"_" + '{}.png'.format(i)imageio.imwrite(os.path.join(img_f_path, temp),silce[int((x - 512) / 2):int((x - 512) / 2) + 512])if __name__ == '__main__':filepath = ' 'nii_to_image(filepath)
1200字范文,内容丰富有趣,写作的好帮手!