import SimpleITK as sitk
import numpy as np
import cv2
import os
import glob
import tqdm
def nifti2png(path):
for file in tqdm.tqdm(glob.glob(os.path.join(path, "*"))): # *表示通配符,即path下面的所有文件都遍历一遍
image = sitk.ReadImage(file)
arr = sitk.GetArrayFromImage(image)
arr = ((arr - np.min(arr)) / (np.max(arr) - np.min(arr)) * 255).astype(np.uint8)
z, y, x = arr.shape
for i in range(z):
slice = arr[i, :, :]
save_name = os.path.join("/datasets/2Dslices_train",
os.path.basename(file)[:-7] + "_" + str(i + 1) + ".png")
cv2.imwrite(save_name, slice) #写入图像,将后面的图像名写入前面的存放路径
if __name__ == '__main__':
path = "/home/imed/下载/transUnetDataset/Synapse/train_npz"
nifti2png(path)
需要注意的是,3D转换到2图像D时,因为像素值范围不同,因此需要归一化到二维图像的像素值范围,对应的代码表述为:arr = ((arr - np.min(arr)) / (np.max(arr) - np.min(arr)) * 255).astype(np.uint8)或者为arr=(arr/np.max(arr)*255).astype(np.uint8)
若不用定义方法的形式,无法批量化,手动处理每一张的方法如下:
file = "/home/imed/下载/transUnetDataset/Synapse/train_npz/DET0000101_avg.nii.gz"
image = sitk.ReadImage(file)
arr = sitk.GetArrayFromImage(image)
# arr=(arr/np.max(arr)*255).astype(np.uint8)
arr = (arr - np.min(arr)) / (np.max(arr) - np.min(arr)) * 255
z, y, x = arr.shape
for i in range(z):
slice = arr[i, :, :]
print(np.max(slice))
cv2.imwrite(os.path.join("/home/imed/下载/transUnetDataset/Synapse/train_npz/zz", str(i + 1) + ".png"), slice)