AnikS22 commited on
Commit
7f58aa4
·
verified ·
1 Parent(s): f2f04dc

Upload predict.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. predict.py +144 -0
predict.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference script: detect immunogold particles in new images.
3
+
4
+ Usage:
5
+ python predict.py --image path/to/image.tif --checkpoint checkpoints/fold_S1_seed42/phase3_best.pth
6
+ python predict.py --fold S1 --checkpoint checkpoints/fold_S1_seed42/phase3_best.pth --config config/config.yaml
7
+ """
8
+
9
+ import argparse
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import torch
14
+ import yaml
15
+
16
+ from src.heatmap import extract_peaks
17
+ from src.model import ImmunogoldCenterNet
18
+ from src.postprocess import apply_structural_mask_filter, cross_class_nms
19
+ from src.preprocessing import load_image, load_mask
20
+ from src.ensemble import sliding_window_inference, d4_tta_predict
21
+ from src.visualize import overlay_annotations
22
+
23
+
24
+ def parse_args():
25
+ parser = argparse.ArgumentParser(description="Predict immunogold particles")
26
+ parser.add_argument("--image", type=str, help="Path to single image")
27
+ parser.add_argument("--mask", type=str, help="Path to mask (optional)")
28
+ parser.add_argument("--fold", type=str, help="Fold synapse ID for evaluation")
29
+ parser.add_argument("--checkpoint", type=str, required=True,
30
+ help="Path to model checkpoint")
31
+ parser.add_argument("--config", type=str, default="config/config.yaml")
32
+ parser.add_argument("--device", type=str, default="auto")
33
+ parser.add_argument("--tta", action="store_true", help="Enable D4 TTA")
34
+ parser.add_argument("--conf-threshold", type=float, default=0.3)
35
+ parser.add_argument("--output-dir", type=str, default="results/predictions")
36
+ return parser.parse_args()
37
+
38
+
39
+ def main():
40
+ args = parse_args()
41
+ with open(args.config) as f:
42
+ cfg = yaml.safe_load(f)
43
+
44
+ device = torch.device(
45
+ "cuda" if args.device == "auto" and torch.cuda.is_available()
46
+ else args.device if args.device != "auto" else "cpu"
47
+ )
48
+
49
+ # Load model
50
+ model = ImmunogoldCenterNet(
51
+ bifpn_channels=cfg["model"]["bifpn_channels"],
52
+ bifpn_rounds=cfg["model"]["bifpn_rounds"],
53
+ num_classes=cfg["model"]["num_classes"],
54
+ )
55
+
56
+ ckpt = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
57
+ model.load_state_dict(ckpt["model_state_dict"])
58
+ model.to(device)
59
+ model.eval()
60
+ print(f"Loaded checkpoint from epoch {ckpt.get('epoch', '?')}, "
61
+ f"val_f1={ckpt.get('val_f1_mean', '?')}")
62
+
63
+ # Load image
64
+ if args.fold:
65
+ from src.preprocessing import discover_synapse_data, load_synapse
66
+ records = discover_synapse_data(cfg["data"]["root"], cfg["data"]["synapse_ids"])
67
+ record = [r for r in records if r.synapse_id == args.fold][0]
68
+ data = load_synapse(record)
69
+ image = data["image"]
70
+ preprocessed = data["image"]
71
+ mask = data["mask"]
72
+ annotations = data["annotations"]
73
+ name = args.fold
74
+ else:
75
+ image = load_image(Path(args.image))
76
+ preprocessed = image
77
+ mask = load_mask(Path(args.mask)) if args.mask else None
78
+ annotations = {"6nm": np.empty((0, 2)), "12nm": np.empty((0, 2))}
79
+ name = Path(args.image).stem
80
+
81
+ # Inference
82
+ if args.tta:
83
+ print("Running D4 TTA inference...")
84
+ heatmap_np, offset_np = d4_tta_predict(model, preprocessed, device)
85
+ else:
86
+ print("Running sliding window inference...")
87
+ heatmap_np, offset_np = sliding_window_inference(
88
+ model, preprocessed,
89
+ patch_size=cfg["data"]["patch_size"],
90
+ device=device,
91
+ )
92
+
93
+ # Extract detections
94
+ heatmap_t = torch.from_numpy(heatmap_np)
95
+ offset_t = torch.from_numpy(offset_np)
96
+
97
+ detections = extract_peaks(
98
+ heatmap_t, offset_t,
99
+ stride=cfg["data"]["stride"],
100
+ conf_threshold=args.conf_threshold,
101
+ nms_kernel_sizes=cfg["postprocessing"]["nms_kernel_size"],
102
+ )
103
+
104
+ # Post-processing
105
+ if mask is not None:
106
+ detections = apply_structural_mask_filter(
107
+ detections, mask,
108
+ margin_px=cfg["postprocessing"]["mask_filter_margin_px"],
109
+ )
110
+ detections = cross_class_nms(
111
+ detections, cfg["postprocessing"]["cross_class_nms_distance_px"],
112
+ )
113
+
114
+ # Print results
115
+ n_6nm = sum(1 for d in detections if d["class"] == "6nm")
116
+ n_12nm = sum(1 for d in detections if d["class"] == "12nm")
117
+ print(f"\nDetections: {n_6nm} 6nm, {n_12nm} 12nm ({len(detections)} total)")
118
+
119
+ # Evaluate if GT available
120
+ if annotations and (len(annotations["6nm"]) > 0 or len(annotations["12nm"]) > 0):
121
+ from src.evaluate import match_detections_to_gt
122
+ results = match_detections_to_gt(
123
+ detections, annotations["6nm"], annotations["12nm"],
124
+ {k: float(v) for k, v in cfg["evaluation"]["match_radii_px"].items()},
125
+ )
126
+ for cls in ["6nm", "12nm", "overall"]:
127
+ r = results[cls]
128
+ print(f" {cls}: F1={r['f1']:.3f}, P={r['precision']:.3f}, "
129
+ f"R={r['recall']:.3f} (TP={r['tp']}, FP={r['fp']}, FN={r['fn']})")
130
+
131
+ # Save visualization
132
+ output_dir = Path(args.output_dir)
133
+ output_dir.mkdir(parents=True, exist_ok=True)
134
+ overlay_annotations(
135
+ image, annotations,
136
+ title=f"{name} — {n_6nm} 6nm, {n_12nm} 12nm detected",
137
+ save_path=output_dir / f"{name}_predictions.png",
138
+ predictions=detections,
139
+ )
140
+ print(f"Saved overlay to {output_dir / f'{name}_predictions.png'}")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()