# Automatize model generation from segmentation

**URL:** <https://discourse.slicer.org/t/automatize-model-generation-from-segmentation/35355>\
**Category:** Support\
**Tags:** segmentation, 3d-model, automation\
**Created:** [April 8, 2024, 3:33pm UTC](https://discourse.slicer.org/t/automatize-model-generation-from-segmentation/35355 "2024-04-08T15:33:28Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![MrMarkus](https://avatars.discourse-cdn.com/v4/letter/m/71e660/32.png) [@MrMarkus](https://discourse.slicer.org/u/MrMarkus)\
**Post date:** [April 29, 2024, 4:20pm UTC](https://discourse.slicer.org/t/automatize-model-generation-from-segmentation/35355/6 "2024-04-29T16:20:30Z")

</div>

Hi again,

meanwhile I discoverd similar topics, e.g.

> [@Export volume (or segment?) to stl file with python](https://discourse.slicer.org/t/export-volume-or-segment-to-stl-file-with-python/25111):
>
> Hi there, Currently I’ve been working on automating a work flow in python that goes like the following: Load CT scans (as .tiffs) Create a segmentation and threshold to identify air in the scans Automate a mouse click in a known location and use the “Remove selected island” feature Apply the “Keep largest island” feature Calculate and report statistics I’d like to add a 6th step that saves the final resulting volume as an STL file so users could easily open up a visual artifact at a later da…

and an example how to export the Model to disk:

[https://github.com/SlicerMorph/Scripts#2-run-an-image-processing-pipeline-on-a-folder-of-volumes](https://github.com/SlicerMorph/Scripts#2-run-an-image-processing-pipeline-on-a-folder-of-volumes)

One question remains on how is the order in setting up the segmentEditorWidget.  
Not sure if the code is “fine” like it is applied, because after all files in the folder  
are processed the “KEEP\_LARGEST\_ISLAND” filter is still “active” → the mouse pointer has this typical “icon”…

```auto
# Load CurrentSegmentation
    CurrentSegmentation = os.path.join(ProjectFolder, FilesInFolder[sampleIndex])
    slicer.util.loadSegmentation(CurrentSegmentation)
    segmentationNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLSegmentationNode")
    
    sampleID = segmentationNode.GetName()
    
    # storage of the segment volume 
    volumeSegment[sampleIndex][0] = sampleID 
    
    # masterVolume for segmentation
    masterVolumeNode = segmentationNode.GetNodeReference(segmentationNode.GetReferenceImageGeometryReferenceRole())
    
    # Create segment editor to get access to effects
    segmentEditorWidget = slicer.qMRMLSegmentEditorWidget()
    
    # To show segment editor widget (useful for debugging):
    # segmentEditorWidget.show()
    segmentEditorWidget.setMRMLScene(slicer.mrmlScene)
    segmentEditorNode = slicer.vtkMRMLSegmentEditorNode()
    slicer.mrmlScene.AddNode(segmentEditorNode)
    segmentEditorWidget.setMRMLSegmentEditorNode(segmentEditorNode)
    
    # actual segmentation
    segmentEditorWidget.setSegmentationNode(segmentationNode)
    segmentEditorWidget.setSourceVolumeNode(masterVolumeNode)
    
    # Visible segments will be processed
    inputSegmentIDs = vtk.vtkStringArray()
    segmentationNode.GetDisplayNode().GetVisibleSegmentIDs(inputSegmentIDs)
    
    segmentationNode.GetDisplayNode().SetSegmentVisibility(inputSegmentIDs.GetValue(2), False)
    
    # apply filter: Keep_Largest_Island / get rid of "particles"
    for index in range(inputSegmentIDs.GetNumberOfValues()-1):
        segmentID = inputSegmentIDs.GetValue(index)
        segmentEditorWidget.setCurrentSegmentID(segmentID)
        
        # Remove islands in inverted segment (these are the holes inside the segment)
        segmentEditorWidget.setActiveEffectByName("Islands")
        effect = segmentEditorWidget.activeEffect()
        effect.setParameter("Operation", "KEEP_LARGEST_ISLAND")
        effect.self().onApply()

    # prepare: Export segment -> to model
    shNode = slicer.mrmlScene.GetSubjectHierarchyNode()
    exportFolderItemId = shNode.CreateFolderItem(shNode.GetSceneItemID(), sampleID)
    slicer.modules.segmentations.logic().ExportAllSegmentsToModels(segmentationNode, exportFolderItemId)
itemList=[]
    shNode.GetItemChildren(exportFolderItemId,itemList)
    if itemList is []:
      print("Error: no model node exported for ", volumeNode.GetName())
      continue
    
    # export skull = Segment_1
    modelNode = shNode.GetItemDataNode(itemList[0])
    # Decimate the model 80%
    slicer.modules.SurfaceToolboxWidget.logic.decimate(modelNode, modelNode, 0.8)
    slicer.util.saveNode(modelNode, plyFilePathSkull)

  # Delete temporary segment editor
    slicer.mrmlScene.RemoveNode(segmentEditorNode)
    del segmentEditorWidget

  slicer.mrmlScene.Clear(0) # EMPTY scene

```

Maybe one could comment on the lines above.

THANKS!

Best,  
Markus

---

_[View the full topic](https://discourse.slicer.org/t/automatize-model-generation-from-segmentation/35355)._
