File size: 15,279 Bytes
5919b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""
Image normalization utilities for MedVision visualization.

Copied and adapted from:
  - medvision_bm/utils/configs.py  (label_map_regroup, CT_HU_windows_WL,
                                     TASK_LIST_FORCE_STANDARD_IMAGE_NORMALIZATION)
  - medvision_bm/sft/sft_utils.py  (normalize_ct_img, normalize_general_img,
                                     normalize_img)
"""

import numpy as np


# ---------------------------------------------------------------------------
# Tasks that must use standard (percentile) normalization even for CT images.
# Mainly designed to skip HU-based normalization for contrast CT scans (e.g. KiPA22).
# Source: medvision_bm/utils/configs.py — TASK_LIST_FORCE_STANDARD_IMAGE_NORMALIZATION
# ---------------------------------------------------------------------------
TASK_LIST_FORCE_STANDARD_IMAGE_NORMALIZATION = [
    {"dataset_name": "KiPA22", "taskID": "01", "taskType": "Tumor-Lesion-Size"},
    {"dataset_name": "KiPA22", "taskID": "01", "taskType": "Box-Size"},
    {"dataset_name": "KiPA22", "taskID": "01", "taskType": "Mask-Size"},
]


# ---------------------------------------------------------------------------
# HU window presets (width, level).
# Source: medvision_bm/utils/configs.py — HU_window_WL_map
# ---------------------------------------------------------------------------
_HU_WINDOW_WL_MAP = {
    "soft_tissue": (400, 40),
    "lung":        (1500, -600),
    "brain":       (80, 40),
    "bone":        (1800, 400),
}

# Per-anatomy-group HU window assignments.
# Source: medvision_bm/utils/configs.py — CT_HU_windows_WL
CT_HU_WINDOWS_WL = {
    "Artery":                    _HU_WINDOW_WL_MAP["soft_tissue"],
    "Vein":                      _HU_WINDOW_WL_MAP["soft_tissue"],
    "Brain":                     _HU_WINDOW_WL_MAP["brain"],
    "Brain Tumor/Lesion":        _HU_WINDOW_WL_MAP["brain"],
    "Heart":                     _HU_WINDOW_WL_MAP["soft_tissue"],
    "Lung":                      _HU_WINDOW_WL_MAP["lung"],
    "Lung Tumor/Lesion":         _HU_WINDOW_WL_MAP["lung"],
    "Liver":                     _HU_WINDOW_WL_MAP["soft_tissue"],
    "Liver Tumor/Lesion":        _HU_WINDOW_WL_MAP["soft_tissue"],
    "Kidney":                    _HU_WINDOW_WL_MAP["soft_tissue"],
    "Kidney Tumor/Lesion":       _HU_WINDOW_WL_MAP["soft_tissue"],
    "Pancreas":                  _HU_WINDOW_WL_MAP["soft_tissue"],
    "Pancreas Tumor/Lesion":     _HU_WINDOW_WL_MAP["soft_tissue"],
    "Gallbladder":               _HU_WINDOW_WL_MAP["soft_tissue"],
    "Spleen":                    _HU_WINDOW_WL_MAP["soft_tissue"],
    "Adrenal Gland":             _HU_WINDOW_WL_MAP["soft_tissue"],
    "Colon":                     _HU_WINDOW_WL_MAP["soft_tissue"],
    "Colon Tumor/Lesion":        _HU_WINDOW_WL_MAP["soft_tissue"],
    "Intestine":                 _HU_WINDOW_WL_MAP["soft_tissue"],
    "Esophagus":                 _HU_WINDOW_WL_MAP["soft_tissue"],
    "Stomach":                   _HU_WINDOW_WL_MAP["soft_tissue"],
    "Urinary System":            _HU_WINDOW_WL_MAP["soft_tissue"],
    "Uterus":                    _HU_WINDOW_WL_MAP["soft_tissue"],
    "Prostate":                  _HU_WINDOW_WL_MAP["soft_tissue"],
    "Head-Neck":                 _HU_WINDOW_WL_MAP["soft_tissue"],
    "Head-Neck Tumor/Lesion":    _HU_WINDOW_WL_MAP["soft_tissue"],
    "Hip":                       _HU_WINDOW_WL_MAP["bone"],
    "Rib":                       _HU_WINDOW_WL_MAP["bone"],
    "Spine":                     _HU_WINDOW_WL_MAP["bone"],
    "Knee Bone":                 _HU_WINDOW_WL_MAP["bone"],
    "Knee Soft Tissue":          _HU_WINDOW_WL_MAP["soft_tissue"],
    "Metastatic Lymph Node":     _HU_WINDOW_WL_MAP["soft_tissue"],
    "Miscellaneous Tumor/Lesion":_HU_WINDOW_WL_MAP["soft_tissue"],
    "Jawbone":                   _HU_WINDOW_WL_MAP["bone"],
    "Tooth":                     _HU_WINDOW_WL_MAP["bone"],
}


# ---------------------------------------------------------------------------
# Maps fine-grained label names to anatomy groups used for HU-window lookup.
# Source: medvision_bm/utils/configs.py — label_map_regroup
# ---------------------------------------------------------------------------
LABEL_MAP_REGROUP = {
    # vasculature
    "aorta": "Artery",
    "anterior communicating artery": "Artery",
    "basilar artery": "Artery",
    "left iliac artery": "Artery",
    "left anterior cerebral artery": "Artery",
    "left common carotid artery": "Artery",
    "left internal carotid artery": "Artery",
    "left middle cerebral artery": "Artery",
    "left posterior cerebral artery": "Artery",
    "left posterior communicating artery": "Artery",
    "left subclavian artery": "Artery",
    "renal artery": "Artery",
    "right iliac artery": "Artery",
    "right anterior cerebral artery": "Artery",
    "right common carotid artery": "Artery",
    "right internal carotid artery": "Artery",
    "right middle cerebral artery": "Artery",
    "right posterior cerebral artery": "Artery",
    "right posterior communicating artery": "Artery",
    "right subclavian artery": "Artery",
    "third a2 segment": "Artery",
    "brachiocephalic trunk": "Artery",
    "superior vena cava": "Vein",
    "inferior vena cava": "Vein",
    "inferior vena cava (ivc)": "Vein",
    "postcava": "Vein",
    "postcava (inferior vena cava)": "Vein",
    "portal and splenic veins": "Vein",
    "portal vein and splenic vein": "Vein",
    "left brachiocephalic vein": "Vein",
    "right brachiocephalic vein": "Vein",
    "left iliac vein": "Vein",
    "right iliac vein": "Vein",
    "renal vein": "Vein",
    # brain
    "brain": "Brain",
    "skull": "Brain",
    "anterior hippocampus": "Brain",
    "posterior hippocampus": "Brain",
    "deep grey matter": "Brain",
    "grey matter": "Brain",
    "white matter": "Brain",
    "brainstem": "Brain",
    "cerebellum": "Brain",
    "ventricles": "Brain",
    "external cerebrospinal fluid": "Brain",
    "stroke infarct": "Brain Tumor/Lesion",
    "peritumoral edema of brain": "Brain Tumor/Lesion",
    "edema of brain": "Brain Tumor/Lesion",
    "surrounding non-enhancing flair hyperintensity of brain": "Brain Tumor/Lesion",
    "resection cavity of brain": "Brain Tumor/Lesion",
    "enhancing brain tumor": "Brain Tumor/Lesion",
    "enhancing brain tumor tissue": "Brain Tumor/Lesion",
    "non-enhancing brain tumor": "Brain Tumor/Lesion",
    "non-enhancing brain tumor core": "Brain Tumor/Lesion",
    "gross tumor volume of brain": "Brain Tumor/Lesion",
    "cystic component of brain": "Brain Tumor/Lesion",
    # heart
    "heart": "Heart",
    "left atrium": "Heart",
    "left atrium of heart": "Heart",
    "left atrial appendage": "Heart",
    "left ventricular cavity": "Heart",
    "left ventricular myocardium": "Heart",
    "left ventricle": "Heart",
    "right ventricular cavity": "Heart",
    "myocardium": "Heart",
    # lungs
    "left lung": "Lung",
    "left lung lower lobe": "Lung",
    "left lung upper lobe": "Lung",
    "right lung": "Lung",
    "right lung lower lobe": "Lung",
    "right lung middle lobe": "Lung",
    "right lung upper lobe": "Lung",
    "lung cancer": "Lung Tumor/Lesion",
    # liver
    "liver": "Liver",
    "liver vessel": "Liver",
    "liver cancer": "Liver Tumor/Lesion",
    "liver tumour": "Liver Tumor/Lesion",
    "liver tumor": "Liver Tumor/Lesion",
    # kidneys
    "kidney": "Kidney",
    "right kidney": "Kidney",
    "left kidney": "Kidney",
    "kidney cyst": "Kidney Tumor/Lesion",
    "left kidney cyst": "Kidney Tumor/Lesion",
    "right kidney cyst": "Kidney Tumor/Lesion",
    "kidney tumor": "Kidney Tumor/Lesion",
    # pancreas
    "pancreas": "Pancreas",
    "pancreas cancer": "Pancreas Tumor/Lesion",
    # gallbladder
    "gall bladder": "Gallbladder",
    "gallbladder": "Gallbladder",
    # spleen
    "spleen": "Spleen",
    # adrenal glands
    "adrenal gland": "Adrenal Gland",
    "left adrenal gland": "Adrenal Gland",
    "left adrenal gland (lag)": "Adrenal Gland",
    "right adrenal gland": "Adrenal Gland",
    "right adrenal gland (rag)": "Adrenal Gland",
    # colon
    "colon": "Colon",
    "colon cancer primaries": "Colon Tumor/Lesion",
    # intestines
    "rectum": "Intestine",
    "duodenum": "Intestine",
    "small bowel": "Intestine",
    "esophagus": "Esophagus",
    # stomach
    "stomach": "Stomach",
    # uro-gynae
    "urinary bladder": "Urinary System",
    "bladder": "Urinary System",
    "uterus": "Uterus",
    "prostate": "Prostate",
    "peripheral zone of prostate": "Prostate",
    "transition zone of prostate": "Prostate",
    # head & neck
    "cochlea": "Head-Neck",
    "trachea": "Head-Neck",
    "pharynx": "Head-Neck",
    "thyroid gland": "Head-Neck",
    "primary gross tumor volume (head & neck)": "Head-Neck Tumor/Lesion",
    "vestibular schwannoma": "Head-Neck Tumor/Lesion",
    # musculoskeletal — hip
    "left hip": "Hip",
    "right hip": "Hip",
    "sacrum": "Hip",
    "left gluteus maximus": "Hip",
    "left gluteus medius": "Hip",
    "left gluteus minimus": "Hip",
    "right gluteus maximus": "Hip",
    "right gluteus medius": "Hip",
    "right gluteus minimus": "Hip",
    "right iliopsoas": "Hip",
    "left iliopsoas": "Hip",
    # ribs
    "left 1st rib": "Rib",
    "left 2nd rib": "Rib",
    "left 3rd rib": "Rib",
    "right 1st rib": "Rib",
    "right 2nd rib": "Rib",
    "right 3rd rib": "Rib",
    **{f"{side} {n}th rib": "Rib" for side in ("left", "right") for n in range(4, 13)},
    "costal cartilages": "Rib",
    # spine
    **{
        f"vertebra {lvl}": "Spine"
        for lvl in (
            "C1", "C2", "C3", "C4", "C5", "C6", "C7",
            "T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8", "T9", "T10", "T11", "T12",
            "L1", "L2", "L3", "L4", "L5", "S1",
        )
    },
    "vertebrae": "Spine",
    "intervertebral discs": "Spine",
    "spinal cord": "Spine",
    # knee
    "femur": "Knee Bone",
    "tibia": "Knee Bone",
    "left femur": "Knee Bone",
    "right femur": "Knee Bone",
    "femoral cartilage": "Knee Soft Tissue",
    "lateral tibial cartilage": "Knee Soft Tissue",
    "medial tibial cartilage": "Knee Soft Tissue",
    "patellar cartilage": "Knee Soft Tissue",
    "lateral meniscus": "Knee Soft Tissue",
    "medial meniscus": "Knee Soft Tissue",
    # lymphatics
    "metastatic lymph node": "Metastatic Lymph Node",
    # miscellaneous
    "edema": "Miscellaneous Tumor/Lesion",
    "tumor": "Miscellaneous Tumor/Lesion",
    "cystic component": "Miscellaneous Tumor/Lesion",
    # dentistry
    "upper jawbone": "Jawbone",
    "lower jawbone": "Jawbone",
    "left inferior alveolar canal": "Jawbone",
    "right inferior alveolar canal": "Jawbone",
    **{t: "Tooth" for t in [
        "upper left canine", "upper left central incisor", "upper left lateral incisor",
        "upper left first premolar", "upper left second premolar",
        "upper left first molar", "upper left second molar",
        "upper left third molar (wisdom tooth)",
        "upper right canine", "upper right central incisor", "upper right lateral incisor",
        "upper right first premolar", "upper right second premolar",
        "upper right first molar", "upper right second molar",
        "upper right third molar (wisdom tooth)",
        "lower left canine", "lower left central incisor", "lower left lateral incisor",
        "lower left first premolar", "lower left second premolar",
        "lower left first molar", "lower left second molar",
        "lower left third molar (wisdom tooth)",
        "lower right canine", "lower right central incisor", "lower right lateral incisor",
        "lower right first premolar", "lower right second premolar",
        "lower right first molar", "lower right second molar",
        "lower right third molar (wisdom tooth)",
    ]},
    # catch-alls
    "na": "Others",
    "implant": "Others",
    "crown": "Others",
    "bridge": "Others",
    "left autochthon": "Others",
    "right autochthon": "Others",
    "sternum": "Others",
    "humerus": "Others",
    "left humerus": "Others",
    "right humerus": "Others",
    "left clavicle": "Others",
    "right clavicle": "Others",
    "left scapula": "Others",
    "right scapula": "Others",
    "prostate/uterus": "Others",
}


# ---------------------------------------------------------------------------
# Core normalization functions.
# Source: medvision_bm/sft/sft_utils.py
# ---------------------------------------------------------------------------

def normalize_ct_img(img, window_width, window_level):
    """Normalize CT Hounsfield Units to [0, 255] using a W/L window."""
    v_min = window_level - (window_width / 2)
    v_max = window_level + (window_width / 2)
    img_normalized = np.clip(img, v_min, v_max)
    img_normalized = ((img_normalized - v_min) / (v_max - v_min)) * 255.0
    return img_normalized.astype(np.uint8)


def normalize_general_img(img):
    """Percentile (0.5–99.5) min-max normalization to [0, 255] for MRI, PET, etc."""
    v_min = np.percentile(img, 0.5)
    v_max = np.percentile(img, 99.5)
    if v_max - v_min == 0:
        return np.zeros_like(img, dtype=np.uint8)
    img_normalized = np.clip(img, v_min, v_max)
    img_normalized = ((img_normalized - v_min) / (v_max - v_min)) * 255.0
    return img_normalized.astype(np.uint8)


def normalize_img(image_2d, image_modality, label_name, dataset_name, taskID, taskType):
    """Normalize a 2D image slice to [0, 255] for visualization.

    Replicates the full normalization logic from medvision_bm/sft/sft_utils.py:
    - CT with a known, non-"Others" label: HU window-based normalization.
    - Everything else (MRI, PET, contrast CT, unknown label): percentile min-max.

    Args:
        image_2d:       2D numpy array of raw pixel/HU values.
        image_modality: Modality string from task_info, e.g. "CT" or "MRI".
        label_name:     Human-readable label name from labels_map, or None.
        dataset_name:   Dataset name string (e.g. "BraTS24").
        taskID:         Task ID string (e.g. "01").
        taskType:       Task type string (e.g. "Tumor-Lesion-Size").

    Returns:
        uint8 numpy array normalized to [0, 255].
    """
    # Check if this task forces standard normalization (skip HU windows)
    is_standard_normalization_required = any(
        t["dataset_name"] == dataset_name
        and t["taskID"] == taskID
        and t["taskType"] == taskType
        for t in TASK_LIST_FORCE_STANDARD_IMAGE_NORMALIZATION
    )

    if image_modality.lower() == "ct":
        group = LABEL_MAP_REGROUP.get(label_name) if label_name is not None else None
        use_hu_window = (
            group is not None
            and not is_standard_normalization_required
            and group.lower() != "others"
        )
        if use_hu_window:
            hu_window_wl = CT_HU_WINDOWS_WL.get(group)
            assert hu_window_wl is not None, (
                f"No HU window defined for group '{group}' (label '{label_name}'). "
                f"Check CT_HU_WINDOWS_WL in image_normalization.py."
            )
            return normalize_ct_img(image_2d, hu_window_wl[0], hu_window_wl[1])
        else:
            return normalize_general_img(image_2d)
    else:
        return normalize_general_img(image_2d)