dicom批量转Nii格式

import SimpleITK as sitk
import numpy as np
import pydicom
import os

'''
功能:读取filepath下的dcm文件
返回值:读取得到的SimpleITK.SimpleITK.Image类   
其他说明:  file = sitk.ReadImage(filepath)
            获取基本信息,大小,像素间距,坐标原点,方向
            file.GetSize()
            file.GetOrigin()
            file.GetSpacing()
            file.GetDirection()
'''

result_path = "xxx\\datasets\\image"

def get_work_path():
    path = input("input dcm work path:")
    return path

def get_dcm_fime_path(work_path):
    dcm_path = []
    for root, dirs, files in os.walk(work_path):
        for file in files:
            if file.endswith(".dcm"):
                dcm_path.append(root)
                break

    return dcm_path

def readdcm(filepath):
    # filepath = "./T2"
    series_id = sitk.ImageSeriesReader.GetGDCMSeriesIDs(filepath)
    series_file_names = sitk.ImageSeriesReader.GetGDCMSeriesFileNames(filepath, series_id[0])
    series_reader = sitk.ImageSeriesReader()  # 读取数据端口
    series_reader.SetFileNames(series_file_names)  # 读取名称
    images = series_reader.Execute()  # 读取数据
    return images


def save(path,dcm_images):

    split_name = path.split("\\")[4]
    num = split_name.split("-")[0]

    sitk.WriteImage(dcm_images, os.path.join(result_path + '/'+"Image" + str(int(num) + 138) + '.nii.gz'))


def main():

    dcm_list = get_dcm_fime_path(get_work_path())

    for path in dcm_list:

        dcm_images = readdcm(path)  # 读取文件

        save(path,dcm_images)

if __name__ == '__main__':
    main()

你可能感兴趣的:(pytorch系列,dicom)