一,nii文件拆分成2d图像
前面解决了如何建造nii文件,现在来把nii图像重新拆分成需要的2d图像(已经在构造整体的代码了,所以封装成了函数)
函数对图像进行归一化后*255输出,由于ITK-SNAP在做标签的时候,没标签的位置为0,不同颜色的标签分别是1-6,所以我mask并没有*255(*255会导致每个分类的灰度都是255,从而无法辨别),而是乘了40
import numpy as np
import nibabel as nib
from PIL import Image
import os
import shutil
import imageio
import cv2
'''
funtion name:nii2mask2d
input:img_addr,label_addr,target_folder(患者图像nii地址,3dmask的nii地址,处理好的对比图像存放地址)
output:none
将患者图像nii,3dmask的nii匹配,输出图像到target_folder
'''
def nii2mask2d(img_addr,label_addr,target_folder):
img_addr_n = nib.load(img_addr)
label_addr_n = nib.load(label_addr)
# Convert them to numpy format,
data = img_addr_n.get_fdata()
label_data = label_addr_n.get_fdata()
# clip the images within [-125, 275],
data_clipped = np.clip(data, -125, 275)
# normalize each 3D image to [0, 1], and
data_normalised = (data_clipped - (-125)) / (275 - (-125))
split_root = img_addr.split('\\') # 通过\\来进行截断
print(split_root)
# extract 2D slices from 3D volume for training cases while
# e.g. slice 000
for i in range(data_clipped.shape[2]):
formattedi = "{:03d}".format(i)
slice000 = data_normalised[:, :, i] * 255
# np.savetxt(r"label.txt", label_data[:, :, 6], delimiter=',', fmt='%5s')
label_slice000 = label_data[:, :, i]* 40 #标注像素是3,4,放到0-255的变化范围内
print(slice000.shape, type(slice000))
image = Image.fromarray(slice000)
image = image.convert("L")
image = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
label = Image.fromarray(label_slice000)
# print(type(label))
# label = cv2.normalize(label, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
np.savetxt(r".\test\masknoL" + str(i + 1) + ".txt", label)
# imageio.imsave(r".\test\mask_new" + str(i + 1) + ".png", label)
label = label.convert("L")
label = label.rotate(270)
np.savetxt(r".\test\mask" + str(i + 1) + ".txt", label)
#已验证分类结果没消失
image.save(target_folder + split_root[-2]+"T2W_TSE_" + str(i+1) + ".png")
label.save(target_folder + "T2W_TSE_" + str(i+1) + "_label.png")
if __name__ == '__main__':
img_addr = r"C:\Users\22495\Desktop\project_folder\mr_data.nii.gz"
label_addr = r"C:\Users\22495\Desktop\myomagroup3a\Untitled.nii.gz"
target_folder = "./test/"
nii2mask2d(img_addr, label_addr, target_folder)#单患者放在test观察
为了患者隐私名称就打码了