dcm文件批量转换为nii.gz文件

import os
import pydicom
import nibabel as nib
import numpy as np
from glob import glob
from pydicom.pixel_data_handlers.util import apply_voi_lut

def dicom_to_nifti(dicom_dir, nifti_path):
    
    dicom_files = glob(os.path.join(dicom_dir, '*.dcm'))
    dicom_files.sort()
    
    if not dicom_files:
        return False

    
    first_dicom = pydicom.dcmread(dicom_files[0])
    pixel_array = apply_voi_lut(first_dicom.pixel_array, first_dicom)
    slices = [pydicom.dcmread(f) for f in dicom_files]
    slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))

    
    pixel_spacing = first_dicom.PixelSpacing
    slice_thickness = first_dicom.SliceThickness
    image_shape = list(pixel_array.shape) + [len(slices)]

    
    image_3d = np.zeros(image_shape, dtype=pixel_array.dtype)

    for i, s in enumerate(slices):
        image_3d[:, :, i] = apply_voi_lut(s.pixel_array, s)

    
    nifti_image = nib.Nifti1Image(image_3d, np.eye(4))
    nifti_image.header['pixdim'][1:4] = [pixel_spacing[0], pixel_spacing[1], slice_thickness]
    
    
    nib.save(nifti_image, nifti_path)
    return True

def main(input_dir, output_dir):
    for root, dirs, files in os.walk(input_dir):
        if files:

            path_parts = root.split(os.sep)
            if len(path_parts) >= 4:
                patient_id = path_parts[-3]
                image_id = path_parts[-1]
                output_filename = f"{patient_id}-{image_id}.nii.gz"
                output_path = os.path.join(output_dir, output_filename)
                if dicom_to_nifti(root, output_path):
                    print(f"Converted {root} to {output_path}")
                else:
                    print(f"Failed to convert {root}")
            else:
                print(f"Skipping {root}: Not enough path levels")

if __name__ == "__main__":
    input_directory = "D:\\your\input\folder"
    output_directory = "D:\\your\output\folder"
    
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)
    
    main(input_directory, output_directory)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值