.nii文件批量处理

以下代码可以批量计算分割的种类和每一类的的体积(立方厘米),并写入.xlsx文件中。

# -*- coding: UTF-8 -*-
from pathlib import Path
import SimpleITK as sitk
import numpy as np
import pandas as pd
import xlwt
import pandas as pd
from collections import defaultdict

label_map = {
    "1": "Carotid lumen-Right carotid",
    "2": "Carotid lumen-Left carotid",
    "3": "Web-Right carotid",
    "4": "Web-Left carotid",
    "5": "Calcification-Right carotid",
    "6": "Calcification-Left carotid",
    "7": "Hypodense plaque-Right carotid",
    "9": "Hypodense plaque-Left carotid",
    "10": "Intraluminal thrombus-Right carotid",
    "11": "Intraluminal thrombus-Left carotid",
    "0": "0",
    "8": "8",
}


def get_volume(path):
    itk = sitk.ReadImage(path)
    array = sitk.GetArrayFromImage(itk)
    labels = np.unique(array)
    labels = labels[labels > 0]
    res = [0] * 12
    for label in labels:
        vol = np.sum(array == label) * np.prod(itk.GetSpacing()) / 1000
        res[label] = vol
    return res


def export_excel(export):
    # 将字典列表转换为DataFrame
    pf = pd.DataFrame(export)
    # 输出
    pf.to_excel('D:\\info.xlsx', encoding='utf-8', index=False)


def main():
    data_path = Path(r"C:\Users\31590\Downloads\CTA_Analyze")
    p = Path(r"C:\Users\31590\Downloads\CTA_Analyze")
    file_full = []
    file_seg = []
    for file in p.rglob('*.nii.gz'):
        if file.parts[-1].endswith('cta1.nii.gz'):
            file_full.append(file)
        else:
            file_seg.append(file)
    seg_paths = file_seg
    d = {}
    info = defaultdict(list)
    for seg_path in seg_paths:
        print(seg_path)
        pat_id = seg_path.parts[-1]
        d[pat_id] = get_volume(seg_path.as_posix())
    for k, v in d.items():
        print(k)
        info['pat_id'].append(k)
        for idx, vol in enumerate(v):
            info[label_map[str(idx)]].append(vol)

    print(info)
    export_excel(info)


if __name__ == '__main__':
    main()

你可能感兴趣的:(python)