I’m trying to get a numpy array out of a segment or binarylabelmap and I can’t find a way to do that currently. I’m sure it’s right in front of me…
I’m just trying to use it to mask my grayscale data array so if there’s a better way to go about this I’m all ears!
What I hoped to do:
grayDataArray = arrayFromVolume(grayscaleVolume)
segmentArray = arrayFromVolume(segment) # this obviously doesn’t work
maskedData = grayDataArray * segmentArray
This works for me, if your Segmentation is named “Seg” and Volume is named “Vol”. If they are named differently, you would just change the parameters to ‘getNode’ in the first two lines
volumeNode = slicer.util.getNode('Vol') # Get the volume node
seg = slicer.util.getNode('Seg') # Get the segmentation node
# Create a binary label volume from segmentation
labelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLLabelMapVolumeNode')
#To export specific segments instead, edit the following line with the one in the bottom
slicer.modules.segmentations.logic().ExportAllSegmentsToLabelmapNode(seg, labelmapVolumeNode)
# Export data as numpy arrays
dicomData = arrayFromVolume(volumeNode)
mask = arrayFromVolume(labelmapVolumeNode)
Edit: to export specific segments instead of all of the segmentation, use the following code:
The segmentsToExport value has to be a vtkStringArray containing all the segment ID’s that you would like to be exported (note, I noticed that this overrides the label map), which is conceptually a fancy string array. To initialize it you have to run the following:
#To get the segment ID of the first segment on the list (named Segment_1 below):
segmentId = seg.GetSegmentation().GetNthSegmentID(0)
Now, I’m not entirely sure what I’m getting from this because now I have an error that the volume array (volumeNode) and the segmentation array (labelmapVolumeNode) have different sizes
The option of matching geometry is exposed in the Segmentations module GUI (specified by the “Reference volume” node), perhaps there is a corresponding API for that too, but I don’t have time to look for it now.
Sorry I’m late to respond to this.
I think your link is incorrect, it looks like the solution you’re speaking of is a bit further down. I think I found it though: