详细~~医学图像格式转换(.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)

你可能感兴趣的:(前端,数据库,图像处理,numpy,python,开发语言)