Last active
August 1, 2023 14:06
-
-
Save jpeoples/2ea7cda162a86c984534667956190ffc to your computer and use it in GitHub Desktop.
Applying windowing to SimpleITK images.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SimpleITK as sitk | |
def wl_to_range(wl): | |
"""Convert window, level, to range""" | |
w, l = wl | |
lower, upper = l-w/2, l+w/2 | |
return lower, upper | |
def remap_range(img, range): | |
"""Remap image intensities so that the range is transformed to [0,1]""" | |
l, u = range | |
img = (img-l)/(u-l) | |
return img | |
def clamp(img, range=(0,1)): | |
"""Clamp intensities in img to range""" | |
arr = sitk.GetArrayFromImage(img) | |
arr[arr < range[0]] = range[0] | |
arr[arr > range[1]] = range[1] | |
out = sitk.GetImageFromArray(arr) | |
out.CopyInformation(img) | |
return out | |
def apply_window_level(img, wl): | |
"""Apply a window to an image, such that intensities in the range are mapped [0,1] and anything outside is clamped""" | |
range = wl_to_range(wl) | |
img = remap_range(img, range) | |
img = clamp(img, (0,1)) | |
return img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment