|
""" |
|
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: |
|
|
|
|
|
|
|
print(f'Conversion failed: {im}') |
|
continue |
|
|