在 3D Slicer 中,从手动导入CT数据到生成用于3D打印的STL模型,涉及一个标准化的处理流程。以下 Python 代码将这一流程封装为一个简易的软件模块,通过 `openclaw` 类提供清晰的函数调用接口 [ref_2][ref_3]。
### 核心流程与代码结构
整个流程可解构为六个步骤,代码将围绕一个主类 `OpenClawProcessor` 进行组织。
```python
"""
openclaw.py
3D Slicer 自动化处理流程:从CT分割到生成3D打印浇筑腔。
依赖:3D Slicer 内置 Python 环境 (SlicerPython)
"""
import slicer
import os
class OpenClawProcessor:
"""
主处理器类,封装从数据加载到模型导出的完整流程。
"""
def __init__(self):
self.volume_node = None # 加载的CT体积数据节点
self.skin_segment_name = "Skin" # 皮肤分割段名称
self.tumor_segment_name = "Tumor" # 肿瘤分割段名称
self.cavity_segment_name = "CastingCavity" # 生成的浇筑腔名称
self.segmentation_node = None # 分割节点,容纳所有分割结果
self.segment_editor_node = None # 分割编辑器逻辑节点
def load_ct_volume(self, file_path):
"""
步骤1:手动导入CT图像数据。
支持 DICOM 目录、NIfTI (.nii/.nii.gz) 或 NRRD 文件。
"""
if not os.path.exists(file_path):
raise FileNotFoundError(f"文件路径不存在: {file_path}")
print(f"[INFO] 正在加载数据: {file_path}")
# slicer.util.loadVolume 能自动识别多种格式
self.volume_node = slicer.util.loadVolume(file_path)
if not self.volume_node:
raise RuntimeError(f"无法加载文件,请检查格式: {file_path}")
print(f"[INFO] 数据加载成功。图像尺寸: {self.volume_node.GetImageData().GetDimensions()}")
return self.volume_node
def setup_segmentation_workspace(self):
"""
步骤2:初始化分割工作空间。
创建分割节点,并关联到分割编辑器。
"""
# 创建新的分割节点
self.segmentation_node = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLSegmentationNode")
self.segmentation_node.CreateDefaultDisplayNodes()
# 关键:设置分割的参考几何,确保与CT空间对齐
self.segmentation_node.SetReferenceImageGeometryParameterFromVolumeNode(self.volume_node)
# 获取分割编辑器部件并关联节点
segment_editor_widget = slicer.modules.segmenteditor.widgetRepresentation().self()
segment_editor_widget.setSegmentationNode(self.segmentation_node)
segment_editor_widget.setMasterVolumeNode(self.volume_node)
# 创建并设置分割编辑器节点
self.segment_editor_node = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLSegmentEditorNode")
segment_editor_widget.setCurrentSegmentEditorNode(self.segment_editor_node)
print("[INFO] 分割工作空间初始化完成。")
return self.segmentation_node
def segment_skin_by_threshold(self, threshold_min=-200, threshold_max=200):
"""
步骤3.1:使用阈值法分割皮肤。
基于CT值范围进行分割,适用于皮肤与空气高对比度场景。
"""
import vtkSegmentationCorePython as segCore
# 在分割节点中创建皮肤段
skin_segment = segCore.vtkSegment()
skin_segment.SetName(self.skin_segment_name)
self.segmentation_node.GetSegmentation().AddSegment(skin_segment)
# 配置分割编辑器
segment_editor_widget = slicer.modules.segmenteditor.widgetRepresentation().self()
segment_editor_widget.setCurrentSegmentEditorNode(self.segment_editor_node)
segment_editor_widget.setActiveEffectByName("Threshold")
effect = segment_editor_widget.activeEffect()
# 设置阈值参数
effect.setParameter("MinimumThreshold", str(threshold_min))
effect.setParameter("MaximumThreshold", str(threshold_max))
effect.setParameter("ThresholdRangeMin", str(threshold_min))
effect.setParameter("ThresholdRangeMax", str(threshold_max))
print(f"[INFO] 应用皮肤阈值分割,范围: [{threshold_min}, {threshold_max}]")
effect.self().onApply() # 执行分割
# 可选后处理:保留最大连通区域以去除内部“孤岛”(如鼻腔)
segment_editor_widget.setActiveEffectByName("Islands")
effect = segment_editor_widget.activeEffect()
effect.setParameter("Operation", "KEEP_LARGEST_ISLAND")
effect.self().onApply()
print("[INFO] 皮肤分割完成,并已清理孤岛。")
def segment_tumor_by_grow_from_seeds(self, seed_coordinates_list, intensity_tolerance=50):
"""
步骤3.2:使用区域生长法分割肿瘤。
需要提供肿瘤内部的种子点坐标(基于图像索引或RAS坐标)。
注意:此函数模拟了参数设置,但种子点交互通常更适合在GUI中完成。
"""
import vtkSegmentationCorePython as segCore
# 创建肿瘤段
tumor_segment = segCore.vtkSegment()
tumor_segment.SetName(self.tumor_segment_name)
self.segmentation_node.GetSegmentation().AddSegment(tumor_segment)
# 配置分割编辑器使用区域生长工具
segment_editor_widget = slicer.modules.segmenteditor.widgetRepresentation().self()
segment_editor_widget.setCurrentSegmentEditorNode(self.segment_editor_node)
segment_editor_widget.setActiveEffectByName("Grow from seeds")
effect = segment_editor_widget.activeEffect()
effect.setParameter("IntensityTolerance", str(intensity_tolerance))
# 重要:在实际GUI操作中,种子点通过鼠标点击放置。
# 此处为演示,假设种子点已通过其他方式设置。
# 更自动化的方法可能需要预先将坐标转换为标记点 (Fiducial)。
print(f"[INFO] 设置肿瘤区域生长,强度容差: {intensity_tolerance}")
print(f"[INFO] 模拟种子点位置: {seed_coordinates_list}")
# effect.self().onApply() # 因种子点依赖交互,此行在此示例中注释掉
print("[INFO] 提示:请在GUI中使用‘Grow from seeds’工具,在肿瘤内部点击放置种子点,然后点击Apply。")
def create_casting_cavity_by_subtraction(self):
"""
步骤4:运用布尔减法生成浇筑腔。
原理:浇筑腔 = 皮肤 - 肿瘤。在分割逻辑中创建一个新段来代表此布尔操作的结果。
"""
import vtkSegmentationCorePython as segCore
# 创建新的段来代表浇筑腔
cavity_segment = segCore.vtkSegment()
cavity_segment.SetName(self.cavity_segment_name)
self.segmentation_node.GetSegmentation().AddSegment(cavity_segment)
# 获取皮肤和肿瘤段的ID
segmentation = self.segmentation_node.GetSegmentation()
skin_segment_id = segmentation.GetSegmentIdBySegmentName(self.skin_segment_name)
tumor_segment_id = segmentation.GetSegmentIdBySegmentName(self.tumor_segment_name)
if skin_segment_id is None or tumor_segment_id is None:
raise ValueError("未找到皮肤或肿瘤分割段,请先完成分割。")
# 配置分割编辑器进行逻辑操作
segment_editor_widget = slicer.modules.segmenteditor.widgetRepresentation().self()
segment_editor_widget.setCurrentSegmentEditorNode(self.segment_editor_node)
segment_editor_widget.setActiveEffectByName("Logical operators")
effect = segment_editor_widget.activeEffect()
# 设置操作:从皮肤中减去肿瘤
effect.setParameter("Operation", "SUBTRACT")
effect.setParameter("ModifierSegmentId”, tumor_segment_id)
# 选择当前活动段为皮肤段,操作结果将存储在新创建的浇筑腔段中
# 注意:在GUI中,需要手动在Segment列表中选择‘Skin’段,然后应用此效果。
# 以下代码模拟了参数设置,但段的选择逻辑在GUI中更直观。
print(f"[INFO] 正在执行布尔运算: {self.skin_segment_name} - {self.tumor_segment_name}")
print("[INFO] 提示:在Segment Editor中,1) 在Segment列表中选择‘Skin’。2) 在Effects中选择‘Logical operators’。3) 设置Operation为‘SUBTRACT’,Modifier Segment为‘Tumor’。4) 点击Apply。结果将生成新段‘CastingCavity’。")
# effect.self().onApply() # 由于段选择依赖GUI状态,此行在此示例中注释掉
def export_cavity_to_stl(self, output_file_path):
"""
步骤5:将布尔运算生成的浇筑腔导出为STL文件,用于3D打印。
"""
if not self.segmentation_node:
raise RuntimeError("分割节点未初始化。")
# 确保输出路径以.stl结尾
if not output_file_path.lower().endswith('.stl'):
output_file_path += '.stl'
# 设置导出参数
segmentation = self.segmentation_node.GetSegmentation()
cavity_segment_id = segmentation.GetSegmentIdBySegmentName(self.cavity_segment_name)
if cavity_segment_id is None:
raise ValueError(f"未找到名为 '{self.cavity_segment_name}' 的分割段。")
# 创建模型节点用于导出
model_node = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLModelNode")
# 将分割段转换为模型表面
success = slicer.modules.segmentations.logic().ExportSegmentToModelNode(self.segmentation_node, cavity_segment_id, model_node)
if not success:
raise RuntimeError("将分割段转换为3D模型失败。")
# 导出模型为STL
success = slicer.util.saveNode(model_node, output_file_path)
if success:
print(f"[SUCCESS] 浇筑腔STL模型已成功导出至: {output_file_path}")
else:
raise RuntimeError(f"导出STL文件失败: {output_file_path}")
# 清理临时模型节点(可选)
slicer.mrmlScene.RemoveNode(model_node)
return output_file_path
def run_full_pipeline(self, ct_file_path, output_stl_path, skin_threshold=(-200, 200)):
"""
步骤6:运行完整处理流程的封装函数。
这是一个高级接口,按顺序调用所有步骤。
注意:肿瘤分割的种子点需要用户交互,因此该步骤被标记为需手动操作。
"""
print("="*50)
print("开始 OpenClaw 完整处理流程")
print("="*50)
# 1. 加载CT
self.load_ct_volume(ct_file_path)
# 2. 初始化分割
self.setup_segmentation_workspace()
# 3. 分割皮肤 (自动)
self.segment_skin_by_threshold(skin_threshold[0], skin_threshold[1])
# 4. 分割肿瘤 (需要用户交互 - 此处为提示)
print("\n[ACTION REQUIRED] 下一步:肿瘤分割。")
print("请在3D Slicer GUI中完成以下操作:")
print(" a. 在‘Segment Editor’模块的Segment列表中,点击‘+’添加新段,命名为‘Tumor’。")
print(" b. 在二维切片视图中,滚动到肿瘤位置。")
print(" c. 在Effects中选择‘Grow from seeds’工具。")
print(" d. 在肿瘤内部多个位置点击鼠标左键,放置种子点(绿色十字)。")
print(" e. 调整‘Intensity tolerance’参数,预览生长区域。")
print(" f. 点击‘Apply’执行分割。")
print("完成后,请在Python控制台按回车继续...")
input("Press Enter to continue after manual tumor segmentation...")
# 5. 生成浇筑腔 (需要用户交互 - 此处为提示)
print("\n[ACTION REQUIRED] 下一步:生成浇筑腔(布尔减法)。")
print("请在‘Segment Editor’模块中完成以下操作:")
print(" a. 在Segment列表中,点击‘+’添加新段,命名为‘CastingCavity’。")
print(" b. 在Segment列表中,**选中‘Skin’段**。")
print(" c. 在Effects中选择‘Logical operators’工具。")
print(" d. 设置Operation为‘SUBTRACT’,Modifier Segment为‘Tumor’。")
print(" e. 点击‘Apply’。此时,‘CastingCavity’段应显示为皮肤减去肿瘤的结果。")
print("完成后,请在Python控制台按回车继续...")
input("Press Enter to continue after boolean subtraction...")
# 6. 导出STL
self.export_cavity_to_stl(output_stl_path)
print("\n" + "="*50)
print("流程完成!")
print(f"最终STL文件已保存至: {output_stl_path}")
print("="*50)
# ====== 使用示例 ======
if __name__ == "__main__":
"""
示例:如何使用 OpenClawProcessor 类。
将此脚本放在 3D Slicer 的 Python Interactor 中运行,或作为模块导入。
"""
# 初始化处理器
processor = OpenClawProcessor()
# 定义输入输出路径 (请根据实际情况修改)
ct_path = r"C:\MyData\Patient01\CT.nii.gz" # 或 DICOM 目录路径
output_path = r"C:\MyOutput\casting_cavity.stl"
try:
# 方式一:全自动运行(皮肤分割自动,肿瘤和布尔运算需手动干预)
processor.run_full_pipeline(ct_path, output_path, skin_threshold=(-150, 250))
# 方式二:分步控制(更灵活,适合集成到更大工作流)
# processor.load_ct_volume(ct_path)
# processor.setup_segmentation_workspace()
# processor.segment_skin_by_threshold(-200, 200)
# # ... 在此处进行手动肿瘤分割和布尔运算 ...
# processor.export_cavity_to_stl(output_path)
except Exception as e:
print(f"[ERROR] 流程执行失败: {e}")
import traceback
traceback.print_exc()
```
### 关键操作与注意事项
1. **手动交互部分**:该代码自动化了数据加载、皮肤分割和最终导出。然而,**肿瘤分割 (`Grow from seeds`)** 和**布尔减法 (`Logical operators`)** 这两个步骤严重依赖用户在图形界面中的交互操作(如点击放置种子点、选择操作段)。代码中通过 `print` 语句和 `input()` 暂停来引导用户。这是为了平衡自动化与分割精度要求,因为肿瘤边界通常需要人工判断 [ref_5]。
2. **参数调整**:
* **皮肤阈值 (`skin_threshold`)**:代码中默认值为 `(-200, 200)` HU。这适用于典型的软组织。**必须根据具体CT扫描协议和患者体型进行调整**。可以在 `run_full_pipeline` 函数中修改此参数。
* **肿瘤区域生长容差 (`intensity_tolerance`)**:在 `segment_tumor_by_grow_from_seeds` 函数中定义。值越小,生长越严格,可能无法覆盖整个肿瘤;值越大,可能泄露到周围组织。需要在GUI中实时调整预览。
3. **布尔运算逻辑**:浇筑腔 (`CastingCavity`) 是皮肤 (`Skin`) 减去肿瘤 (`Tumor`) 的结果。这在手术规划或定制植入物制造中很常见,用于创建容纳健康组织或填充物的空腔 [ref_3]。
4. **封装为简易软件**:`OpenClawProcessor` 类将所有功能封装在一起。可以将其保存为 `openclaw.py` 文件。在 3D Slicer 中,通过 `View -> Python Interactor` 打开控制台,使用 `exec(open(‘path/to/openclaw.py’).read())` 加载,然后创建对象并调用方法。更进一步的封装可以创建一个 Slicer 扩展模块,添加图形界面按钮和参数输入框 [ref_4]。
5. **导出与3D打印**:导出的STL文件是一个三角网格表面模型。在用于3D打印前,**务必使用专业的3D打印切片软件(如Ultimaker Cura、PrusaSlicer)检查模型**,确保其是“水密”的(无孔洞、非流形边),必要时进行修复和添加支撑 [ref_6]。
通过运行此脚本,用户可以在3D Slicer环境的引导下,高效地完成从CT数据到可3D打印的浇筑腔模型的半自动化生成流程。