|
| 1 | +# Copyright 2022 Diagnostic Image Analysis Group, Radboudumc, Nijmegen, The Netherlands |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import gc |
| 16 | +import sys |
| 17 | +from argparse import ArgumentParser |
| 18 | +from pathlib import Path |
| 19 | + |
| 20 | +import SimpleITK |
| 21 | + |
| 22 | +from src.kidney_abnormality_segmentation.config import ( |
| 23 | + default_input_path, |
| 24 | + default_model_path, |
| 25 | + default_output_path, |
| 26 | +) |
| 27 | +from src.kidney_abnormality_segmentation.postprocessing.postprocess_segmentation_mask import ( |
| 28 | + postprocess_segmentation_mask, |
| 29 | +) |
| 30 | +from src.kidney_abnormality_segmentation.preprocessing.extract_roi import extract_roi |
| 31 | +from src.kidney_abnormality_segmentation.segmentation.segment_ct_image import ( |
| 32 | + segment_ct_image, |
| 33 | +) |
| 34 | +from src.kidney_abnormality_segmentation.utils import resample_volume, stem |
| 35 | + |
| 36 | + |
| 37 | +def build_parser() -> ArgumentParser: |
| 38 | + """Create and return the CLI argument parser.""" |
| 39 | + p = ArgumentParser(description="Process images and perform segmentation") |
| 40 | + p.add_argument( |
| 41 | + "--use-cropping", |
| 42 | + action="store_true", |
| 43 | + default=False, |
| 44 | + help="Enable ROI cropping based on TotalSegmentator (default: disabled).", |
| 45 | + ) |
| 46 | + # Use Path typing and safer argument names (avoid shadowing builtins like `input`) |
| 47 | + p.add_argument( |
| 48 | + "--input-path", |
| 49 | + type=Path, |
| 50 | + default=default_input_path(), |
| 51 | + help="Input folder path (defaults to /input or $INPUT_PATH).", |
| 52 | + ) |
| 53 | + p.add_argument( |
| 54 | + "--output-path", |
| 55 | + type=Path, |
| 56 | + default=default_output_path(), |
| 57 | + help="Output folder path (defaults to /output or $OUTPUT_PATH).", |
| 58 | + ) |
| 59 | + p.add_argument( |
| 60 | + "--model-path", |
| 61 | + type=Path, |
| 62 | + default=default_model_path(), |
| 63 | + help="Model weights folder path (defaults to /opt/ml/model or $MODEL_PATH).", |
| 64 | + ) |
| 65 | + return p |
| 66 | + |
| 67 | + |
| 68 | +def run(): |
| 69 | + parser = build_parser() |
| 70 | + args = parser.parse_args() |
| 71 | + |
| 72 | + # List all CT files under /input |
| 73 | + ct_folder = args.input_path |
| 74 | + if not ct_folder.exists(): |
| 75 | + raise FileNotFoundError(f"Input folder does not exist: {ct_folder}") |
| 76 | + if not ct_folder.is_dir(): |
| 77 | + raise NotADirectoryError(f"Input path is not a directory: {ct_folder}") |
| 78 | + |
| 79 | + try: |
| 80 | + all_cts = list(ct_folder.rglob("*.mha")) |
| 81 | + except PermissionError as e: |
| 82 | + raise PermissionError(f"Cannot access {args.input_path}: {e}") from e |
| 83 | + |
| 84 | + if not all_cts: |
| 85 | + print(f"No CT files found under {ct_folder}") |
| 86 | + sys.exit(1) |
| 87 | + |
| 88 | + print(f"[run] Found {len(all_cts)} input CTs to process") |
| 89 | + crop_roi = args.use_cropping |
| 90 | + |
| 91 | + for input_ct_image_path in all_cts: |
| 92 | + print(f"[run] Processing {input_ct_image_path.name}") |
| 93 | + if input_ct_image_path.name.startswith("."): |
| 94 | + print(f"[run] Skipping {input_ct_image_path.name} because not an image.") |
| 95 | + continue |
| 96 | + image_name = stem(str(input_ct_image_path)) |
| 97 | + out_folder = args.output_path |
| 98 | + out_folder.mkdir(parents=True, exist_ok=True) |
| 99 | + out_path = out_folder / f"{image_name}.mha" |
| 100 | + if out_path.is_file(): |
| 101 | + print( |
| 102 | + f"[run] Skipping {input_ct_image_path.name} because output segmentation already exists for this image." |
| 103 | + ) |
| 104 | + continue |
| 105 | + # 3) Decide what to hand to segment_ct_image: |
| 106 | + # - If cropping: read into memory, crop, then pass the cropped SITK.Image. |
| 107 | + # - If no cropping: NEVER read the full CT. Pass the filepath string instead. |
| 108 | + orig_spacing = SimpleITK.ReadImage(str(input_ct_image_path)).GetSpacing() |
| 109 | + if crop_roi: |
| 110 | + print("[run] Cropping ROI; will read full CT into memory.") |
| 111 | + full_ct = SimpleITK.ReadImage(str(input_ct_image_path)) |
| 112 | + input_for_seg = extract_roi(full_ct) |
| 113 | + # free the full CT |
| 114 | + del full_ct |
| 115 | + gc.collect() |
| 116 | + else: |
| 117 | + print( |
| 118 | + "[run] No cropping requested; will segment from disk without reading full CT." |
| 119 | + ) |
| 120 | + input_for_seg = str(input_ct_image_path) |
| 121 | + |
| 122 | + # 4) Segment (this now never loads the full on-disk CT into RAM) |
| 123 | + print("[run] Calling segment_ct_image() …") |
| 124 | + segmentation_sitk = segment_ct_image(input_for_seg, str(args.model_path)) |
| 125 | + |
| 126 | + # 5) Free any remaining cropped image if it was in RAM |
| 127 | + if isinstance(input_for_seg, SimpleITK.Image): |
| 128 | + del input_for_seg |
| 129 | + gc.collect() |
| 130 | + |
| 131 | + # 6) Postprocess & write out |
| 132 | + post_sitk = postprocess_segmentation_mask(segmentation_sitk) |
| 133 | + final_image = resample_volume( |
| 134 | + post_sitk, |
| 135 | + new_spacing=orig_spacing, |
| 136 | + interpolator=SimpleITK.sitkNearestNeighbor, |
| 137 | + ) |
| 138 | + print(f"[run] Writing final mask to: {out_path}") |
| 139 | + |
| 140 | + SimpleITK.WriteImage(final_image, str(out_path)) |
| 141 | + |
| 142 | + print("[run] Done.") |
| 143 | + return 0 |
| 144 | + |
| 145 | + |
| 146 | +if __name__ == "__main__": |
| 147 | + sys.exit(run()) |
0 commit comments