opencv使用滑条选择最佳加窗值(windowing:WW, WL)

1.1、 本文介绍医学影像CT的DICOM文件的窗宽(Window Width,简写WW)窗位(Window Level,简写WL)与CT值(HU)的关系。

 比如 WW = 400,WL = 60,那么对应的CT(HU)范围为-140 ~ 260H ,即

WW = ( 260 - (-140) )= 400

WL = (260 + (-140))/ 2 =60

就是怎么计算而来的。

1.2、医学影像CT上,不同的部位比如心脏、骨组织,往往显示的是黑白色(即灰度),我们常常用合适范围的灰度值,来观察不同的CT效果。
opencv使用滑条选择最佳加窗值(windowing:WW, WL)_第1张图片

import numpy as np
import cv2
import matplotlib.pyplot as plt
import SimpleITK as itk
import skimage.io as io
import sys, os 


nii_file = r'./Naso_GTV//train/1/data.nii.gz'
itk_img = itk.ReadImage(nii_file)
itk_hu_data = itk.GetArrayFromImage(itk_img)  # == img.get_fdata(), Hu data

def _img_transfor(itk_img, WW, WL):
    img_arr = itk.GetArrayFromImage(itk_img).astype(np.float32)
    img_arr = window_normalize(img_arr, WW, WL)
    # torch_itk = torch.from_numpy(img_arr)
    return img_arr

def window_normalize(img, WW, WL, dst_range=(0, 1)):
    """
    WW: window width
    WL: window level
    dst_range: normalization range
    """
    src_min = WL - WW/2
    src_max = WL + WW/2
    outputs = (img - src_min)/WW * (dst_range[1] - dst_range[0]) + dst_range[0]
    outputs[img >= src_max] = 1
    outputs[img <= src_min] = 0
    return outputs * 255


# 创建窗口
cv2.namedWindow('windowing')
value = (0, 0)
def update(x):
    # 回调函数 更新value的值
    global value
    WW_value = cv2.getTrackbarPos('WW', 'windowing')
    WL_value = cv2.getTrackbarPos('WL', 'windowing')

    value = (WW_value - 1024, WL_value - 1024)

    img = _img_transfor(itk_img, WW_value - 1024, WL_value - 1024)
    io.imsave("./io.png", img[83])
    png = cv2.imread("./io.png")
    cv2.imshow("windowing", png)

    print('Update Value, value ={}'.format(value))

cv2.createTrackbar('WW','windowing',0,2048,update)
cv2.createTrackbar('WL','windowing',0,2048,update)

cv2.setTrackbarPos('WW','windowing',350 + 1024)
cv2.setTrackbarPos('WL','windowing',40 + 1024)

while(1):       
    # 等待按键按下
    k = cv2.waitKey(0)
    # 销毁窗口
    if k == 27:
        cv2.destroyAllWindows()
        break

opencv使用滑条选择最佳加窗值(windowing:WW, WL)_第2张图片opencv使用滑条选择最佳加窗值(windowing:WW, WL)_第3张图片

你可能感兴趣的:(opencv使用滑条选择最佳加窗值(windowing:WW, WL))