DeepLesion / scripts /apply_window.py
farrell236's picture
update scripts
4021c62
"""
Apply CT windowing parameter from DL_info.csv to Images_png
"""
import os
import cv2
import numpy as np
import pandas as pd
from glob import glob
from tqdm import tqdm
dir_in = '../Images_png'
dir_out = '../Images_png_wn'
info_fn = '../DL_info.csv'
if not os.path.exists(dir_out):
os.mkdir(dir_out)
dl_info = pd.read_csv(info_fn)
def clip_and_normalize(np_image: np.ndarray,
clip_min: int = -150,
clip_max: int = 250
) -> np.ndarray:
np_image = np.clip(np_image, clip_min, clip_max)
np_image = (np_image - clip_min) / (clip_max - clip_min)
return np_image
for idx, row in tqdm(dl_info.iterrows(), total=len(dl_info)):
folder = row['File_name'].rsplit('_', 1)[0]
images = sorted(glob(f'{dir_in}/{folder}/*.png'))
if not os.path.exists(f'{dir_out}/{folder}'):
os.mkdir(f'{dir_out}/{folder}')
DICOM_windows = [float(value.strip()) for value in row['DICOM_windows'].split(',')]
for im in images:
try:
image = cv2.imread(im, cv2.IMREAD_UNCHANGED)
image = image.astype('int32') - 32768
image = clip_and_normalize(image, *DICOM_windows)
image = (image*255).astype('uint8')
cv2.imwrite(f'{dir_out}/{folder}/{os.path.basename(im)}', image)
except AttributeError:
# Broken Images
# 001821_07_01/372.png
# 002161_04_02/116.png
print(f'Conversion failed: {im}')
continue