Change label color using python script

Dear all,

how can I combine all the colors in the “label” image to one color using python script.

Thanks

IIbraheem

Get the image data from the labelmap volume node, and apply vtkImageThreshold filter.

Thanks Andras. I will try this. I thought there maybe an easier way by using the “ChangeLabelEffect” from the editor module.

If you want to modify labels from your own script then manipulating the voxels using numpy is probably the simplest. For example, to change all non-zero voxels to 2:

a = slicer.util.array('Output Volume-label')
a[a>0] = 2

Using the vtkImageThreshold filter would be about 5-6 lines.

If you manipulate segmentations using GUI then I would recommend to use Segment Editor module instead of the old, relatively limited Editor module.

Thanks for the tips. I think numpy is the fastest way to do this. Could you please share how to write the array back to the volume?
lb= slicer.util.getNode('input-label')
lbd = lb.GetImageData()
lbd[lbd>0] = 2
I can not find sothomig like
lb.SettImageData(lbd)

found it :grin:
I forgot to update the dispaly.
these commands are enough:
lb= slicer.util.getNode('input-label')
lb[lb>0] = 2

1 Like

Yes, if you just toggle the slice slider the update volume will show up.

But if you want to do it automatically from a script you need to inform VTK/Slicer that numpy has changed the binary data so it will render automatically.

So you need something like this to trigger a redraw

a = slicer.util.array('Output Volume-label')
a[a>0] = 2
node = slicer.util.getNode('Output Volume-label')
node.GetImageData().GetPointData().GetScalars().Modified()
node.Modified()

many thanks for the code. It helps a lot.