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:

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.UpdateWindowLevelFromRectangle(0, [60,60], [45,45])
1 Like