Created
March 29, 2016 02:20
-
-
Save louismullie/ea9123c42f44bb646b50 to your computer and use it in GitHub Desktop.
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
def window_level(arr, window_center, window_width, lut_min=0, lut_max=255): | |
# Basic sanity checking. | |
if np.isreal(arr).sum() != arr.size: raise ValueError | |
if lut_max != 255: raise ValueError | |
if arr.dtype != np.float64: arr = arr.astype(np.float64) | |
# Get window information. | |
window_width = max(1, window_width) | |
wc, ww = np.float64(window_center), np.float64(window_width) | |
lut_range = np.float64(lut_max) - lut_min | |
# Transform the image. | |
minval = wc - 0.5 - (ww - 1.0) / 2.0 | |
maxval = wc - 0.5 + (ww - 1.0) / 2.0 | |
min_mask = (minval >= arr) | |
to_scale = (arr > minval) & (arr < maxval) | |
max_mask = (arr >= maxval) | |
if min_mask.any(): arr[min_mask] = lut_min | |
# Scale the image to the right proportions. | |
if to_scale.any(): arr[to_scale] = \ | |
((arr[to_scale] - (wc - 0.5)) / | |
(ww - 1.0) + 0.5) * lut_range + lut_min | |
if max_mask.any(): arr[max_mask] = lut_max | |
arr = np.rint(arr).astype(np.uint8) | |
return arr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment