nii格式图像转为png,并重命名
文件夹格式:nii
输出格式:png,并重命名
将文件夹里的文件拆出来:
for /f "delims=" %%p in ('dir /b/ad') do copy %%p\*.* D:\test\test0_disease_png\
pause
import numpy as np
import os # 遍历文件夹
import nibabel as nib # nii格式一般都会用到这个包
import imageio # 转换成图像
def rename(imgfile):
#rootDir = imgfile
for root, dirs, files in os.walk(imgfile):
path = root
print(path)
for f in files:
os.rename(path + os.sep + f, path + os.sep + os.path.basename(path) + f)
def nii_to_image(niifile):
filenames = os.listdir(filepath) # 读取nii文件夹
slice_trans = []
for f in filenames:
# 开始读取nii文件
img_path = os.path.join(filepath, f)
img = nib.load(img_path) # 读取nii
img_fdata = img.get_fdata()
fname = f.replace('.nii.gz', '') # 去掉nii的后缀名,替换成空的即为文件夹
img_f_path = os.path.join(imgfile, fname)
# 创建nii对应的图像的文件夹
if not os.path.exists(img_f_path):
os.mkdir(img_f_path) # 新建文件夹
# 开始转换为图像
(x, y, z) = img.shape
for i in range(z): # z是图像的序列
silce = img_fdata[:, :, i] # 选择哪个方向的切片都可以
# imageio.imwrite(os.path.join(img_f_path,'{}.png'.format(i)), silce)
imageio.imwrite(os.path.join(img_f_path, '{}.png'.format(i)), silce)
# 保存图像
if __name__ == '__main__':
filepath = 'D:\mask\\test0'
imgfile = 'D:\\test\\test0_disease'
nii_to_image(filepath)
rename(imgfile)
本文来自博客园,作者:编程coding小白,转载请注明原文链接:https://www.cnblogs.com/zhenhua1203/p/15533777.html