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

DC-3T
Mon, 17 Aug 2020 08:29:34 +0000
Support

Dear all,

I hope you’re doing well. I’ve spent the last week or two struggling to convert a large number of .stl files (~1,000) drawn in 3D Slicer 4.10.2 into .nii binary label maps using Python. The .stl data were derived from segmentations drawn on Dixon MRI .nii data that I’m using as the reference volumes for the conversions. I spent some time working with the example code from the Wiki (Documentation), but with little success. Looking through the forum here I found some good tips (e.g. Load a .stl file and save it to a binary label map), and I came up with the following script:

stl_list = sys.argv[2:]  # Get list of .stl files
dixon_path = os.path.join(sys.argv[1], 'mDIXONvol.nii.gz')
dixonVolumeNode = slicer.util.loadVolume(dixon_path, returnNode=True)[1]

for stl_file_name in stl_list:
	t = time()

	# Extract abbreviated ROI name from .stl filename
	stl_name = os.path.splitext(stl_file_name.split("_")[-1])[0]

	segmentation = slicer.util.loadSegmentation(stl_file_name, returnNode=True)[1]
	ids = vtk.vtkStringArray()
	segmentation.GetDisplayNode().GetVisibleSegmentIDs(ids)

	outputLabelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLLabelMapVolumeNode')
	slicer.modules.segmentations.logic().ExportSegmentsToLabelmapNode(segmentation, ids, outputLabelmapVolumeNode, dixonVolumeNode)
	slicer.util.saveNode(outputLabelmapVolumeNode, os.path.join(cwd, stl_name + ".nii.gz"))
	print("Converted " + stl_name + ".stl to " + stl_name + ".nii in " + str(round(time() - t, 3)) + "s")
exit()

Unfortunately, this leads to blank .nii files (all zeros), which becomes apparent when I load the .nii labelmaps in the 3D Slicer GUI. I can’t figure out why this is happening. I do, however, get the following warning during processing:

CalculateOutputGeometry: No image geometry specified, default geometry is calculated (0.333381665360425;0;0;30.7908134460449;0;0.333381665360425;0;-72.2878036499023;0;0;0.333381665360425;-9.96676349639893;0;0;0;1;0;160;0;179;0;543;)

I’m not sure why this warning is appearing, given that I’m using the original reference volumes for the conversion. Could there be a coordinate system issue here? I’d really appreciate any insights you might be able to share here.

With gratitude,
Donnie

13 posts - 5 participants