I want to apply a threshold value on an image and overlay this threshold result as a segmentation (or labelmap) on the image.
Based on a sample in script repository I tried to do it this way:
threshold = 500
#getting volume node and its image as array
volumeNode = slicer.util.getNode("volume")
volumeNode_array = slicer.util.arrayFromVolume(volumeNode)
#creating new segmentation node and segment and set its reference image geometry to volume node
segmentationNode = slicer.vtkMRMLSegmentationNode()
slicer.mrmlScene.AddNode(segmentationNode)
segmentationNode.CreateDefaultDisplayNodes()
segmentationNode.SetReferenceImageGeometryParameterFromVolumeNode(volumeNode)
segmentationNode.GetSegmentation().AddEmptySegment()
segmentId = segmentationNode.GetSegmentation().GetSegmentIdBySegmentName('Segment_1')
#get the array of segmentation, update its values and refresh the segmentatin
segmentArray = slicer.util.arrayFromSegmentBinaryLabelmap(segmentationNode, segmentId, volumeNode)
segmentArray[:] = 0
segmentArray[volumeNode_array > threshold] = 1
slicer.util.updateSegmentBinaryLabelmapFromArray(segmentArray, segmentationNode, segmentId, volumeNode)
this returns this error:
segmentArray = slicer.util.arrayFromSegmentBinaryLabelmap(segmentationNode, segmentId, volumeNode)
TypeError: arrayFromSegmentBinaryLabelmap() takes 2 positional arguments but 3 were given
I see in the documentation though this function can take 3 arguments, the last one is reference volume:
referenceVolumeNode: a volume node that determines geometry (origin, spacing, axis directions, extents) of the array.
It is also stated that:
If not specified then the volume that was used for setting the segmentation's geometry is used as for the reference volume.
since I’m setting the reference image geometry upper in code, if I don’t pass the referenceVolumeNode I will get this error:
segmentArray[volumeNode_array > threshold] = 1
IndexError: boolean index did not match indexed array along dimension 0; dimension is 0 but corresponding boolean dimension is 135
I appreciate any ideas in this regard.