siddharthdhara17 commited on
Commit
fa5bb00
·
verified ·
1 Parent(s): 2c6edad

Upload baselines/predict_nnunet.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. baselines/predict_nnunet.py +129 -0
baselines/predict_nnunet.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ nnU-Net prediction script that loads the trained model checkpoint
3
+ and generates predictions compatible with evaluate.py.
4
+
5
+ Usage:
6
+ python baselines/predict_nnunet.py \
7
+ --nnunet_results /workspace/data/nnUNet_results \
8
+ --test_dir data/flat_test \
9
+ --output_dir results/nnunet \
10
+ --num_samples 16
11
+ """
12
+ import argparse
13
+ import os
14
+ import sys
15
+ import glob
16
+ import numpy as np
17
+ import torch
18
+ from PIL import Image
19
+ from tqdm import tqdm
20
+
21
+
22
+ def load_nnunet_model(nnunet_results, fold=0):
23
+ """Load nnU-Net model from checkpoint."""
24
+ from nnunetv2.inference.predict_from_raw_data import nnUNetPredictor
25
+
26
+ # Find the trainer folder
27
+ dataset_dir = os.path.join(nnunet_results, "Dataset001_LIDC")
28
+ trainer_dirs = [d for d in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, d))]
29
+ trainer_name = trainer_dirs[0] # e.g., nnUNetTrainer200epochs__nnUNetPlans__2d
30
+ model_folder = os.path.join(dataset_dir, trainer_name)
31
+
32
+ print(f"Loading nnU-Net model from: {model_folder}")
33
+
34
+ predictor = nnUNetPredictor(
35
+ tile_step_size=0.5,
36
+ use_gaussian=True,
37
+ use_mirroring=True,
38
+ perform_everything_on_device=True,
39
+ device=torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu'),
40
+ verbose=False,
41
+ verbose_preprocessing=False,
42
+ allow_tqdm=False,
43
+ )
44
+ predictor.initialize_from_trained_model_folder(
45
+ model_folder,
46
+ use_folds=(fold,),
47
+ checkpoint_name='checkpoint_best.pth',
48
+ )
49
+ return predictor
50
+
51
+
52
+ def predict_single_image(predictor, image_path):
53
+ """Run nnU-Net prediction on a single image and return binary mask."""
54
+ # Load image as numpy array
55
+ img = np.array(Image.open(image_path).convert('L')) # (H, W)
56
+ # nnU-Net expects (C, Z, Y, X) for 3D or is handled internally
57
+ # For 2D nnU-Net, we need to pass the image properly
58
+ # Use the predictor's predict_single_npy_array method
59
+ img_input = img[np.newaxis, np.newaxis].astype(np.float32) # (1, 1, H, W)
60
+
61
+ # nnU-Net properties dict for 2D data
62
+ props = {
63
+ 'spacing': [999.0, 1.0, 1.0],
64
+ 'shape_after_cropping': img_input.shape[1:],
65
+ 'bbox_used_for_cropping': [[0, s] for s in img_input.shape[1:]],
66
+ 'shape_before_cropping': img_input.shape[1:],
67
+ 'class_locations': {},
68
+ }
69
+
70
+ # Run prediction
71
+ prediction = predictor.predict_single_npy_array(
72
+ input_image=img_input[0], # (1, H, W) - single channel
73
+ image_properties=props,
74
+ segmentation_previous_stage=None,
75
+ output_file_or_dir=None,
76
+ save_or_return_probabilities=False,
77
+ )
78
+
79
+ # prediction is a numpy array with segmentation labels
80
+ binary_mask = (prediction > 0).astype(np.uint8)
81
+
82
+ # Remove z dimension if present
83
+ if binary_mask.ndim == 3:
84
+ binary_mask = binary_mask[0]
85
+
86
+ return binary_mask
87
+
88
+
89
+ def main():
90
+ parser = argparse.ArgumentParser(description="nnU-Net Prediction")
91
+ parser.add_argument("--nnunet_results", type=str, required=True)
92
+ parser.add_argument("--test_dir", type=str, required=True)
93
+ parser.add_argument("--output_dir", type=str, required=True)
94
+ parser.add_argument("--num_samples", type=int, default=16)
95
+ parser.add_argument("--fold", type=int, default=0)
96
+ args = parser.parse_args()
97
+
98
+ os.makedirs(args.output_dir, exist_ok=True)
99
+
100
+ # Load model
101
+ predictor = load_nnunet_model(args.nnunet_results, args.fold)
102
+
103
+ # Get test images
104
+ image_files = sorted(glob.glob(os.path.join(args.test_dir, "*.png")))
105
+ # Filter to only images (not masks)
106
+ image_files = [f for f in image_files if "_mask" not in os.path.basename(f)]
107
+ print(f"Test dataset: {len(image_files)} images from {args.test_dir}")
108
+
109
+ total_saved = 0
110
+ for img_path in tqdm(image_files, desc="Predicting"):
111
+ basename = os.path.splitext(os.path.basename(img_path))[0]
112
+
113
+ # Get prediction
114
+ mask = predict_single_image(predictor, img_path)
115
+
116
+ # Save N replicated samples (deterministic model = same prediction)
117
+ for s in range(args.num_samples):
118
+ out_path = os.path.join(args.output_dir, f"{basename}_sample{s:02d}.png")
119
+ Image.fromarray(mask * 255).save(out_path)
120
+ total_saved += 1
121
+
122
+ print(f"\nSaved {len(image_files)} predictions × {args.num_samples} samples = {total_saved} files")
123
+ print(f"\nPredictions saved to {args.output_dir}")
124
+ print(f"Ready for evaluation:")
125
+ print(f" python evaluate.py --samples_dir {args.output_dir} --gt_dir data/testing --results_file results/nnunet_eval.csv")
126
+
127
+
128
+ if __name__ == "__main__":
129
+ main()