Create and overlay a segmentation on a volume

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.

Latest version of the Slicer documentation on ReadTheDocs (this is the one that is shown by default when you don’t specify a version) is for latest Slicer Preview Release. The code snippet works well for the latest Slicer Preview Release.

For older versions of the script repository, you would need to choose the corresponding version in the lower-left corner in ReadTheDocs, but since we migrated the script repository in Slicer-4.13, there are no earlier archived versions.

Therefore, you either need to update your Slicer or modify the code snippet to match the API of the Slicer version you are using. I would recommend updating your Slicer, as the new Slicer Stable Release will be out soon, which will have the same API as the latest Slicer Preview Release.

1 Like