This script creates 3 segments by thresholding each channel, displays the segmentation in 3D, and displays the 3 channels as an RGB image:
# Inputs
filename = r"c:\Users\andra\OneDrive\Projects\SlicerTesting2022\20220222-Confocal\RGB STACK2.tif"
channelThresholds = [20, 30, 40]
# Install scikit-image
try:
import skimage
except:
pip_install('scikit-image')
from skimage import io
import numpy as np
# Read the image into numpy array
im = io.imread(filename)
# Create segments by thresholding each channel
# Create temporary labelmap volume node (it will store the thresholded image that will be imported into the segmentation)
tempLabelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLLabelMapVolumeNode")
tempLabelmapVolumeNode.CreateDefaultDisplayNodes()
# Do not set a color node ID. This will make segment names set based on the labelmap volume's name (instead of looking up the segment name in the color node)
tempLabelmapVolumeNode.GetDisplayNode().SetAndObserveColorNodeID("")
segmentationNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLSegmentationNode")
for component in range(im.shape[3]):
componentImage = im[:,:,:,component]
componentThreshold = channelThresholds[component]
thresholdedComponentImage = np.zeros(componentImage.shape)
thresholdedComponentImage[componentImage > componentThreshold] = 1
tempLabelmapVolumeNode.SetName(f"Component-{component}") # the volume node's name will be used as segment name
slicer.util.updateVolumeFromArray(tempLabelmapVolumeNode, thresholdedComponentImage)
slicer.modules.segmentations.logic().ImportLabelmapToSegmentationNode(tempLabelmapVolumeNode, segmentationNode)
slicer.mrmlScene.RemoveNode(tempLabelmapVolumeNode)
# Show segmentation in 3D
segmentationNode.CreateClosedSurfaceRepresentation()
segmentationNode.GetDisplayNode().SetOpacity(0.6)
# Show the image as an RGB volume in slice views
volumeNodeRGB = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLVectorVolumeNode", "image-rgb")
slicer.util.updateVolumeFromArray(volumeNodeRGB, im)
slicer.util.setSliceViewerLayers(background=volumeNodeRGB, fit=True)