|
| 1 | +# Copyright (c) 2021 The Foundation for Research on Information Technologies in Society (IT'IS). |
| 2 | +# |
| 3 | +# This file is part of s4l-scripts |
| 4 | +# (see https://github.com/dyollb/s4l-scripts). |
| 5 | +# |
| 6 | +# This software is released under the MIT License. |
| 7 | +# https://opensource.org/licenses/MIT |
| 8 | + |
| 9 | +import numpy as np |
| 10 | +from pathlib import Path |
| 11 | +from typing import Dict |
| 12 | + |
| 13 | + |
| 14 | +def load_stanford_label_info(file_path: Path) -> Dict[int, str]: |
| 15 | + """Load tissue names and labels from stanford example dataset |
| 16 | +
|
| 17 | + Args: |
| 18 | + file_path: label info file to parse |
| 19 | +
|
| 20 | + The file is assumed to by in CSV format with 3 columns, where the first row is a header, e.g. |
| 21 | +
|
| 22 | + new label, freesurfer label, freesurfer name |
| 23 | + 1, 2, "Left-Cerebral-White-Matter" |
| 24 | + 1, 41, "Right-Cerebral-White-Matter" |
| 25 | + 1, 77, "WM-hypointensities" |
| 26 | + ... |
| 27 | + """ |
| 28 | + with open(file_path, "r") as f: |
| 29 | + lines = f.readlines() |
| 30 | + label_info: Dict[int, str] = {} |
| 31 | + for line in lines[1:]: |
| 32 | + parts = line.split(",") |
| 33 | + if len(parts) != 3: |
| 34 | + continue |
| 35 | + label = int(parts[0].strip()) |
| 36 | + name = parts[2].strip().strip('"').replace(" ", "_") |
| 37 | + if label in label_info: |
| 38 | + label_info[label] += f"_{name}" |
| 39 | + else: |
| 40 | + label_info[label] = name |
| 41 | + return label_info |
| 42 | + |
| 43 | + |
| 44 | +def save_iseg_label_info(label_info: Dict[int, str], file_path: Path): |
| 45 | + """save label info dictionary as iSEG compatible tissue list |
| 46 | +
|
| 47 | + Args: |
| 48 | + tissue_list: input label info dictionary |
| 49 | + file_path: tissue list file |
| 50 | +
|
| 51 | + Example file: |
| 52 | + V7 |
| 53 | + N3 |
| 54 | + C0.00 0.00 1.00 0.50 Bone |
| 55 | + C0.00 1.00 0.00 0.50 Fat |
| 56 | + C1.00 0.00 0.00 0.50 Skin |
| 57 | + """ |
| 58 | + max_label = max(label_info.keys()) |
| 59 | + tissue_names = [f"tissue{i}" for i in range(max_label + 1)] |
| 60 | + for id, name in label_info.items(): |
| 61 | + tissue_names[id] = name |
| 62 | + |
| 63 | + with open(file_path, "w") as f: |
| 64 | + print("V7", file=f) |
| 65 | + print(f"N{max_label}", file=f) |
| 66 | + for i in range(1, max_label): |
| 67 | + r, g, b = np.random.rand(), np.random.rand(), np.random.rand() |
| 68 | + print(f"C{r:.2f} {g:.2f} {b:.2f} 0.50 {tissue_names[i]}", file=f) |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + label_info_file = Path("/Users/lloyd/Models/StandfordData") / "label_info.txt" |
| 73 | + label_info = load_stanford_label_info(label_info_file) |
| 74 | + save_iseg_label_info(label_info, label_info_file.parent / "label_info_iseg.txt") |
0 commit comments