Creating Histograms From Segments

I’ve been trying to follow the code found here to create a histogram from my existing MR and existing segmentation. I read on another post that I need to change the volume node and segmentation node so I have the code below, after multiple errors:

>>> volumeNode = getNode("Volume1")

>>> segmentationNode = getNode("Segmentation")

>>> segmentationNode.SetReferenceImageGeometryParameterFromVolumeNode(volumeNode)

>>> segmentID = "Segment_1"

>>> import numpy as np

>>> volumeArray = slicer.util.arrayFromVolume(volumeNode)

>>> segmentArray = arrayFromSegment(segmentationNode, segmentID)

>>> segmentVoxels = volumeArray[segmentArray != 0]

Traceback (most recent call last):

File "<console>", line 1, in <module>

IndexError: boolean index did not match indexed array along dimension 0; dimension is 112 but corresponding boolean dimension is 61

If anyone could tell me what I'm missing that would be fantastic! Unfortunately, I have no experience with python... 


You need to use

segmentArray = slicer.util.arrayFromSegmentBinaryLabelmap(segmentationNode, segmentID, volumeNode)

Using this version ensures that the segmentArray is the same size as the volumeArray of volumeNode. The error you ran into is because the segmentArray is a different size than the volumeArray, so you can’t use it to properly index into volumeArray because it is not clear what the corresponding locations are.

Thank you for your reply! When I try that, I get the following error:
Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘module’ object has no attribute ‘arrayFromSegmentBinaryLabelmap’

What version of Slicer are you using? If you upgrade to a recent preview release, that function will be present. It was also used in the example you were following (Script repository — 3D Slicer documentation). I would guess that you are using an older version of Slicer where the arrayFromSegmentBinaryLabelmap function had not been added yet.

Hi 3Dslicer community, I am trying to create a histogram from an existing segment by 3dslicer 5.2.2 and this code did not work. Your helps will be greatly appreciated.