Skip to content

Commit 8f31f33

Browse files
committed
Initial commit codebase
1 parent 83e6562 commit 8f31f33

15 files changed

Lines changed: 922 additions & 9 deletions

File tree

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
*.pt
2+
*.pyc
3+
*.egg-info

Dockerfile

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime
2+
3+
RUN pip3 install monai==1.4.0
4+
RUN pip3 install TotalSegmentator
5+
RUN pip3 install nnunetv2==2.4.2
6+
RUN pip3 install blosc2
7+
RUN pip3 install acvl-utils==0.2

README.md

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,24 +32,19 @@ export nnUNet_results='/path/to/.totalsegmentator/nnunet/results'
3232
## Running the algorithm
3333
When using the container build using the Dockerfile you can mount the input path containing the CT scans to "/input", the output path to "/output", and the folder containing downloaded model weights to "/opt/ml/model".
3434

35-
When using a virtual or conda environment, you need to set the input, output and model directories using command line arguments:
36-
```bash
37-
--input
38-
--output
39-
--model
40-
```
35+
When using a virtual or conda environment, you can either use the command line arguments to set the folder paths or set them as environment variables.
4136

4237
### To start the script
43-
Kick-off the script with ```python main.py``` with the following input arguments:
38+
You can kick-off the script with:
4439

4540
```bash
46-
--use_cropping (optionally)
41+
python main.py --use-cropping (optional) --input-path (optional) --output-path(optional) --model-path (optional)
4742
```
4843

4944
## Pipeline:
5045
The algorithm does the following steps for each CT scan (in .mha format) in the input folder:
5146
1. read ct scan (.mha) using SimpleITK
52-
2. if flag --use_cropping is set: use TotalSegmentator to find bladder and lungs, if found, crop around that in all three directions.
47+
2. if flag --use-cropping is set: use TotalSegmentator to find bladder and lungs, if found, crop around that in all three directions.
5348
3. use trained nnUNet to segment the kidneys and kidney abnormalities if present
5449
4. postprocess the kidney abnormality masks by removing small components (<3mm) and only keeping components attached to a kidney region, except when the abnormality component is larger than 100,000 mm^3.
5550

main.py

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
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())

pyproject.toml

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
[build-system]
2+
requires = ["setuptools>=68", "wheel"]
3+
build-backend = "setuptools.build_meta"
4+
5+
[project]
6+
name = "kidney_abnormality_segmentation"
7+
version = "1.0.0"
8+
description = "Kidney Abnormality Segmentation using nnUNet."
9+
readme = "README.md"
10+
requires-python = ">=3.9"
11+
license = {text = "Apache License, Version 2.0 (the 'License)"}
12+
authors = [{name = "Sarah de Boer"}]
13+
dependencies = [
14+
"monai==1.4.0",
15+
"TotalSegmentator",
16+
"nnunetv2==2.4.2",
17+
"blosc2",
18+
"acvl-utils==0.2"
19+
]
20+
21+
[project.optional-dependencies]
22+
dev = ["pytest", "black", "ruff"]

requirements.yml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
name: kidney-abnormality-segmentation
2+
channels:
3+
- pytorch
4+
- conda-forge
5+
- defaults
6+
dependencies:
7+
- python=3.11
8+
- pip
9+
- pytorch=2.2.2
10+
- monai=1.4.0
11+
- pip:
12+
- TotalSegmentator
13+
- nnunetv2==2.4.2
14+
- blosc2
15+
- acvl-utils==0.2
16+
- -e .

src/kidney_abnormality_segmentation/__init__.py

Whitespace-only changes.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import os
2+
from pathlib import Path
3+
4+
# Defaults match docker mounts
5+
DEFAULT_INPUT_PATH = Path("/input")
6+
DEFAULT_OUTPUT_PATH = Path("/output")
7+
DEFAULT_MODEL_PATH = Path("/opt/ml/model")
8+
9+
10+
def default_input_path() -> Path:
11+
"""Return default input path, allowing override via env var."""
12+
return Path(os.getenv("INPUT_PATH", DEFAULT_INPUT_PATH))
13+
14+
15+
def default_output_path() -> Path:
16+
"""Return default output path, allowing override via env var."""
17+
return Path(os.getenv("OUTPUT_PATH", DEFAULT_OUTPUT_PATH))
18+
19+
20+
def default_model_path() -> Path:
21+
"""Return default model path, allowing override via env var."""
22+
return Path(os.getenv("MODEL_PATH", DEFAULT_MODEL_PATH))

src/kidney_abnormality_segmentation/postprocessing/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)