Unable to export segment with ExportSegmentsClosedSurfaceRepresentationToFiles

Hi,

I have been using the code snippet below to export large amounts of segmentations to .stl format.

segmentation = slicer.util.loadSegmentation(seg)
vol = slicer.util.loadVolume(mag)
    
volumeNode = slicer.util.getNode('*magnitude*')  # Get the volume node  
segNode = slicer.util.getNode('*Segment*')
    slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsClosedSurfaceRepresentationToFiles(out, segNode, None, "STL", False, 0.001, False)
    
slicer.mrmlScene.RemoveNode(volumeNode)
slicer.mrmlScene.RemoveNode(segmentation)

I don’t know why when I’m trying the same code to export a new dataset I’m getting the following error.

TypeError: ExportSegmentsClosedSurfaceRepresentationToFiles argument 2: method requires a vtkMRMLSegmentationNode, a vtkMRMLSegmentationStorageNode was provided.

Kind regards,
Xabier

It seems that this returns the wrong node (the segmentation storage node instead of the segmentation node itself). I suggest using a more robust way to get the node.

Is there a way of getting the first segment following the order displayed in the GUI?

Here is my working code:

nii_pathname =  ...   
seg = slicer.util.loadSegmentation(nii_pathname)
segmentationNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLSegmentationNode")
slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsClosedSurfaceRepresentationToFiles(out, segmentationNode, None, "STL")
slicer.mrmlScene.RemoveNode(segmentationNode)
slicer.mrmlScene.RemoveNode(seg)

I don’t know why using the function “GetFirstNodeByClass” works, but it does meet the need.

1 Like

slicer.util.getNode('*Segment*') returns the first node in the scene that contains Segment in its name or ID (including all the hidden nodes). There can be many nodes like that in the scene: the segmentation node, the segmentation display node, and segmentation storage node. getNode helper function (especially when it is used with wildcards as input) is only recommended for quick testing and troubleshooting.

If you specify the kind of node you are looking for (vtkMRMLSegmentationNode) and you only have one node of that type in the scene then the result is always as you expect.