How to change window/level programmatically

Hi Andras, how could I set the window/level region programmatically, and apply the optimal window/level afterwards?

See example in script repository: https://www.slicer.org/wiki/Documentation/Nightly/ScriptRepository#Change_window.2Flevel_.28brightness.2Fcontrast.29_or_colormap_of_a_volume

Yes, I knew that example, but what I wanted is to auto window/level using a selected region, just like when we press ‘Ctrl’ and drag the mouse.

The logic is implemented in vtkImageHistogramStatistics. If you don’t want to use GUI then you can use that class directly from your scripts. You can have a look at the window/level widget’s source code as an example how it is used there.

1 Like

The code snippet for anyone that might be interested (selecting a rectangle at the specified positions on the background of the Green slice viewer and applying Window Level):

widget = slicer.vtkMRMLWindowLevelWidget()
widget.SetSliceNode(getNode('vtkMRMLSliceNodeGreen'))
widget.SetMRMLApplicationLogic(slicer.app.applicationLogic())
widget.UpdateWindowLevelFromRectangle(0, [60,60], [45,45])