import os
import nibabel as nib
import h5py
import numpy as np
def convert_nii_to_h5(input_folder, output_folder):
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=True)
# 遍历输入文件夹下的所有文件
for filename in os.listdir(input_folder):
if filename.endswith(".nii") or filename.endswith(".nii.gz"):
# 构建完整的文件路径
nii_path = os.path.join(input_folder, filename)
h5_filename = os.path.splitext(filename)[0] + ".h5"
h5_path = os.path.join(output_folder, h5_filename)
# 读取 .nii 文件
nii_file = nib.load(nii_path)
image_data = nii_file.get_fdata(dtype=np.float32) # 使用浮点数以确保精度
header = nii_file.header
# 创建 .h5 文件并保存数据
with h5py.File(h5_path, 'w') as h5_file:
h5_file.create_dataset('data', data=image_data, dtype=np.float32)
# 保存 header 信息作为属性
for key in header:
h5_file.attrs[key] = header[key]
print(f"转换完成: {nii_path} -> {h5_path}")
# 设置输入文件夹和输出文件夹路径
input_folder = "/BraTST1"
output_folder = "/T1h5"
# 执行转换
convert_nii_to_h5(input_folder, output_folder)
nii to h5代码
最新推荐文章于 2025-04-03 16:49:51 发布