使用SimpleITK计算如下所示的病灶标注的整体体积。
可以在该代码的基础上,增加写入excel表的操作,这样就可以把模型推理前的体积和模型推理后的体积都写入excel表,然后进行一系列分析。
1 计算ROI病灶体积
用SimpleITK包进行ROI/病灶体积的计算
import SimpleITK as sitk
import numpy as np
def calculate_volume(mask_image_path):
# 读取分割结果的图像文件
mask_image = sitk.ReadImage(mask_image_path)
# 获取图像的大小、原点和间距
size = mask_image.GetSize()
origin = mask_image.GetOrigin()
spacing = mask_image.GetSpacing()
# 将 SimpleITK 图像转换为 NumPy 数组
mask_array = sitk.GetArrayFromImage(mask_image)
# 计算非零像素的数量
non_zero_voxels = (mask_array > 0).sum()
# 计算像素的体积(以立方毫米为单位)
voxel_volume_mm3 = spacing[0] * spacing[1] * spacing[2]
# 计算体积(以 mm³ 为单位)
volume_mm3 = non_zero_voxels * voxel_volume_mm3
# 如果需要以其他单位(例如 cm³)显示,请进行适当的单位转换
volume_cm3 = volume_mm3 / 1000.0
return size,spacing,non_zero_voxels,volume_cm3
maskFilePath = "./dataset/split_2_41/train/Mask/sub-strokecase0001_ses-0001_msk_reg.nii.gz"
size,spacing,non_zero_voxels,roi_volume = calculate_volume(maskFilePath)
print("================================")
print(size,spacing,non_zero_voxels)
print(f'ROI 或病灶的体积为 {roi_volume} cm³')
测试结果:
================================
(97, 113, 97) (2.0, 2.0, 2.0) 1446
ROI 或病灶的体积为 11.568 cm³
2,写入excel中
写入excel中:表格形式如下:
代码如下:
import SimpleITK as sitk
import numpy as np
import os
import pandas as pd
import openpyxl
def toexcel(maskfilepath,excelfilepath):
maskFilePath = maskfilepath
excel_file_path = excelfilepath
file_names = []
sizes = []
spacings = []
non_zero_voxels = []
roi_volumes = []
for file_name in os.listdir(maskFilePath):
if file_name.endswith('.nii.gz'): # Assuming your files have this extension
file_path = os.path.join(maskFilePath, file_name)
# Assuming your calculate_volume function returns a tuple (size, spacing, non_zero_voxels, roi_volume)
size, spacing, non_zero_voxel, roi_volume = calculate_volume(file_path)
file_names.append(file_name)
sizes.append(size)
spacings.append(spacing)
non_zero_voxels.append(non_zero_voxel)
roi_volumes.append(roi_volume)
print(file_names, spacings, non_zero_voxels, roi_volumes)
# Create a DataFrame from the lists:
data = {
'File Name': file_names,
'Size': sizes,
'Spacing': spacings,
'Non-Zero Voxels': non_zero_voxels,
'ROI Volume': roi_volumes
}
df = pd.DataFrame(data)
df.to_excel(excel_file_path, index=False, header=['File Name', 'Size', 'Spacing', 'Non-Zero', 'ROI Volume/Ml'])
print('完成')