详细~~医学图像格式转换(.h5文件转为nii.gz文件!!!)

首先先查看一下.h5文件中的内容:

import h5py

def show_hdf5_datasets(h5_file_path):
    with h5py.File(h5_file_path, 'r') as h5_file:
        print("Datasets in the HDF5 file:")
        for dataset_name in h5_file:
            print(dataset_name)

h5_file_path = 'input_file.h5'
show_hdf5_datasets(h5_file_path)

然后根据里面内容进行对应的转换:

以我自己的为例:我里面是 image 和 label 两个内容,所以我的转换如下(其他都是类似,大家类比一下):
 

import h5py
import numpy as np
import nibabel as nib

def h5_to_nifti(h5_file_path, nifti_file_path, nifti_label_file_path):
    # 读取HDF5文件
    with h5py.File(h5_file_path, 'r') as h5_file:
        # 获取'image'和'label'数据集
        if 'image' not in h5_file:
            raise ValueError("HDF5 file should contain a dataset named 'image'")
        if 'label' not in h5_file:
            raise ValueError("HDF5 file should contain a dataset named 'label'")
        
        image_data = h5_file['image'][:]
        label_data = h5_file['label'][:]
        
        # 转换为NIfTI格式
        # 
        image_data = np.transpose(image_data, (2, 1, 0))
        label_data = np.transpose(label_data, (2, 1, 0))
        
        # 创建NIfTI图像对象
        nifti_img = nib.Nifti1Image(image_data, affine=np.eye(4))  
        nifti_label_img = nib.Nifti1Image(label_data, affine=np.eye(4))  
        
        # 保存为NIfTI文件
        nib.save(nifti_img, nifti_file_path)
        nib.save(nifti_label_img, nifti_label_file_path)


h5_file_path = 'input_file.h5'
nifti_file_path = 'output_image.nii.gz'
nifti_label_file_path = 'output_label.nii.gz'
h5_to_nifti(h5_file_path, nifti_file_path, nifti_label_file_path)

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天不想Debug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值