forked from eshasadia/CORE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathablation_study.py
More file actions
1472 lines (1259 loc) · 57.5 KB
/
Copy pathablation_study.py
File metadata and controls
1472 lines (1259 loc) · 57.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
CORE – Ablation Study Script
============================
Systematically compares:
A) CORE pipeline step ablation
1. Baseline – no registration (identity)
2. Rigid-only – Trimorph + XFeat rigid alignment
3. Elastic-only – deep multi-scale elastic registration (no rigid pre-step)
4. CORE Coarse – Rigid + Elastic (standard coarse pipeline)
5. CORE Full – Coarse + fine nuclei-level shape-aware registration
(requires --fixed-nuclei / --moving-nuclei CSVs)
B) State-of-the-art comparison methods
6. Phase Correlation – translation-only (scipy)
7. ITK Rigid (MI) – SimpleITK Mattes Mutual Information rigid
8. ITK Demons – SimpleITK Demons diffeomorphic non-rigid
9. ORB + RANSAC Affine – OpenCV keypoint-based
10. AKAZE + RANSAC Affine – OpenCV keypoint-based (patent-free)
Metrics (computed whenever applicable)
- TRE – Target Registration Error (pixels, mean/median/std/max)
- rTRE – Relative TRE (mean/median)
- NGF – Normalised Gradient Field (higher = better edge alignment)
- NCC – Normalised Cross-Correlation (higher = better)
- SSIM – Structural Similarity Index (higher = better)
- DICE – Dice coefficient of tissue masks (higher = better)
- Time – per-method wall-clock time (seconds)
Usage
-----
python ablation_study.py \\
--source /path/to/moving.tiff \\
--target /path/to/fixed.tiff \\
[--fixed-landmarks fixed_lm.csv] \\
[--moving-landmarks moving_lm.csv] \\
[--fixed-nuclei fixed_nuclei.csv] \\
[--moving-nuclei moving_nuclei.csv] \\
[--output-dir ./ablation_results] \\
[--methods all] \\
[--no-plots]
The landmark CSVs must have a header row; columns after the first are
treated as (x, y) coordinates (same format used elsewhere in the repo).
The nuclei CSVs must contain ``global_x`` and ``global_y`` columns.
Before running
--------------
conda env create -f environment.yml
conda activate core
export VISION_AGENT_API_KEY="<your-key>"
"""
from __future__ import annotations
import argparse
import os
import sys
import time
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import cv2
import numpy as np
import pandas as pd
import SimpleITK as sitk
from scipy.ndimage import map_coordinates
from scipy.signal import correlate2d
from skimage import color
from skimage.metrics import structural_similarity as ssim
# ── Make sure the repo root is on sys.path when run directly ──────────────────
_ROOT = os.path.dirname(os.path.abspath(__file__))
if _ROOT not in sys.path:
sys.path.insert(0, _ROOT)
from core.config import (
PREPROCESSING_RESOLUTION,
RegistrationParams,
)
from core.evaluation.evaluation import (
apply_displacement_field_to_points,
ngf_metric,
rtre,
tre,
)
from core.preprocessing.padding import pad_images
from core.preprocessing.preprocessing import extract_tissue_masks, load_wsi_images
from core.registration.nonrigid import elastic_image_registration
from core.registration.registration import (
convert_4x4_to_3x3_transform,
create_displacement_field,
find_mutual_nearest_neighbors,
perform_cpd_registration,
perform_icp_registration,
perform_rigid_registration,
)
from core.registration.cpd import CPD as _CPD
import core.utils.util as util
# ── Optional fine-registration imports ────────────────────────────────────────
try:
from core.preprocessing.nuclei_analysis import load_nuclei_coordinates
from core.preprocessing.padding import pad_landmarks
from core.registration.nonrigid import compute_deformation_and_apply
from core.registration.registration import perform_shape_aware_registration
_FINE_REG_AVAILABLE = True
except ImportError:
_FINE_REG_AVAILABLE = False
# ── Silence non-critical warnings ─────────────────────────────────────────────
warnings.filterwarnings("ignore", category=UserWarning)
# ─────────────────────────────────────────────────────────────────────────────
# Data structures
# ─────────────────────────────────────────────────────────────────────────────
ALL_METHODS = [
"baseline",
"rigid_only",
"elastic_only",
"core_coarse",
"core_full",
"phase_correlation",
"itk_rigid_mi",
"itk_demons",
"orb_ransac",
"akaze_ransac",
# ── Point-based methods ──────────────────────────────────────────────
"sift_ransac",
"icp",
"cpd_rigid",
"cpd_affine",
"cpd_nonrigid",
]
# Human-readable labels for tables / plots
METHOD_LABELS: Dict[str, str] = {
"baseline": "Baseline (none)",
"rigid_only": "CORE Rigid only",
"elastic_only": "CORE Elastic only",
"core_coarse": "CORE Coarse (R+E)",
"core_full": "CORE Full (R+E+Fine)",
"phase_correlation": "Phase Correlation",
"itk_rigid_mi": "ITK Rigid (MI)",
"itk_demons": "ITK Demons",
"orb_ransac": "ORB + RANSAC",
"akaze_ransac": "AKAZE + RANSAC",
# ── Point-based methods ──────────────────────────────────────────────
"sift_ransac": "SIFT + RANSAC",
"icp": "ICP (Open3D)",
"cpd_rigid": "CPD Rigid",
"cpd_affine": "CPD Affine",
"cpd_nonrigid": "CPD Non-rigid",
}
@dataclass
class MethodResult:
"""Holds all metric values for a single method."""
method: str
label: str
time_total_s: float = float("nan")
time_rigid_s: float = float("nan")
time_elastic_s: float = float("nan")
time_fine_s: float = float("nan")
# Image-quality metrics
ngf: float = float("nan")
ncc: float = float("nan")
ssim_score: float = float("nan")
dice_mask: float = float("nan")
# Landmark-based metrics (only when landmarks are provided)
tre_mean: float = float("nan")
tre_median: float = float("nan")
tre_std: float = float("nan")
tre_max: float = float("nan")
rtre_mean: float = float("nan")
rtre_median: float = float("nan")
# Error / skip note
note: str = ""
def to_dict(self) -> dict:
return {
"Method": self.label,
"Time total (s)": _fmt(self.time_total_s),
"Time rigid (s)": _fmt(self.time_rigid_s),
"Time elastic (s)": _fmt(self.time_elastic_s),
"Time fine (s)": _fmt(self.time_fine_s),
"NGF ↑": _fmt(self.ngf, 4),
"NCC ↑": _fmt(self.ncc, 4),
"SSIM ↑": _fmt(self.ssim_score, 4),
"DICE mask ↑": _fmt(self.dice_mask, 4),
"TRE mean (px) ↓": _fmt(self.tre_mean, 2),
"TRE median (px) ↓": _fmt(self.tre_median, 2),
"TRE std (px)": _fmt(self.tre_std, 2),
"TRE max (px) ↓": _fmt(self.tre_max, 2),
"rTRE mean ↓": _fmt(self.rtre_mean, 5),
"rTRE median ↓": _fmt(self.rtre_median, 5),
"Note": self.note,
}
def _fmt(val: float, decimals: int = 3) -> str:
if np.isnan(val):
return "N/A"
return f"{val:.{decimals}f}"
# ─────────────────────────────────────────────────────────────────────────────
# Metric helpers
# ─────────────────────────────────────────────────────────────────────────────
def _ncc(fixed: np.ndarray, moving: np.ndarray) -> float:
"""Normalised cross-correlation between two RGB images converted to grey."""
fg = color.rgb2gray(fixed).astype(np.float64)
mg = color.rgb2gray(moving).astype(np.float64)
fg -= fg.mean()
fg_std = fg.std()
mg -= mg.mean()
mg_std = mg.std()
if fg_std < 1e-10 or mg_std < 1e-10:
return 0.0
return float(np.mean((fg / fg_std) * (mg / mg_std)))
def _ssim(fixed: np.ndarray, moving: np.ndarray) -> float:
"""SSIM on the grayscale versions (skimage)."""
fg = color.rgb2gray(fixed)
mg = color.rgb2gray(moving)
data_range = max(fg.max(), mg.max()) - min(fg.min(), mg.min())
if data_range < 1e-10:
return 1.0
return float(ssim(fg, mg, data_range=data_range))
def _dice_masks(mask_a: np.ndarray, mask_b: np.ndarray) -> float:
"""Dice coefficient of two binary masks."""
a = mask_a.astype(bool)
b = mask_b.astype(bool)
intersection = np.logical_and(a, b).sum()
total = a.sum() + b.sum()
if total == 0:
return 0.0
return float(2.0 * intersection / total)
def _compute_image_metrics(
fixed: np.ndarray,
warped: np.ndarray,
fixed_mask: np.ndarray,
warped_mask: np.ndarray,
result: MethodResult,
) -> None:
"""Fill in NGF, NCC, SSIM, DICE on *result* in-place."""
try:
result.ngf = ngf_metric(fixed, warped)
except Exception:
pass
try:
result.ncc = _ncc(fixed, warped)
except Exception:
pass
try:
result.ssim_score = _ssim(fixed, warped)
except Exception:
pass
try:
result.dice_mask = _dice_masks(fixed_mask, warped_mask)
except Exception:
pass
def _compute_landmark_metrics(
fixed_lm: np.ndarray,
warped_lm: np.ndarray,
image_shape: Tuple[int, int],
result: MethodResult,
) -> None:
"""Fill in TRE / rTRE metrics on *result* in-place."""
try:
tre_vals = tre(fixed_lm, warped_lm)
result.tre_mean = float(np.mean(tre_vals))
result.tre_median = float(np.median(tre_vals))
result.tre_std = float(np.std(tre_vals))
result.tre_max = float(np.max(tre_vals))
rtre_vals = rtre(fixed_lm, warped_lm, image_shape[1], image_shape[0])
result.rtre_mean = float(np.mean(rtre_vals))
result.rtre_median = float(np.median(rtre_vals))
except Exception:
pass
def _warp_landmarks_affine(landmarks: np.ndarray, matrix_3x3: np.ndarray) -> np.ndarray:
"""Apply a 3×3 affine matrix to (N,2) landmark array."""
hom = np.hstack([landmarks, np.ones((len(landmarks), 1))])
return (matrix_3x3 @ hom.T).T[:, :2]
def _warp_landmarks_displacement(
landmarks: np.ndarray,
disp_field_hw2: np.ndarray,
) -> np.ndarray:
"""
Apply a (H, W, 2) displacement field to (N, 2) landmarks.
Returns only the valid (in-bounds) subset; caller must handle size mismatch.
"""
moved, valid = apply_displacement_field_to_points(landmarks, disp_field_hw2)
# Re-insert invalid points with their original positions so shapes match
out = landmarks.copy()
out[valid] = moved
return out
def _warp_mask(mask: np.ndarray, matrix_2x3: np.ndarray) -> np.ndarray:
"""Warp a binary mask with a 2×3 affine matrix."""
h, w = mask.shape
warped = cv2.warpAffine(
mask.astype(np.uint8), matrix_2x3, (w, h), flags=cv2.INTER_NEAREST
)
return warped.astype(bool)
def _rgb_from_tensor(t) -> np.ndarray:
"""Convert PyTorch warped tensor (1,1,H,W) or (1,C,H,W) to uint8 RGB ndarray."""
arr = t.detach().cpu().numpy()
if arr.ndim == 4:
arr = arr[0]
if arr.shape[0] == 1: # grayscale → RGB
arr = np.concatenate([arr, arr, arr], axis=0)
arr = np.transpose(arr, (1, 2, 0)) # CHW → HWC
arr = (arr * 255).clip(0, 255).astype(np.uint8)
return arr
# ─────────────────────────────────────────────────────────────────────────────
# Registration method implementations
# ─────────────────────────────────────────────────────────────────────────────
# ── 1. Baseline ───────────────────────────────────────────────────────────────
def run_baseline(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="baseline", label=METHOD_LABELS["baseline"])
t0 = time.perf_counter()
warped = source.copy()
result.time_total_s = time.perf_counter() - t0
_compute_image_metrics(target, warped, target_mask, source_mask, result)
if fixed_lm is not None and moving_lm is not None:
_compute_landmark_metrics(fixed_lm, moving_lm, target.shape, result)
return result
# ── 2. CORE Rigid-only ────────────────────────────────────────────────────────
def run_rigid_only(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="rigid_only", label=METHOD_LABELS["rigid_only"])
t0 = time.perf_counter()
try:
warped, transform = perform_rigid_registration(
source, target, source_mask, target_mask
)
result.time_rigid_s = time.perf_counter() - t0
result.time_total_s = result.time_rigid_s
warped_mask = _warp_mask(source_mask, transform[:2])
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
warped_lm = _warp_landmarks_affine(moving_lm, np.linalg.inv(transform))
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 3. CORE Elastic-only ──────────────────────────────────────────────────────
def run_elastic_only(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="elastic_only", label=METHOD_LABELS["elastic_only"])
t0 = time.perf_counter()
try:
def_field, warped_t = elastic_image_registration(source, target)
result.time_elastic_s = time.perf_counter() - t0
result.time_total_s = result.time_elastic_s
warped = _rgb_from_tensor(warped_t)
# Warp mask using the displacement field
disp_np = def_field.detach().cpu().numpy()[0] # (H, W, 2) in normalised coords
disp_hw2 = _denorm_displacement(disp_np, source.shape[:2])
warped_mask = _warp_mask_displacement(source_mask, disp_hw2)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
warped_lm = _warp_landmarks_displacement(moving_lm, disp_hw2)
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 4. CORE Coarse (Rigid + Elastic) ─────────────────────────────────────────
def run_core_coarse(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="core_coarse", label=METHOD_LABELS["core_coarse"])
t0 = time.perf_counter()
try:
# Rigid step
t_rigid0 = time.perf_counter()
rigid_warped, transform = perform_rigid_registration(
source, target, source_mask, target_mask
)
result.time_rigid_s = time.perf_counter() - t_rigid0
# Elastic step
t_elast0 = time.perf_counter()
def_field, warped_t = elastic_image_registration(rigid_warped, target)
result.time_elastic_s = time.perf_counter() - t_elast0
result.time_total_s = time.perf_counter() - t0
warped = _rgb_from_tensor(warped_t)
disp_np = def_field.detach().cpu().numpy()[0]
disp_hw2 = _denorm_displacement(disp_np, rigid_warped.shape[:2])
# Compose: first rigid, then elastic
rigid_warped_mask = _warp_mask(source_mask, transform[:2])
warped_mask = _warp_mask_displacement(rigid_warped_mask, disp_hw2)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
rigid_lm = _warp_landmarks_affine(moving_lm, np.linalg.inv(transform))
final_lm = _warp_landmarks_displacement(rigid_lm, disp_hw2)
_compute_landmark_metrics(fixed_lm, final_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 5. CORE Full (Coarse + Fine nuclei) ──────────────────────────────────────
def run_core_full(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
fixed_nuclei_csv: Optional[str],
moving_nuclei_csv: Optional[str],
padding_params: dict,
) -> MethodResult:
result = MethodResult(method="core_full", label=METHOD_LABELS["core_full"])
if not _FINE_REG_AVAILABLE:
result.note = "Fine registration modules not importable; skipped."
return result
if fixed_nuclei_csv is None or moving_nuclei_csv is None:
result.note = "Nuclei CSVs not provided; skipped."
return result
t0 = time.perf_counter()
try:
# Coarse rigid
t_r0 = time.perf_counter()
rigid_warped, transform = perform_rigid_registration(
source, target, source_mask, target_mask
)
result.time_rigid_s = time.perf_counter() - t_r0
# Coarse elastic
t_e0 = time.perf_counter()
def_field, warped_t = elastic_image_registration(rigid_warped, target)
result.time_elastic_s = time.perf_counter() - t_e0
# Convert displacement field for downstream use
disp_field_np = util.tc_df_to_np_df(def_field)
# Fine nuclei registration
t_f0 = time.perf_counter()
moving_df = load_nuclei_coordinates(moving_nuclei_csv)
fixed_df = load_nuclei_coordinates(fixed_nuclei_csv)
deform_field, moving_updated, fixed_pts, _ = compute_deformation_and_apply(
source,
transform,
def_field,
moving_df,
fixed_df,
padding_params,
util,
pad_landmarks,
)
_, _, shape_transformed = perform_shape_aware_registration(
fixed_pts,
moving_updated,
shape_weight=0.3,
max_iterations=100,
tolerance=1e-11,
)
result.time_fine_s = time.perf_counter() - t_f0
result.time_total_s = time.perf_counter() - t0
# Image quality from elastic warped result
warped = _rgb_from_tensor(warped_t)
disp_np = def_field.detach().cpu().numpy()[0]
disp_hw2 = _denorm_displacement(disp_np, rigid_warped.shape[:2])
rigid_warped_mask = _warp_mask(source_mask, transform[:2])
warped_mask = _warp_mask_displacement(rigid_warped_mask, disp_hw2)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
# Landmark metrics using shape-aware output
if fixed_lm is not None:
_compute_landmark_metrics(fixed_pts, shape_transformed, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 6. Phase Correlation ──────────────────────────────────────────────────────
def run_phase_correlation(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
from skimage.registration import phase_cross_correlation
result = MethodResult(
method="phase_correlation", label=METHOD_LABELS["phase_correlation"]
)
t0 = time.perf_counter()
try:
src_g = color.rgb2gray(source)
tgt_g = color.rgb2gray(target)
shift, _, _ = phase_cross_correlation(tgt_g, src_g, upsample_factor=10)
# Build a translation-only affine matrix
M = np.array([[1, 0, shift[1]], [0, 1, shift[0]]], dtype=np.float64)
warped = cv2.warpAffine(source, M, (target.shape[1], target.shape[0]))
result.time_total_s = time.perf_counter() - t0
warped_mask = _warp_mask(source_mask, M)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
M3 = np.vstack([M, [0, 0, 1]])
warped_lm = _warp_landmarks_affine(moving_lm, np.linalg.inv(M3))
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 7. ITK Rigid (Mutual Information) ────────────────────────────────────────
def run_itk_rigid_mi(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="itk_rigid_mi", label=METHOD_LABELS["itk_rigid_mi"])
t0 = time.perf_counter()
try:
fixed_sitk = _rgb_to_sitk(target)
moving_sitk = _rgb_to_sitk(source)
reg = sitk.ImageRegistrationMethod()
reg.SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)
reg.SetMetricSamplingStrategy(reg.RANDOM)
reg.SetMetricSamplingPercentage(0.1)
reg.SetInterpolator(sitk.sitkLinear)
# Initialise with moments
init = sitk.CenteredTransformInitializer(
fixed_sitk, moving_sitk,
sitk.Euler2DTransform(),
sitk.CenteredTransformInitializerFilter.MOMENTS,
)
reg.SetInitialTransform(init)
reg.SetOptimizerAsGradientDescent(
learningRate=1.0, numberOfIterations=200,
convergenceMinimumValue=1e-6, convergenceWindowSize=10,
)
reg.SetOptimizerScalesFromPhysicalShift()
final_transform = reg.Execute(
sitk.Cast(fixed_sitk, sitk.sitkFloat32),
sitk.Cast(moving_sitk, sitk.sitkFloat32),
)
warped_sitk = sitk.Resample(
moving_sitk, fixed_sitk, final_transform,
sitk.sitkLinear, 0.0, moving_sitk.GetPixelID(),
)
warped = sitk.GetArrayFromImage(warped_sitk)
if warped.ndim == 2:
warped = np.stack([warped] * 3, axis=-1)
warped = warped.astype(np.uint8)
result.time_total_s = time.perf_counter() - t0
# Approximate mask warp via ITK transform
warped_mask = _warp_mask_sitk(source_mask, fixed_sitk, final_transform)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
warped_lm = _transform_landmarks_sitk(moving_lm, final_transform, source.shape)
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 8. ITK Demons ─────────────────────────────────────────────────────────────
def run_itk_demons(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="itk_demons", label=METHOD_LABELS["itk_demons"])
t0 = time.perf_counter()
try:
fixed_sitk = sitk.Cast(_rgb_to_sitk(target), sitk.sitkFloat32)
moving_sitk = sitk.Cast(_rgb_to_sitk(source), sitk.sitkFloat32)
demons = sitk.FastSymmetricForcesDemonsRegistrationFilter()
demons.SetNumberOfIterations(200)
demons.SetStandardDeviations(1.5)
disp_field = demons.Execute(fixed_sitk, moving_sitk)
disp_tx = sitk.DisplacementFieldTransform(disp_field)
warped_sitk = sitk.Resample(
sitk.Cast(_rgb_to_sitk(source), sitk.sitkFloat32),
fixed_sitk, disp_tx,
sitk.sitkLinear, 0.0, sitk.sitkFloat32,
)
warped = sitk.GetArrayFromImage(sitk.Cast(warped_sitk, sitk.sitkUInt8))
if warped.ndim == 2:
warped = np.stack([warped] * 3, axis=-1)
result.time_total_s = time.perf_counter() - t0
disp_np = sitk.GetArrayFromImage(disp_field) # (H, W, 2)
warped_mask = _warp_mask_displacement(source_mask, disp_np)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
warped_lm = _warp_landmarks_displacement(moving_lm, disp_np)
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 9. ORB + RANSAC ───────────────────────────────────────────────────────────
def run_orb_ransac(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="orb_ransac", label=METHOD_LABELS["orb_ransac"])
t0 = time.perf_counter()
try:
M = _keypoint_affine(source, target, descriptor="ORB")
warped = cv2.warpAffine(source, M, (target.shape[1], target.shape[0]))
result.time_total_s = time.perf_counter() - t0
warped_mask = _warp_mask(source_mask, M)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
M3 = np.vstack([M, [0, 0, 1]])
warped_lm = _warp_landmarks_affine(moving_lm, np.linalg.inv(M3))
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 10. AKAZE + RANSAC ────────────────────────────────────────────────────────
def run_akaze_ransac(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
result = MethodResult(method="akaze_ransac", label=METHOD_LABELS["akaze_ransac"])
t0 = time.perf_counter()
try:
M = _keypoint_affine(source, target, descriptor="AKAZE")
warped = cv2.warpAffine(source, M, (target.shape[1], target.shape[0]))
result.time_total_s = time.perf_counter() - t0
warped_mask = _warp_mask(source_mask, M)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
M3 = np.vstack([M, [0, 0, 1]])
warped_lm = _warp_landmarks_affine(moving_lm, np.linalg.inv(M3))
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ─────────────────────────────────────────────────────────────────────────────
# Shared low-level helpers
# ─────────────────────────────────────────────────────────────────────────────
def _keypoint_affine(
source: np.ndarray,
target: np.ndarray,
descriptor: str = "ORB",
min_matches: int = 10,
) -> np.ndarray:
"""
Estimate a 2×3 affine matrix via keypoint matching + RANSAC.
Parameters
----------
source, target : RGB uint8 arrays
descriptor : 'ORB', 'AKAZE', or 'SIFT'
min_matches : minimum number of inlier matches required
Returns
-------
M : (2, 3) float64 affine matrix
"""
src_g = cv2.cvtColor(source, cv2.COLOR_RGB2GRAY)
tgt_g = cv2.cvtColor(target, cv2.COLOR_RGB2GRAY)
if descriptor == "ORB":
det = cv2.ORB_create(nfeatures=10_000)
norm = cv2.NORM_HAMMING
elif descriptor == "SIFT":
det = cv2.SIFT_create()
norm = cv2.NORM_L2
else: # AKAZE
det = cv2.AKAZE_create()
norm = cv2.NORM_HAMMING
kp1, des1 = det.detectAndCompute(src_g, None)
kp2, des2 = det.detectAndCompute(tgt_g, None)
if des1 is None or des2 is None or len(des1) < min_matches or len(des2) < min_matches:
raise RuntimeError(
f"{descriptor}: insufficient keypoints "
f"(src={len(kp1) if kp1 else 0}, tgt={len(kp2) if kp2 else 0})"
)
bf = cv2.BFMatcher(norm, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda m: m.distance)
if len(matches) < min_matches:
raise RuntimeError(
f"{descriptor}: too few matches ({len(matches)} < {min_matches})"
)
src_pts = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
M, mask = cv2.estimateAffine2D(src_pts, dst_pts, method=cv2.RANSAC, ransacReprojThreshold=3.0)
if M is None:
raise RuntimeError(f"{descriptor}: RANSAC affine estimation failed.")
return M.astype(np.float64)
def _rgb_to_sitk(img: np.ndarray) -> sitk.Image:
"""Convert RGB uint8 array to grayscale SimpleITK image."""
gray = (color.rgb2gray(img) * 255).astype(np.uint8)
return sitk.GetImageFromArray(gray)
def _warp_mask_sitk(
mask: np.ndarray,
reference_sitk: sitk.Image,
transform: sitk.Transform,
) -> np.ndarray:
"""Warp a binary mask using a SimpleITK transform."""
mask_sitk = sitk.GetImageFromArray(mask.astype(np.uint8))
mask_sitk.CopyInformation(reference_sitk)
warped = sitk.Resample(
mask_sitk, reference_sitk, transform,
sitk.sitkNearestNeighbor, 0, mask_sitk.GetPixelID(),
)
return sitk.GetArrayFromImage(warped).astype(bool)
def _transform_landmarks_sitk(
landmarks: np.ndarray,
transform: sitk.Transform,
image_shape: Tuple[int, ...],
) -> np.ndarray:
"""
Apply a SimpleITK transform to (N, 2) landmark coordinates.
SimpleITK transforms operate in physical space; we assume unit spacing.
The transform maps fixed → moving (inverse direction), so we use the
inverse to map moving → fixed.
"""
inv_tx = transform.GetInverse()
out = np.zeros_like(landmarks)
for i, (x, y) in enumerate(landmarks):
tx, ty = inv_tx.TransformPoint((float(x), float(y)))
out[i] = [tx, ty]
return out
def _denorm_displacement(
disp_norm: np.ndarray,
image_shape: Tuple[int, int],
) -> np.ndarray:
"""
Convert a PyTorch grid-sample normalised displacement field (H, W, 2) in
[-1, 1] to pixel-space displacement (H, W, 2).
"""
H, W = image_shape
out = disp_norm.copy()
out[..., 0] = disp_norm[..., 0] * (W / 2.0) # x dimension
out[..., 1] = disp_norm[..., 1] * (H / 2.0) # y dimension
return out
def _warp_mask_displacement(
mask: np.ndarray,
disp_hw2: np.ndarray,
) -> np.ndarray:
"""Apply a pixel-space (H, W, 2) displacement field to warp a binary mask."""
h, w = mask.shape
map_x = (np.arange(w, dtype=np.float32)[None, :] + disp_hw2[..., 0]).astype(np.float32)
map_y = (np.arange(h, dtype=np.float32)[:, None] + disp_hw2[..., 1]).astype(np.float32)
warped = cv2.remap(
mask.astype(np.uint8), map_x, map_y,
cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=0,
)
return warped.astype(bool)
# ─────────────────────────────────────────────────────────────────────────────
# Point-based method helpers
# ─────────────────────────────────────────────────────────────────────────────
_PT_MAX_POINTS = 3000 # max tissue points used by ICP / CPD
def _extract_tissue_points(mask: np.ndarray, max_points: int = _PT_MAX_POINTS) -> np.ndarray:
"""
Subsample foreground pixel coordinates from a binary tissue mask.
Returns
-------
np.ndarray of shape (N, 2) with (x, y) float32 coordinates.
"""
ys, xs = np.where(mask > 0)
if len(xs) == 0:
raise RuntimeError("Tissue mask is empty — cannot extract points.")
points = np.column_stack([xs, ys]).astype(np.float32)
if len(points) > max_points:
rng = np.random.default_rng(seed=42)
idx = rng.choice(len(points), size=max_points, replace=False)
points = points[idx]
return points
def _cpd_rigid_to_2x3(R: np.ndarray, t: np.ndarray, s: float) -> np.ndarray:
"""
Convert CPD rigid parameters (R, t, s) to a 2×3 OpenCV affine matrix.
CPD rigid transform: T(y) = s * y @ R.T + t
Expanded for a row vector [x, y]:
x' = s*(R[0,0]*x + R[1,0]*y) + t[0]
y' = s*(R[0,1]*x + R[1,1]*y) + t[1]
"""
A = s * R # 2×2
return np.array([
[A[0, 0], A[1, 0], t[0]],
[A[0, 1], A[1, 1], t[1]],
], dtype=np.float64)
def _cpd_affine_to_2x3(B: np.ndarray, t: np.ndarray) -> np.ndarray:
"""
Convert CPD affine parameters (B, t) to a 2×3 OpenCV affine matrix.
CPD affine transform: T(y) = y @ B.T + t
Expanded:
x' = B[0,0]*x + B[1,0]*y + t[0]
y' = B[0,1]*x + B[1,1]*y + t[1]
"""
return np.array([
[B[0, 0], B[1, 0], t[0]],
[B[0, 1], B[1, 1], t[1]],
], dtype=np.float64)
def _points_to_dense_warp(
source_pts: np.ndarray,
target_pts: np.ndarray,
image_shape: Tuple[int, int],
) -> np.ndarray:
"""
Interpolate sparse point correspondences into a dense (H, W, 2) pixel-space
displacement field using the repo's `create_displacement_field`.
"""
return create_displacement_field(
source_pts,
target_pts,
image_shape,
method=RegistrationParams.INTERPOLATION_METHOD,
sigma=RegistrationParams.DISPLACEMENT_SIGMA,
max_displacement=RegistrationParams.MAX_DISPLACEMENT,
)
# ── 11. SIFT + RANSAC Affine ──────────────────────────────────────────────────
def run_sift_ransac(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
"""SIFT keypoint matching + RANSAC affine estimation."""
result = MethodResult(method="sift_ransac", label=METHOD_LABELS["sift_ransac"])
t0 = time.perf_counter()
try:
M = _keypoint_affine(source, target, descriptor="SIFT")
warped = cv2.warpAffine(source, M, (target.shape[1], target.shape[0]))
result.time_total_s = time.perf_counter() - t0
warped_mask = _warp_mask(source_mask, M)
_compute_image_metrics(target, warped, target_mask, warped_mask, result)
if fixed_lm is not None and moving_lm is not None:
M3 = np.vstack([M, [0, 0, 1]])
warped_lm = _warp_landmarks_affine(moving_lm, np.linalg.inv(M3))
_compute_landmark_metrics(fixed_lm, warped_lm, target.shape, result)
except Exception as exc:
result.note = str(exc)
return result
# ── 12. ICP ───────────────────────────────────────────────────────────────────
def run_icp(
source: np.ndarray,
target: np.ndarray,
source_mask: np.ndarray,
target_mask: np.ndarray,
fixed_lm: Optional[np.ndarray],
moving_lm: Optional[np.ndarray],
) -> MethodResult:
"""
Iterative Closest Point (Open3D) on subsampled tissue mask points.
The resulting rigid transform is applied to warp the full image.
"""
result = MethodResult(method="icp", label=METHOD_LABELS["icp"])
t0 = time.perf_counter()
try:
src_pts = _extract_tissue_points(source_mask)
tgt_pts = _extract_tissue_points(target_mask)
transform_4x4, _ = perform_icp_registration(src_pts, tgt_pts)