import numpy as np
import os # 遍歷文件夾
import nibabel as nib # nii格式一般都會用到這個包
import imageio # 轉換成圖像
center = -500 //肺部的窗寬窗位
width = 1500
def 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) # 讀取nii
img_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.5
max = (2 * center + width) / 2.0 + 0.5
dFactor = 255.0 / (max - min)
# 開始轉換爲圖像
(x, y, z) = img.shape
for i in range(z): # z是圖像的序列
silce = img_fdata[:, :, i] # 選擇哪個方向的切片都可以
silce = silce - min
silce =np.trunc( silce * dFactor)
silce[silce < 0.0] = 0
silce[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)