-
Notifications
You must be signed in to change notification settings - Fork 21
/
align.py
1288 lines (1098 loc) · 45.2 KB
/
align.py
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
import sys
import numpy as np
import SimpleITK as sitk
import bigstream.utility as ut
import time
from bigstream.configure_irm import configure_irm
from bigstream.transform import apply_transform, compose_transform_list, compress_transform_list
from bigstream.metrics import patch_mutual_information
from bigstream import features
import cv2
def apply_alignment_spacing(
fix,
mov,
fix_mask,
mov_mask,
fix_spacing,
mov_spacing,
alignment_spacing,
):
"""
Skip sample all images to as close to alignment_spacing as possible
Determine new voxel spacings
Parameters
----------
fix : nd-array
The fixed image
mov : nd-array
The moving image
fix_mask : nd-array
The fixed image mask (can be None)
Can have a different shape than fix, but assumed to have the same
domain or field of view
mov_mask : nd-array
The moving image mask (can be None)
Can have a different shape than mov, but assumed to have the same
domain or field of view
fix_spacing : 1d-array
The fixed image voxel spacing
mov_spacing : 1d-array
The moving image voxel spacing
Returns
-------
Returns 8 values in a tuple
1. skip sampled fixed image
2. skip sampled moving image
3. skip sampled fix_mask (or None)
4. skip sampled mov_mask (or None)
5. spacing of skip sampled fixed image
6. spacing of skip sampled moving image
7. spacing of skip sampled fixed mask (or None)
8. spacing of skip sampled moving mask (or None)
"""
# ensure spacings are floating point
fix_spacing = fix_spacing.astype(np.float64)
mov_spacing = mov_spacing.astype(np.float64)
# get mask spacings
fix_mask_spacing = None
if fix_mask is not None:
fix_mask_spacing = ut.relative_spacing(fix_mask.shape,
fix.shape,
fix_spacing)
mov_mask_spacing = None
if mov_mask is not None:
mov_mask_spacing = ut.relative_spacing(mov_mask.shape,
mov.shape,
mov_spacing)
# skip sample
if alignment_spacing:
fix, fix_spacing = ut.skip_sample(fix, fix_spacing, alignment_spacing)
mov, mov_spacing = ut.skip_sample(mov, mov_spacing, alignment_spacing)
if fix_mask is not None:
fix_mask, fix_mask_spacing = ut.skip_sample(
fix_mask, fix_mask_spacing, alignment_spacing,
)
if mov_mask is not None:
mov_mask, mov_mask_spacing = ut.skip_sample(
mov_mask, mov_mask_spacing, alignment_spacing,
)
return (fix, mov, fix_mask, mov_mask,
fix_spacing, mov_spacing, fix_mask_spacing, mov_mask_spacing,)
def images_to_sitk(
fix,
mov,
fix_mask,
mov_mask,
fix_spacing,
mov_spacing,
fix_mask_spacing,
mov_mask_spacing,
fix_origin,
mov_origin,
):
"""
Convert all image inputs to SimpleITK image objects
Parameters
----------
fix : nd-array
The fixed image
mov : nd-array
The moving image
fix_mask : nd-array
The fixed image mask (can be None)
mov_mask : nd-array
The moving image mask (can be None)
fix_spacing : 1d-array
The voxel spacing of the fixed image
mov_spacing : 1d-array
The voxel spacing of the moving image
fix_mask_spacing : 1d-array
The voxel spacing of the fixed image mask (can be None)
fix and fix_mask are assumed to have the same domain,
but this assumption can be slightly broken after skip_sampling
mov_mask_spacing : 1d-array
The voxel spacing of the moving image mask (can be None)
mov and mov_mask are assumed to have the same domain,
but this assumption can be slightly broken after skip_sampling
Returns
-------
Returns 4 values in a tuple
1. fix image as sitk.Image object
2. mov image as sitk.Image object
3. fix_mask as sitk.Image object (or None)
4. mov_mask as sitk.Image object (or None)
"""
fix = sitk.Cast(ut.numpy_to_sitk(
fix, fix_spacing, origin=fix_origin), sitk.sitkFloat32)
mov = sitk.Cast(ut.numpy_to_sitk(
mov, mov_spacing, origin=mov_origin), sitk.sitkFloat32)
if fix_mask is not None:
fix_mask = ut.numpy_to_sitk(
fix_mask, fix_mask_spacing, origin=fix_origin)
if mov_mask is not None:
mov_mask = ut.numpy_to_sitk(
mov_mask, mov_mask_spacing, origin=mov_origin)
return fix, mov, fix_mask, mov_mask
def format_static_transform_data(
transforms,
fix,
fix_spacing,
fix_origin,
):
"""
Set transform_spacings and transform_origins explicitly
Parameters
----------
transforms : list of nd-arrays
The list of static transforms
fix : nd-array
The fixed image
fix_spacing : 1d-array
The voxel spacing of the fixed image
fix_origin : 1d-array
The origin of the fixed image (can be None)
Returns
-------
Returns 2 values in a tuple
1. The tuple of transform spacings
2. The tuple of transform origins
"""
spacings = []
for transform in transforms:
spacing = fix_spacing
if len(transform.shape) not in [1, 2]:
spacing = ut.relative_spacing(transform.shape,
fix.shape,
fix_spacing)
spacings.append(spacing)
spacings = tuple(spacings)
origins = (fix_origin,)*len(transforms)
return (spacings, origins)
def feature_point_ransac_affine_align(
fix, mov,
fix_spacing,
mov_spacing,
blob_sizes,
alignment_spacing=None,
num_sigma_max=15,
cc_radius=12,
nspots=5000,
match_threshold=0.7,
max_spot_match_distance=None,
point_matches_threshold=50,
align_threshold=2.0,
diagonal_constraint=0.25,
fix_spot_detection_kwargs={},
mov_spot_detection_kwargs={},
fix_spots=None,
fix_spots_count_threshold=100,
mov_spots=None,
mov_spots_count_threshold=100,
fix_mask=None,
mov_mask=None,
fix_origin=None,
mov_origin=None,
static_transform_list=[],
default=None,
**kwargs,
):
"""
Currently this function only works on 3D images.
Compute an affine alignment from feature points and ransac.
A blob detector finds feature points in fix and mov. Correspondence
between the fix and mov point sets is estimated using neighborhood
correlation. A ransac filter determines the affine transform that brings
the largest number of corresponding points to the same locations.
At least 100 spots must be found in the fixed image and 100 spots
in the moving image, otherwise default is returned. At least 50
correspondence pairs must be found, otherwise default is returned.
These constraints are required for reasonable performance from the
ransac affine alignment algorithm.
If insufficient points are found modify fix_spot_detection_kwargs
and/or mov_spot_detection_kwargs. See bigstream.features.
If insufficient point matches are found, modify match_threshold.
Parameters
----------
fix : ndarray
the fixed image
mov : ndarray
the moving image; `fix.ndim` must equal `mov.ndim`
fix_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the fixed image.
Length must equal `fix.ndim`
mov_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the moving image.
Length must equal `mov.ndim`
blob_sizes : list of two floats
The [minimum, maximum] size of feature point objects in voxel units
num_sigma_max : scalar int (default: 15)
The maximum number of laplacians to use in the feature point LoG detector
cc_radius : scalar int (default: 12)
The halfwidth of neighborhoods around feature points used to determine
correlation and correspondence
nspots : scalar int (default: 5000)
The maximum number of feature point spots to use in each image
If more spots are found the brightest ones are used.
match_threshold : scalar float in range [0, 1] (default: 0.7)
The minimum correlation two feature point neighborhoods must have to
consider them corresponding points
max_spot_match_distance : scalar float (default: None)
The maximum distance a fix and mov spot can be before alignment
to still be considered matching spots; in microns. This helps
prevent false positive correspondences.
point_matches_threshold : scalar int (default: 50)
Minimum number of matching points for a valid alignment
align_threshold : scalar float (default: 2.0)
The maximum distance two points can be to be considered aligned
by the affine transform; in microns.
diagonal_constraint : scalar float (default: 0.25)
Diagonal entries of the affine matrix cannot be lower than
1 - diagonal_contraint or higher than 1 + diagonal_contraint.
If this condition is violated the default transform is returned.
This helps prevent bad alignments.
fix_spot_detection_kwargs : dict (default {})
Arguments passed to bigstream.features.blob_detection for fixed image
mov_spot_detection_kwargs : dict (default {})
Arguments passed to bigstream.features.blob_detection for moving image
fix_spots : nd-array Nx3 (default: None)
Skip the spot detection for the fixed image and provide your own spot coordinate
fix_spots_count_threshold : scalar int (default: 100)
Minimum number of fixed spots that need to exist for a valid alignment.
Note that many times in order to have a better alignment it is better to tweak
threshold and/or threshold_rel in fix_spot_detection_kwargs then to lower this value
mov_spots : nd-array Nx3 (default: None)
Skip the spot detection for the moving image and provide your own spot coordinate
mov_spots_count_threshold : scalar int (default: 100)
Minimum number of fixed spots that need to exist for a valid alignment.
Note that many times in order to have a better alignment it is better to tweak
threshold and/or threshold_rel in mov_spot_detection_kwargs then to lower this value
fix_mask : binary nd-array (default: None)
Spots from fixed image can only be found in the foreground of this mask
mov_mask : binary nd-array (default: None)
Spots from moving image can only be found in the foreground of this mask
fix_origin : 1d array (default: all zeros)
The origin of the fixed image in physical units
mov_origin : 1d array (default: all zeros)
The origin of the moving image in physical units
static_transform_list : list of numpy arrays (default: [])
Transforms applied to moving image before applying query transform
Assumed to have the same domain as the fixed image, though sampling
can be different. I.e. the origin and span are the same (in phyiscal
units) but the number of voxels can be different.
default : 2d array 4x4 (default: identity)
A default transform to return if the method fails to find a valid one
**kwargs : any additional keyword arguments
Passed to cv2.estimateAffine3D
Returns
-------
affine_matrix : 2d array 4x4
An affine matrix matching the moving image to the fixed image
"""
# establish default
if default is None: default = np.eye(fix.ndim + 1)
# apply static transforms
if static_transform_list:
mov = apply_transform(
fix, mov, fix_spacing, mov_spacing,
transform_list=static_transform_list,
fix_origin=fix_origin,
mov_origin=mov_origin,
)
if mov_mask is not None:
mov_mask = apply_transform(
fix.astype(mov_mask.dtype), mov_mask,
fix_spacing, mov_spacing,
transform_list=static_transform_list,
fix_origin=fix_origin,
mov_origin=mov_origin,
interpolator='0',
)
mov_spacing = fix_spacing
# skip sample and determine mask spacings
X = apply_alignment_spacing(
fix, mov,
fix_mask, mov_mask,
fix_spacing, mov_spacing,
alignment_spacing,
)
fix = X[0]
mov = X[1]
fix_mask = X[2]
mov_mask = X[3]
fix_spacing = X[4]
mov_spacing = X[5]
fix_mask_spacing = X[6]
mov_mask_spacing = X[7]
# get fix spots
num_sigma = int(min(blob_sizes[1] - blob_sizes[0], num_sigma_max))
assert num_sigma > 0, 'num_sigma must be greater than 0, make sure blob_sizes[1] > blob_sizes[0]'
print(f'{time.ctime(time.time())} computing fixed spots', flush=True)
if fix_spots is None:
fix_kwargs = {
'num_sigma':num_sigma,
'exclude_border':cc_radius,
}
fix_kwargs = {**fix_kwargs, **fix_spot_detection_kwargs}
print(f'{time.ctime(time.time())} fixed spots detection using',
fix_kwargs, flush=True)
fix_spots = features.blob_detection(
fix, blob_sizes[0], blob_sizes[1],
mask=fix_mask,
**fix_kwargs,
)
print(f'{time.ctime(time.time())} found {len(fix_spots)} fixed spots',
flush=True)
if len(fix_spots) < fix_spots_count_threshold:
print(f'{time.ctime(time.time())}',
'insufficient fixed spots found, returning default',
flush=True)
return default
# get mov spots
print(f'{time.ctime(time.time())} computing moving spots', flush=True)
if mov_spots is None:
mov_kwargs = {
'num_sigma':num_sigma,
'exclude_border':cc_radius,
}
mov_kwargs = {**mov_kwargs, **mov_spot_detection_kwargs}
print(f'{time.ctime(time.time())} moving spots detection using',
mov_kwargs, flush=True)
mov_spots = features.blob_detection(
mov, blob_sizes[0], blob_sizes[1],
mask=mov_mask,
**mov_kwargs,
)
print(f'{time.ctime(time.time())} found {len(mov_spots)} moving spots',
flush=True)
if len(mov_spots) < mov_spots_count_threshold:
print(f'{time.ctime(time.time())}',
'insufficient moving spots found, returning default',
flush=True)
return default
# sort
print(f'{time.ctime(time.time())} sorting spots', flush=True)
sort_idx = np.argsort(fix_spots[:, 3])[::-1]
fix_spots = fix_spots[sort_idx, :3][:nspots]
sort_idx = np.argsort(mov_spots[:, 3])[::-1]
mov_spots = mov_spots[sort_idx, :3][:nspots]
# get contexts
print(f'{time.ctime(time.time())} extracting contexts', flush=True)
fix_spot_contexts = features.get_contexts(fix, fix_spots, cc_radius)
mov_spot_contexts = features.get_contexts(mov, mov_spots, cc_radius)
# get pairwise correlations
print(f'{time.ctime(time.time())} computing pairwise correlations',
flush=True)
correlations = features.pairwise_correlation(
fix_spot_contexts, mov_spot_contexts,
)
# convert to physical units
fix_spots = fix_spots * fix_spacing
mov_spots = mov_spots * mov_spacing
# get matching points
fix_spots, mov_spots = features.match_points(
fix_spots, mov_spots,
correlations, match_threshold,
max_distance=max_spot_match_distance,
)
print(f'{time.ctime(time.time())} {len(fix_spots)} - {len(mov_spots)} matched spots',
flush=True)
if len(fix_spots) < point_matches_threshold or len(mov_spots) < point_matches_threshold:
print(f'{time.ctime(time.time())}',
'insufficient point matches found, returning default',
flush=True)
return default
# align
print(f'{time.ctime(time.time())}',
'Found enough spots to estimate the affine',
'fix:', len(fix_spots), ',',
'moving:', len(mov_spots),
flush=True)
_, Aff, _ = cv2.estimateAffine3D(
fix_spots, mov_spots,
ransacThreshold=align_threshold,
confidence=0.999,
**kwargs,
)
# ensure affine is sensible
if np.any( np.abs(np.diag(Aff) - 1) > diagonal_constraint ):
print(f'{time.ctime(time.time())}',
'Degenerate affine produced, returning default',
flush=True)
return default
# augment matrix and return
affine = np.eye(fix.ndim + 1)
affine[:fix.ndim, :] = Aff
return affine
def random_affine_search(
fix,
mov,
fix_spacing,
mov_spacing,
random_iterations,
nreturn=1,
max_translation=None,
max_rotation=None,
max_scale=None,
max_shear=None,
alignment_spacing=None,
fix_mask=None,
mov_mask=None,
fix_origin=None,
mov_origin=None,
static_transform_list=[],
use_patch_mutual_information=False,
print_running_improvements=False,
**kwargs,
):
"""
Apply random affine matrices within given bounds to moving image.
This function is intended to find good initialization for a full affine
alignment obtained by calling `affine_align`
Parameters
----------
fix : ndarray
the fixed image
mov : ndarray
the moving image; `fix.ndim` must equal `mov.ndim`
fix_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the fixed image.
Length must equal `fix.ndim`
mov_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the moving image.
Length must equal `mov.ndim`
random_iterations : int
The number of random affine matrices to sample
nreturn : int (default: 1)
The number of affine matrices to return. The best scoring results
are returned.
max_translation : float or tuple of float
The maximum amplitude translation allowed in random sampling.
Specified in physical units (e.g. um or mm)
Can be specified per axis.
max_rotation : float or tuple of float
The maximum amplitude rotation allowed in random sampling.
Specified in radians
Can be specified per axis.
max_scale : float or tuple of float
The maximum amplitude scaling allowed in random sampling.
Can be specified per axis.
max_shear : float or tuple of float
The maximum amplitude shearing allowed in random sampling.
Can be specified per axis.
alignment_spacing : float (default: None)
Fixed and moving images are skip sampled to a voxel spacing
as close as possible to this value. Intended for very fast
simple alignments (e.g. low amplitude motion correction)
fix_mask : binary ndarray (default: None)
A mask limiting metric evaluation region of the fixed image
Assumed to have the same domain as the fixed image, though sampling
can be different. I.e. the origin and span are the same (in phyiscal
units) but the number of voxels can be different.
mov_mask : binary ndarray (default: None)
A mask limiting metric evaluation region of the moving image
Assumed to have the same domain as the moving image, though sampling
can be different. I.e. the origin and span are the same (in phyiscal
units) but the number of voxels can be different.
fix_origin : 1d array (default: None)
Origin of the fixed image.
Length must equal `fix.ndim`
mov_origin : 1d array (default: None)
Origin of the moving image.
Length must equal `mov.ndim`
static_transform_list : list of numpy arrays (default: [])
Transforms applied to moving image before applying query transform
Assumed to have the same domain as the fixed image, though sampling
can be different. I.e. the origin and span are the same (in phyiscal
units) but the number of voxels can be different.
use_patch_mutual_information : bool (default: False)
Uses a custom metric function in bigstream.metrics
print_running_improvements : bool (default: False)
If True, whenever a better transform is found print the
iteration, score, and parameters
**kwargs : any additional arguments
Passed to `configure_irm` This is how you customize the metric.
If `use_path_mutual_information` is True this is passed to
the `patch_mutual_information` function instead.
Returns
-------
best transforms : sorted list of 4x4 numpy.ndarrays (affine matrices)
best nreturn results, first element of list is the best result
"""
# function to help generalize parameter limits to 3d
def expand_param_to_3d(param, null_value):
if isinstance(param, (int, float)):
param = (param,) * 2
if isinstance(param, tuple):
param += (null_value,)
return param
# TODO: consider moving to native 2D
# generalize 2d inputs to 3d
if fix.ndim == 2:
fix = fix.reshape(fix.shape + (1,))
mov = mov.reshape(mov.shape + (1,))
fix_spacing = tuple(fix_spacing) + (1.,)
mov_spacing = tuple(mov_spacing) + (1.,)
max_translation = expand_param_to_3d(max_translation, 0)
max_rotation = expand_param_to_3d(max_rotation, 0)
max_scale = expand_param_to_3d(max_scale, 1)
max_shear = expand_param_to_3d(max_shear, 0)
if fix_mask is not None: fix_mask = fix_mask.reshape(fix_mask.shape + (1,))
if mov_mask is not None: mov_mask = mov_mask.reshape(mov_mask.shape + (1,))
if fix_origin is not None: fix_origin = tuple(fix_origin) + (0.,)
if mov_origin is not None: mov_origin = tuple(mov_origin) + (0.,)
# generate random parameters, first row is always identity
params = np.zeros((random_iterations+1, 12))
params[:, 6:9] = 1 # default for scale params
F = lambda mx: 2 * (mx * np.random.rand(random_iterations, 3)) - mx
if max_translation: params[1:, 0:3] = F(max_translation)
if max_rotation: params[1:, 3:6] = F(max_rotation)
if max_scale: params[1:, 6:9] = np.e**F(np.log(max_scale))
if max_shear: params[1:, 9:] = F(max_shear)
center = np.array(fix.shape) / 2 * fix_spacing # center of rotation
# format static transform data explicitly
a, b = format_static_transform_data(
static_transform_list, fix, fix_spacing, fix_origin,
)
static_transform_spacing = a
static_transform_origin = b
# skip sample and determine mask spacings
X = apply_alignment_spacing(
fix, mov,
fix_mask, mov_mask,
fix_spacing, mov_spacing,
alignment_spacing,
)
fix = X[0]
mov = X[1]
fix_mask = X[2]
mov_mask = X[3]
fix_spacing = X[4]
mov_spacing = X[5]
fix_mask_spacing = X[6]
mov_mask_spacing = X[7]
# a useful value later, storing prevents redundant function calls
WORST_POSSIBLE_SCORE = np.finfo(np.float64).max
# define metric evaluation
if use_patch_mutual_information:
# wrap patch_mi metric
def score_affine(affine):
# apply transform
transform_list = static_transform_list + [affine,]
aligned = apply_transform(
fix, mov, fix_spacing, mov_spacing,
transform_list=transform_list,
fix_origin=fix_origin,
mov_origin=mov_origin,
transform_spacing=static_transform_spacing,
transform_origin=static_transform_origin,
)
mov_mask_aligned = None
if mov_mask is not None:
mov_mask_aligned = apply_transform(
fix_mask, mov_mask, fix_mask_spacing, mov_mask_spacing,
transform_list=transform_list,
fix_origin=fix_origin,
mov_origin=mov_origin,
transform_spacing=static_transform_spacing,
transform_origin=static_transform_origin,
interpolator='0',
)
# evaluate metric
# TODO: this function needs to be updated for different
# mask and image sizes
return patch_mutual_information(
fix, aligned, fix_spacing,
fix_mask=fix_mask,
mov_mask=mov_mask_aligned,
return_metric_image=False,
**kwargs,
)
# use an irm metric
else:
# construct irm, set images, masks, transforms
kwargs['optimizer'] = 'LBFGS2' # optimizer is not used, just a dummy value
kwargs['optimizer_args'] = {}
irm = configure_irm(**kwargs)
fix, mov, fix_mask, mov_mask = images_to_sitk(
fix, mov, fix_mask, mov_mask,
fix_spacing, mov_spacing,
fix_mask_spacing, mov_mask_spacing,
fix_origin, mov_origin,
)
if fix_mask is not None: irm.SetMetricFixedMask(fix_mask)
if mov_mask is not None: irm.SetMetricMovingMask(mov_mask)
if static_transform_list:
T = ut.transform_list_to_composite_transform(
static_transform_list,
static_transform_spacing,
static_transform_origin,
)
irm.SetMovingInitialTransform(T)
# wrap irm metric
def score_affine(affine):
irm.SetInitialTransform(ut.matrix_to_affine_transform(affine))
try:
return irm.MetricEvaluate(fix, mov)
except Exception as e:
return WORST_POSSIBLE_SCORE
# score all random affines
current_best_score = WORST_POSSIBLE_SCORE
scores = np.empty(random_iterations + 1, dtype=np.float64)
for iii, ppp in enumerate(params):
scores[iii] = score_affine(ut.physical_parameters_to_affine_matrix_3d(ppp, center))
if print_running_improvements and scores[iii] < current_best_score:
current_best_score = scores[iii]
print(f'{time.ctime(time.time())}',iii, ': ', current_best_score, '\n', ppp)
sys.stdout.flush()
# return top results
partition_indx = np.argpartition(scores, nreturn)[:nreturn]
params, scores = params[partition_indx], scores[partition_indx]
return [ut.physical_parameters_to_affine_matrix_3d(p, center) for p in params[np.argsort(scores)]]
def affine_align(
fix,
mov,
fix_spacing,
mov_spacing,
rigid=False,
initial_condition=None,
alignment_spacing=None,
fix_mask=None,
mov_mask=None,
fix_origin=None,
mov_origin=None,
static_transform_list=[],
default=None,
**kwargs,
):
"""
Affine or rigid alignment of a fixed/moving image pair.
Lots of flexibility in speed/accuracy trade off.
Highly configurable and useful in many contexts.
Parameters
----------
fix : ndarray
the fixed image
mov : ndarray
the moving image; `fix.ndim` must equal `mov.ndim`
fix_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the fixed image.
Length must equal `fix.ndim`
mov_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the moving image.
Length must equal `mov.ndim`
rigid : bool (default: False)
Restrict the alignment to rigid motion only
initial_condition : str or 4x4 ndarray (default: None)
How to begin the optimization. Only one string value is allowed:
"CENTER" in which case the alignment is initialized by a center
of mass alignment. If a 4x4 ndarray is given the optimization
is initialized with that transform.
alignment_spacing : float (default: None)
Fixed and moving images are skip sampled to a voxel spacing
as close as possible to this value. Intended for very fast
simple alignments (e.g. low amplitude motion correction)
fix_mask : binary ndarray (default: None)
A mask limiting metric evaluation region of the fixed image
Assumed to have the same domain as the fixed image, though sampling
can be different. I.e. the origin and span are the same (in phyiscal
units) but the number of voxels can be different.
mov_mask : binary ndarray (default: None)
A mask limiting metric evaluation region of the moving image
Assumed to have the same domain as the moving image, though sampling
can be different. I.e. the origin and span are the same (in phyiscal
units) but the number of voxels can be different.
fix_origin : 1d array (default: None)
Origin of the fixed image.
Length must equal `fix.ndim`
mov_origin : 1d array (default: None)
Origin of the moving image.
Length must equal `mov.ndim`
static_transform_list : list of numpy arrays (default: [])
Transforms applied to moving image before applying query transform
Assumed to have the same domain as the fixed image, though sampling
can be different. I.e. the origin and span are the same (in phyiscal
units) but the number of voxels can be different.
default : 4x4 array (default: identity matrix)
If the optimization fails, print error message but return this value
**kwargs : any additional arguments
Passed to `configure_irm`
This is where you would set things like:
metric, iterations, shrink_factors, and smooth_sigmas
Returns
-------
transform : 4x4 array
The affine or rigid transform matrix matching moving to fixed
"""
# determine the correct default
if default is None: default = np.eye(fix.ndim + 1)
initial_transform_given = isinstance(initial_condition, np.ndarray)
if initial_transform_given and np.all(default == np.eye(fix.ndim + 1)):
default = initial_condition
# format static transform data explicitly
a, b = format_static_transform_data(
static_transform_list, fix, fix_spacing, fix_origin,
)
static_transform_spacing = a
static_transform_origin = b
# skip sample and convert inputs to sitk images
X = apply_alignment_spacing(
fix, mov,
fix_mask, mov_mask,
fix_spacing, mov_spacing,
alignment_spacing,
)
fix, mov, fix_mask, mov_mask = images_to_sitk(
*X, fix_origin, mov_origin,
)
fix_spacing = X[4]
mov_spacing = X[5]
fix_mask_spacing = X[6]
mov_mask_spacing = X[7]
# set up registration object
irm = configure_irm(**kwargs)
# set initial static transforms
if static_transform_list:
T = ut.transform_list_to_composite_transform(
static_transform_list,
static_transform_spacing,
static_transform_origin,
)
irm.SetMovingInitialTransform(T)
# distinguish between 2D and 3D for rigid transforms
ndims = fix.GetDimension()
rigid_transform_constructor = sitk.Euler2DTransform if ndims == 2 else sitk.Euler3DTransform
# set transform to optimize
if isinstance(initial_condition, str) and initial_condition == "CENTER":
a, b = fix, mov
if fix_mask is not None and mov_mask is not None:
a, b = fix_mask, mov_mask
x = sitk.CenteredTransformInitializer(a, b, rigid_transform_constructor())
x = rigid_transform_constructor(x).GetTranslation()[::-1]
initial_condition = np.eye(ndims+1)
initial_condition[:ndims, -1] = x
initial_transform_given = True
if rigid and not initial_transform_given:
transform = rigid_transform_constructor()
elif rigid and initial_transform_given:
transform = ut.matrix_to_euler_transform(initial_condition)
elif not rigid and not initial_transform_given:
transform = sitk.AffineTransform(fix.GetDimension())
elif not rigid and initial_transform_given:
transform = ut.matrix_to_affine_transform(initial_condition)
irm.SetInitialTransform(transform, inPlace=True)
# set masks
if fix_mask is not None: irm.SetMetricFixedMask(fix_mask)
if mov_mask is not None: irm.SetMetricMovingMask(mov_mask)
# execute alignment, for any exceptions return default
try:
initial_metric_value = irm.MetricEvaluate(fix, mov)
irm.Execute(fix, mov)
final_metric_value = irm.MetricEvaluate(fix, mov)
except Exception as e:
print(f'{time.ctime(time.time())}',
'Registration failed due to ITK exception:\n', e,
flush=True)
print(f'{time.ctime(time.time())} Returning default',
flush=True)
return default
# if registration improved metric return result
# otherwise return default
if final_metric_value < initial_metric_value:
print(f'{time.ctime(time.time())} Registration succeeded',
flush=True)
return ut.affine_transform_to_matrix(transform)
else:
print(f'{time.ctime(time.time())} Optimization failed to improve metric',
flush=True)
print(f'{time.ctime(time.time())}',
f'METRIC VALUES initial: {initial_metric_value} final: {final_metric_value}',
flush=True)
print(f'{time.ctime(time.time())} Returning default',
flush=True)
return default
def deformable_align(
fix,
mov,
fix_spacing,
mov_spacing,
control_point_spacing,
control_point_levels,
alignment_spacing=None,
fix_mask=None,
mov_mask=None,
fix_origin=None,
mov_origin=None,
static_transform_list=[],
default=None,
**kwargs,
):
"""
Register moving to fixed image with a bspline parameterized deformation field
Parameters
----------
fix : ndarray
the fixed image
mov : ndarray
the moving image; `fix.ndim` must equal `mov.ndim`
fix_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the fixed image.
Length must equal `fix.ndim`
mov_spacing : 1d array
The spacing in physical units (e.g. mm or um) between voxels
of the moving image.
control_point_spacing : float
The spacing in physical units (e.g. mm or um) between control