2023-08-25 计算勾画结构的Dice值

给定同一CT下的两个RTSTRUCT文件,如何计算某个roi的dice值?
需要注意的是,文件夹下面不能有RTdose(RD)文件,否则会误认为CTSeries的一部分
有个办法是在patient目录下面做个CT目录,把CT series文件放在这里面,即目录结构如下:
-patient
--CT
---CT_slice1.dcm
---CT_slice2.dcm
......
--RTStruct.dcm
--RTPlan.dcm
--RTDose.dcm

import pydicom, os
import numpy as np
import pprint
from rt_utils import RTStructBuilder

def get_binary_masks(ct_folder, rtstruct_path, roi_names):
    """
    Returns binary masks for multiple ROIs.
    """
    # Load existing RT Struct.
    rtstruct = RTStructBuilder.create_from(dicom_series_path=ct_folder, rt_struct_path=rtstruct_path)
    
    # Dict to store masks
    masks = {}

    # Loading the 3D Masks for each ROI
    for roi in roi_names:
        masks[roi] = rtstruct.get_roi_mask_by_name(roi)

    return masks

def compute_dice(mask1, mask2):
    """
    Compute the Dice similarity coefficient between two binary masks.
    """
    intersection = np.sum(mask1 * mask2)
    return 2. * intersection / (np.sum(mask1) + np.sum(mask2))

def compute_dice_for_roids(ct_folder, rtstruct1_path, rtstruct2_path, roi_names):
    """
    Compute the Dice similarity coefficient for a list of ROIs from two RTSTRUCT files.
    """
    masks1 = get_binary_masks(ct_folder, rtstruct1_path, roi_names)
    masks2 = get_binary_masks(ct_folder, rtstruct2_path, roi_names)
    
    dice_values = {}
    for roi in roi_names:
        dice_values[roi] = compute_dice(masks1[roi], masks2[roi])

    return dice_values

roi_name = ["Bowel",'Bladder','Rectum']
folder_path = r"D:\code\temp3\Test004"

rs_files = [f for f in os.listdir(folder_path) if f.endswith(".dcm") and pydicom.dcmread(os.path.join(folder_path,f)).Modality == 'RTSTRUCT']

if len(rs_files) != 2:
    print(f"Unexpected number of RS files in {folder_path}. Skipping...")

ct_path = os.path.join(folder_path, 'CT')
rs_file1 = os.path.join(folder_path, rs_files[0])
rs_file2 = os.path.join(folder_path, rs_files[1])

# 使用
dice_value = compute_dice_for_roids(ct_path, rs_file1, rs_file2, roi_name)
print(f"Dice value for ROI '{roi_name}':")
pprint.pprint(dice_value)

输出结果如下:

Dice value for ROI '['Bowel', 'Bladder', 'Rectum']':
{'Bladder': 0.7260938138909983,
 'Bowel': 0.5581661189246565,
 'Rectum': 0.5876511775938893}

提取roi的mask,用到 RT-Utils 这个模块

Loading an existing RT Struct contour as a mask

from rt_utils import RTStructBuilder
import matplotlib.pyplot as plt

# Load existing RT Struct. Requires the series path and existing RT Struct path
rtstruct = RTStructBuilder.create_from(
  dicom_series_path="./testlocation", 
  rt_struct_path="./testlocation/rt-struct.dcm"
)

# View all of the ROI names from within the image
print(rtstruct.get_roi_names())

# Loading the 3D Mask from within the RT Struct
mask_3d = rtstruct.get_roi_mask_by_name("ROI NAME")

# Display one slice of the region
first_mask_slice = mask_3d[:, :, 0]
plt.imshow(first_mask_slice)
plt.show()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。