Hi Diana,
I did something similar for my data. Assuming you start with a Volume node named âinputVolumeNodeâ and draw a segmentation ROI on it (default name âSegmentationâ) the following code should do it for you. Caveat: You need the latest nightly build of slicer to draw the plot :
import SimpleITK as sitk
import sitkUtils
import numpy as np
newScalarNode = slicer.mrmlScene.AddNewNodeByClass(âvtkMRMLScalarVolumeNodeâ) #to be used later
seg = getNode(âSegmentationâ)
#create a temporary labelmap
labelMapNode = slicer.mrmlScene.AddNewNodeByClass(âvtkMRMLLabelMapVolumeNodeâ)
#using reference volume will match the geometry
ids = vtk.vtkStringArray()
seg.GetSegmentation().GetSegmentIDs(ids)
slicer.modules.segmentations.logic().ExportSegmentsToLabelmapNode(seg,ids,labelMapNode,inputVolumeNode)
mif = sitk.MaskImageFilter()
mif.SetOutsideValue(-1234) #custom dummy value thatâs recognizable
roiSITK = sitkUtils.PullVolumeFromSlicer(inputVolumeNode)
maskSITK = sitkUtils.PullVolumeFromSlicer(labelMapNode)
final = mif.Execute(roiSITK,maskSITK)
sitkUtils.PushVolumeToSlicer(final,newScalarNode)
#creating histogram <-------------- from this onwards the code is from slicer scripts webpage
np_tmp = arrayFromVolume(newScalarNode)
np_tmp=np_tmp[np_tmp!=-1234] # flattens the array and removes selected outside label values
histogram = np.histogram(np_tmp, bins=50)
#Save results to a new table node
tableNode=slicer.mrmlScene.AddNewNodeByClass(âvtkMRMLTableNodeâ)
updateTableFromArray(tableNode, histogram)
tableNode.GetTable().GetColumn(0).SetName(âCountâ)
tableNode.GetTable().GetColumn(1).SetName(âIntensityâ)
#Create plot ------ DOES NOT EXIST ON PRE VERSION 4.9 !
plotSeriesNode = slicer.mrmlScene.AddNewNodeByClass(âvtkMRMLPlotSeriesNodeâ, newScalarNode.GetName() + â histogramâ)
plotSeriesNode.SetAndObserveTableNodeID(tableNode.GetID())
plotSeriesNode.SetXColumnName(âIntensityâ)
plotSeriesNode.SetYColumnName(âCountâ)
plotSeriesNode.SetPlotType(plotSeriesNode.PlotTypeScatterBar)
plotSeriesNode.SetColor(0, 0.6, 1.0)
#Create chart and add plot
plotChartNode = slicer.mrmlScene.AddNewNodeByClass(âvtkMRMLPlotChartNodeâ)
plotChartNode.AddAndObservePlotSeriesNodeID(plotSeriesNode.GetID())
plotChartNode.YAxisRangeAutoOff()
plotChartNode.SetYAxisRange(0, 500000)
#Show plot in layout
slicer.modules.plots.logic().ShowChartInLayout(plotChartNode)