Converting .stl files to binary label maps in .nii format using Python

Thanks very much for the code. I gave it a try, and I’m still getting the following message: “CalculateOutputGeometry: No image geometry specified, default geometry is calculated”. The output volume is still just an array of zeros as well. I’m not sure why this happens, and I’ve confirmed that the reference volumes and models are all loaded correctly…

I was, however, able to get the example code from the script repository to work in Slicer 4.11, after some modifications. Here is my working code:

referenceVolumeNode = slicer.util.loadVolume(ref_volume)
inputModel = slicer.util.loadModel(stl_file)

# Convert model to labelmap
seg = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLSegmentationNode')
seg.SetReferenceImageGeometryParameterFromVolumeNode(referenceVolumeNode)
slicer.modules.segmentations.logic().ImportModelToSegmentationNode(inputModel, seg)
seg.CreateBinaryLabelmapRepresentation()
outputLabelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLLabelMapVolumeNode')
slicer.modules.segmentations.logic().ExportVisibleSegmentsToLabelmapNode(seg, outputLabelmapVolumeNode, referenceVolumeNode)

# Set image directions to correct flip L-R issue
imageDirections = [[-1,0,0], [0,1,0], [0,0,1]] 
outputLabelmapVolumeNode.SetIJKToRASDirections(imageDirections)
	
slicer.util.saveNode(outputLabelmapVolumeNode, "seg.nii.gz"))

Aside from the unexpected left-right flip, which I’ve corrected here, the code works like a charm. Thanks very much for your help!