因为项目需要把CT图像中骨头更加明确的显示出来,且还需要保存nii文件,所以查了一些资料,在这里做一下笔记,方便以后使用。代码如下:
import nibabel as nib import numpy as np import SimpleITK as sitk center = 350 # 窗位 width = 1200 # 窗宽 filename = 'E:/个人/骨折检测/分割项目/HDC-Net-master/mydata/RibFrac1-image.nii.gz' img = nib.load(filename) img_fdata = img.get_fdata() min = (2 * center - width) / 2.0 + 0.5 max = (2 * center + width) / 2.0 + 0.5 dFactor = 255.0 / (max - min) img_fdata[img_fdata<min] = min img_fdata[img_fdata>max] = max # 进行转置,因为需要按照原来的方向进行保存 data = np.transpose(img_fdata, [2, 1, 0]) (z, y, x) = data.shape print(z," ",y," ",x) for i in range(z): for j in range(x): for k in range(y): value = data[i,j,k] if value <= min: value = 0 elif value < max: value = (value - min) / width * 255 elif value >= max: value = 255 else: data[i,j,k] = value #进行保存 print("-----------------") filesname = "RibFrac1.nii.gz" img = sitk.GetImageFromArray(data) sitk.WriteImage(img, filesname) print("+++++++++++++++++")