File size: 1,834 Bytes
82fc2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94ce97c
82fc2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94ce97c
 
82fc2b1
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
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 = '/path/to/DeepLesion/Images_png'
dir_out = './Keyslices_1bbox'
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


def draw_bounding_box(image, bbox):
    if len(image.shape) == 2:
        image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    x1, y1, x2, y2 = bbox
    cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
    return image


# import matplotlib.pyplot as plt

for idx, row in tqdm(dl_info.iterrows(), total=len(dl_info)):

    folder, filename = row['File_name'].rsplit('_', 1)
    image_file = f'{dir_in}/{folder}/{filename}'

    DICOM_windows = [float(value.strip()) for value in row['DICOM_windows'].split(',')]
    bbox = [int(float(value.strip())) for value in row['Bounding_boxes'].split(',')]

    try:
        image = cv2.imread(image_file, cv2.IMREAD_UNCHANGED)
        image = image.astype('int32') - 32768
        image = clip_and_normalize(image, *DICOM_windows)
        image = (image * 255).astype('uint8')
        image = draw_bounding_box(image, bbox)

        # plt.imshow(image)
        # plt.show()

        cv2.imwrite(f'{dir_out}/lesion_{idx}.png', image)

    except AttributeError:
        # Broken Images
        # 001821_07_01/372.png
        # 002161_04_02/116.png
        print(f'Conversion failed: {image_file}')
        continue