Run Export To Files in the Segmentations Module from a script

I’d like to run the Export To Files functionality in the Segmentations Module from a slicer module I am developing. When running this, I need to be able to pass in the destination folder and the file format (nii.gz).

Does anyone know how to do this please?

This works (found here: Script repository — 3D Slicer documentation):

outputPath = "c:/tmp"

def exportLabelmap():
  segmentationNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLSegmentationNode")
  referenceVolumeNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLScalarVolumeNode")
  labelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLLabelMapVolumeNode")
  slicer.modules.segmentations.logic().ExportVisibleSegmentsToLabelmapNode(segmentationNode, labelmapVolumeNode, referenceVolumeNode)
  filepath = outputPath + "/" + referenceVolumeNode.GetName() + "-label.nrrd"
  slicer.util.saveNode(labelmapVolumeNode, filepath)
  slicer.mrmlScene.RemoveNode(labelmapVolumeNode.GetDisplayNode().GetColorNode())
  slicer.mrmlScene.RemoveNode(labelmapVolumeNode)
  slicer.util.delayDisplay("Segmentation saved to " + filepath)

shortcut = qt.QShortcut(slicer.util.mainWindow())
shortcut.setKey(qt.QKeySequence("Ctrl+Shift+s"))
shortcut.connect( "activated()", exportLabelmap)

1 Like

For saving a scalar volume this should work, assuming you have a yourScalarVolumeNode:

tempDir = slicer.app.temporaryPath + "/Test/"
myStorageNode=yourScalarVolume.CreateDefaultStorageNode()
myStorageNode.SetFileName(tempDir+"test.nii.gz")
myStorageNode.WriteData(yourScalarVolume)