用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

将 dicom 转换为nii.gz

2025-11-03 作者: Playboy_lh举报

[python]代码库

import os
import SimpleITK as sitk
import glob

def find_dicom_files(input_folder):
    """
    递归查找DICOM文件,支持多层目录结构
    
    参数:
    - input_folder: 搜索DICOM文件的根目录
    
    返回:
    - 包含DICOM文件的目录路径,如果没找到返回None
    """
    # 首先检查当前目录
    reader = sitk.ImageSeriesReader()
    dicom_files = reader.GetGDCMSeriesFileNames(input_folder)
    
    if dicom_files:
        return input_folder
    
    # 如果当前目录没有,递归搜索子目录
    for root, dirs, files in os.walk(input_folder):
        if root != input_folder:  # 跳过根目录本身
            dicom_files = reader.GetGDCMSeriesFileNames(root)
            if dicom_files:
                return root
    
    return None

def dicom_to_nifti(input_folder, output_file):
    """
    将一个目录中的 DICOM 文件转换为 NIfTI 格式 (.nii.gz)。

    参数:
    - input_folder: 包含 DICOM 文件的目录路径。
    - output_file: 输出的 NIfTI 文件路径 (.nii.gz)。

    """
    try:
        # 查找实际的DICOM文件位置
        actual_dicom_folder = find_dicom_files(input_folder)
        
        if not actual_dicom_folder:
            print(f"警告: 在 {input_folder} 及其子目录中未找到 DICOM 文件")
            return False
        
        # 读取 DICOM 文件
        reader = sitk.ImageSeriesReader()
        dicom_files = reader.GetGDCMSeriesFileNames(actual_dicom_folder)
        reader.SetFileNames(dicom_files)

        # 将 DICOM 文件读取为 SimpleITK 图像
        image = reader.Execute()

        # 保存为 NIfTI 格式
        sitk.WriteImage(image, output_file)
        print(f"成功: NIfTI 文件已保存到: {output_file} (来源: {actual_dicom_folder})")
        return True
        
    except Exception as e:
        print(f"错误: 处理 {input_folder} 时出错: {str(e)}")
        return False

def process_all_patients(base_path):
    """
    处理当前目录下所有病人文件夹中的CT和CBCT数据
    
    参数:
    - base_path: 包含所有病人文件夹的根目录路径(默认为当前目录)
    """
    # 创建输出目录
    output_dir = os.path.join(base_path, "converted_nifti")
    os.makedirs(output_dir, exist_ok=True)
    
    print(f"输出目录: {output_dir}")
    
    # 获取当前目录下的所有病人文件夹(排除输出目录)
    all_items = [item for item in os.listdir(base_path) 
                 if os.path.isdir(os.path.join(base_path, item))]
    
    # 排除输出目录和其他系统目录
    patient_dirs = [item for item in all_items 
                   if item != "converted_nifti" and not item.startswith('.')]
    
    print(f"找到 {len(patient_dirs)} 个病人文件夹")
    
    ct_success_count = 0
    cbct_success_count = 0
    
    for patient_name in patient_dirs:
        patient_dir = os.path.join(base_path, patient_name)
        print(f"\n处理病人: {patient_name}")
        
        # 检查是否存在 ct 和 cbct 子文件夹
        ct_dir = os.path.join(patient_dir, "ct")
        cbct_dir = os.path.join(patient_dir, "cbct")
        
        # 处理 CT
        if os.path.exists(ct_dir):
            ct_output_file = os.path.join(output_dir, f"{patient_name}_ct.nii.gz")
            print(f"  处理CT: {patient_name}")
            if dicom_to_nifti(ct_dir, ct_output_file):
                ct_success_count += 1
        else:
            print(f"  警告: 病人 {patient_name} 中未找到 ct 文件夹")
        
        # 处理 CBCT
        if os.path.exists(cbct_dir):
            cbct_output_file = os.path.join(output_dir, f"{patient_name}_cbct.nii.gz")
            print(f"  处理CBCT: {patient_name}")
            if dicom_to_nifti(cbct_dir, cbct_output_file):
                cbct_success_count += 1
        else:
            print(f"  警告: 病人 {patient_name} 中未找到 cbct 文件夹")
    
    print(f"\n处理完成!")
    print(f"CT 成功转换: {ct_success_count} 个")
    print(f"CBCT 成功转换: {cbct_success_count} 个")

if __name__ == "__main__":
    # 使用当前目录作为基础路径
    current_dir = os.getcwd()
    print(f"当前工作目录: {current_dir}")
    process_all_patients(current_dir)

[代码运行效果截图]


将 dicom 转换为nii.gz


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...