forked from dipy/dipy
/
imwarp.py
1708 lines (1437 loc) · 70 KB
/
imwarp.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
""" Classes and functions for Symmetric Diffeomorphic Registration """
from __future__ import print_function
import abc
from dipy.utils.six import with_metaclass
import numpy as np
import numpy.linalg as npl
import scipy as sp
import nibabel as nib
import dipy.align.vector_fields as vfu
from dipy.align import floating
from dipy.align import VerbosityLevels
from dipy.align import Bunch
RegistrationStages = Bunch(INIT_START=0,
INIT_END=1,
OPT_START=2,
OPT_END=3,
SCALE_START=4,
SCALE_END=5,
ITER_START=6,
ITER_END=7)
r"""Registration Stages
This enum defines the different stages which the Volumetric Registration
may be in. The value of the stage is passed as a parameter to the call-back
function so that it can react accordingly.
INIT_START: optimizer initialization starts
INIT_END: optimizer initialization ends
OPT_START: optimization starts
OPT_END: optimization ends
SCALE_START: optimization at a new scale space resolution starts
SCALE_END: optimization at the current scale space resolution ends
ITER_START: a new iteration starts
ITER_END: the current iteration ends
"""
def mult_aff(A, B):
r"""Returns the matrix product A.dot(B) considering None as the identity
Parameters
----------
A : array, shape (n,k)
B : array, shape (k,m)
Returns
-------
The matrix product A.dot(B). If any of the input matrices is None, it is
treated as the identity matrix. If both matrices are None, None is returned.
"""
if A is None:
return B
elif B is None:
return A
return A.dot(B)
def get_direction_and_spacings(affine, dim):
r"""Extracts the rotational and spacing components from a matrix
Extracts the rotational and spacing (voxel dimensions) components from a
matrix. An image gradient represents the local variation of the image's gray
values per voxel. Since we are iterating on the physical space, we need to
compute the gradients as variation per millimeter, so we need to divide each
gradient's component by the voxel size along the corresponding axis, that's
what the spacings are used for. Since the image's gradients are oriented
along the grid axes, we also need to re-orient the gradients to be given
in physical space coordinates.
Parameters
----------
affine : array, shape (k, k), k = 3, 4
the matrix transforming grid coordinates to physical space.
Returns
-------
direction : array, shape (k-1, k-1)
the rotational component of the input matrix
spacings : array, shape (k-1,)
the scaling component (voxel size) of the matrix
"""
if affine is None:
return np.eye(dim), np.ones(dim)
dim = affine.shape[1]-1
#Temporary hack: get the zooms by building a nifti image
affine4x4 = np.eye(4)
empty_volume = np.zeros((0,0,0))
affine4x4[:dim, :dim] = affine[:dim, :dim]
affine4x4[:dim, 3] = affine[:dim, dim-1]
nib_nifti = nib.Nifti1Image(empty_volume, affine4x4)
scalings = np.asarray(nib_nifti.get_header().get_zooms())
scalings = np.asarray(scalings[:dim], dtype = np.float64)
A = affine[:dim,:dim]
return A.dot(np.diag(1.0/scalings)), scalings
class ScaleSpace(object):
def __init__(self, image, num_levels,
codomain_affine=None,
input_spacing=None,
sigma_factor=0.2,
mask0=False):
r""" ScaleSpace
Computes the Scale Space representation of an image. The scale space is
simply a list of images produced by smoothing the input image with a
Gaussian kernel with increasing smoothing parameter. If the image's
voxels are isotropic, the smoothing will be the same along all
directions: at level L = 0,1,..., the sigma is given by s * ( 2^L - 1 ).
If the voxel dimensions are not isotropic, then the smoothing is
weaker along low resolution directions.
Parameters
----------
image : array, shape (r,c) or (s, r, c) where s is the number of slices,
r is the number of rows and c is the number of columns of the input
image.
num_levels : int
the desired number of levels (resolutions) of the scale space
codomain_affine : array, shape (k, k), k=3,4 (for either 2D or 3D images)
the matrix transforming voxel coordinates to space coordinates in
the input image discretization
input_spacing : array, shape (k-1,)
the spacing (voxel size) between voxels in physical space
sigma_factor : float
the smoothing factor to be used in the construction of the scale
space.
mask0 : Boolean
if True, all smoothed images will be zero at all voxels that are
zero in the input image.
"""
self.dim = len(image.shape)
self.num_levels = num_levels
input_size = np.array(image.shape)
if mask0:
mask = np.asarray(image>0, dtype=np.int32)
#normalize input image to [0,1]
img = (image - image.min())/(image.max() - image.min())
if mask0:
img *= mask
#The properties are saved in separate lists. Insert input image
#properties at the first level of the scale space
self.images = [img.astype(floating)]
self.domain_shapes = [input_size.astype(np.int32)]
if input_spacing is None:
input_spacing = np.ones((self.dim,), dtype = np.int32)
self.spacings = [input_spacing]
self.scalings = [np.ones(self.dim)]
self.affines = [codomain_affine]
self.sigmas = [np.zeros(self.dim)]
if codomain_affine is not None:
self.affine_invs = [npl.inv(codomain_affine)]
else:
self.affine_invs = [None]
#compute the rest of the levels
min_spacing = np.min(input_spacing)
for i in range(1, num_levels):
scaling_factor = 2**i
scaling = np.ndarray((self.dim+1,))
#Note: the minimum below is present in ANTS to prevent the scaling
#from being too large (making the sub-sampled image to be too small)
#this makes the sub-sampled image at least 32 voxels at each
#direction it is risky to make this decision based on image size,
#though (we need to investigate more the effect of this)
#scaling = np.minimum(scaling_factor * min_spacing / input_spacing,
# input_size / 32)
scaling = scaling_factor * min_spacing / input_spacing
output_spacing = input_spacing * scaling
extended = np.append(scaling, [1])
if not codomain_affine is None:
affine = codomain_affine.dot(np.diag(extended))
else:
affine = np.diag(extended)
output_size = input_size * (input_spacing / output_spacing) + 0.5
output_size = output_size.astype(np.int32)
sigmas = sigma_factor * (output_spacing / input_spacing - 1.0)
#filter along each direction with the appropriate sigma
filtered = sp.ndimage.filters.gaussian_filter(image, sigmas)
filtered = ((filtered - filtered.min())/
(filtered.max() - filtered.min()))
if mask0:
filtered *= mask
#Add current level to the scale space
self.images.append(filtered.astype(floating))
self.domain_shapes.append(output_size)
self.spacings.append(output_spacing)
self.scalings.append(scaling)
self.affines.append(affine)
self.affine_invs.append(npl.inv(affine))
self.sigmas.append(sigmas)
def get_expand_factors(self, from_level, to_level):
r"""Ratio of voxel size from pyramid level from_level to to_level
Given two scale space resolutions a = from_level, b = to_level,
returns the ratio of voxels size at level b to voxel size at level a
(the factor that must be used to multiply voxels at level a to
'expand' them to level b).
Parameters
----------
from_level : int, 0 <= from_level < L, (L = number of resolutions)
the resolution to expand voxels from
to_level : int, 0 <= to_level < from_level
the resolution to expand voxels to
Returns
-------
factors : array, shape (k,), k = 2, 3
the expand factors (a scalar for each voxel dimension)
"""
factors = (np.array(self.spacings[to_level]) /
np.array(self.spacings[from_level]) )
return factors
def print_level(self, level):
r"""Prints properties of a pyramid level
Prints the properties of a level of this scale space to standard output
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to be printed
"""
print('Domain shape: ', self.get_domain_shape(level))
print('Spacing: ', self.get_spacing(level))
print('Scaling: ', self.get_scaling(level))
print('Affine: ', self.get_affine(level))
print('Sigmas: ', self.get_sigmas(level))
def _get_attribute(self, attribute, level):
r"""Returns an attribute from the Scale Space at a given level
Returns the level-th element of attribute if level is a valid level
of this scale space. Otherwise, returns None.
Parameters
----------
attribute : list
the attribute to retrieve the level-th element from
level : int,
the index of the required element from attribute.
Returns
-------
attribute[level] : object
the requested attribute if level is valid, else it raises
a ValueError
"""
if 0 <= level < self.num_levels:
return attribute[level]
raise ValueError('Invalid pyramid level: '+str(level))
def get_image(self, level):
r"""Smoothed image at a given level
Returns the smoothed image at the requested level in the Scale Space.
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smooth image from
Returns
-------
the smooth image at the requested resolution or None if an invalid
level was requested
"""
return self._get_attribute(self.images, level)
def get_domain_shape(self, level):
r"""Shape the sub-sampled image must have at a particular level
Returns the shape the sub-sampled image must have at a particular
resolution of the scale space (note that this object does not explicitly
subsample the smoothed images, but only provides the properties
the sub-sampled images must have).
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the sub-sampled shape from
Returns
-------
the sub-sampled shape at the requested resolution or None if an
invalid level was requested
"""
return self._get_attribute(self.domain_shapes, level)
def get_spacing(self, level):
r"""Spacings the sub-sampled image must have at a particular level
Returns the spacings (voxel sizes) the sub-sampled image must have at a
particular resolution of the scale space (note that this object does
not explicitly subsample the smoothed images, but only provides the
properties the sub-sampled images must have).
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the sub-sampled shape from
Returns
-------
the spacings (voxel sizes) at the requested resolution or None if an
invalid level was requested
"""
return self._get_attribute(self.spacings, level)
def get_scaling(self, level):
r"""Adjustment factor for input-spacing to reflect voxel sizes at level
Returns the scaling factor that needs to be applied to the input spacing
(the voxel sizes of the image at level 0 of the scale space) to
transform them to voxel sizes at the requested level.
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the scalings from
Returns
-------
the scaling factors from the original spacing to the spacings at the
requested level
"""
return self._get_attribute(self.scalings, level)
def get_affine(self, level):
r"""Voxel-to-space transformation at a given level
Returns the voxel-to-space transformation associated to the sub-sampled
image at a particular resolution of the scale space (note that this
object does not explicitly subsample the smoothed images, but only
provides the properties the sub-sampled images must have).
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get affine transform from
Returns
-------
the affine (voxel-to-space) transform at the requested resolution or
None if an invalid level was requested
"""
return self._get_attribute(self.affines, level)
def get_affine_inv(self, level):
r"""Space-to-voxel transformation at a given level
Returns the space-to-voxel transformation associated to the sub-sampled
image at a particular resolution of the scale space (note that this
object does not explicitly subsample the smoothed images, but only
provides the properties the sub-sampled images must have).
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the inverse transform from
Returns
-------
the inverse (space-to-voxel) transform at the requested resolution or
None if an invalid level was requested
"""
return self._get_attribute(self.affine_invs, level)
def get_sigmas(self, level):
r"""Smoothing parameters used at a given level
Returns the smoothing parameters (a scalar for each axis) used at the
requested level of the scale space
Parameters
----------
level : int, 0 <= from_level < L, (L = number of resolutions)
the scale space level to get the smoothing parameters from
Returns
-------
the smoothing parameters at the requested level
"""
return self._get_attribute(self.sigmas, level)
class DiffeomorphicMap(object):
def __init__(self,
dim,
disp_shape,
disp_affine=None,
domain_shape=None,
domain_affine=None,
codomain_shape=None,
codomain_affine=None,
prealign=None):
r""" DiffeomorphicMap
Implements a diffeomorphic transformation on the physical space. The
deformation fields encoding the direct and inverse transformations
share the same domain discretization (both the discretization grid shape
and voxel-to-space matrix). The input coordinates (physical coordinates)
are first aligned using prealign, and then displaced using the
corresponding vector field interpolated at the aligned coordinates.
Parameters
----------
dim : int, 2 or 3
the transformation's dimension
disp_shape : array, shape (dim,)
the number of slices (if 3D), rows and columns of the deformation
field's discretization
disp_affine : the voxel-to-space transformation between the deformation field's
grid and space
domain_shape : array, shape (dim,)
the number of slices (if 3D), rows and columns of the default
discretizatio of this map's domain
domain_affine : array, shape (dim+1, dim+1)
the default voxel-to-space transformation between this map's
discretization and physical space
codomain_shape : array, shape (dim,)
the number of slices (if 3D), rows and columns of the images that
are 'normally' warped using this transformation in the forward
direction (this will provide default transformation parameters to
warp images under this transformation). By default, we assume that
the inverse transformation is 'normally' used to warp images with
the same discretization and voxel-to-space transformation as the
deformation field grid.
codomain_affine : array, shape (dim+1, dim+1)
the voxel-to-space transformation of images that are 'normally'
warped using this transformation (in the forward direction).
prealign : array, shape (dim+1, dim+1)
the linear transformation to be applied to align input images to
the reference space before warping under the deformation field.
"""
self.dim = dim
if(disp_shape is None):
raise ValueError("Invalid displacement field discretization")
self.disp_shape = np.asarray(disp_shape, dtype = np.int32)
# If the discretization affine is None, we assume it's the identity
self.disp_affine = disp_affine
if(self.disp_affine is None):
self.disp_affine_inv = None
else:
self.disp_affine_inv = npl.inv(self.disp_affine)
# If domain_shape is not provided, we use the map's discretization shape
if(domain_shape is None):
self.domain_shape = self.disp_shape
else:
self.domain_shape = np.asarray(domain_shape, dtype = np.int32)
self.domain_affine = domain_affine
if(domain_affine is None):
self.domain_affine_inv = None
else:
self.domain_affine_inv = npl.inv(domain_affine)
# If codomain shape was not provided, we assume it is an endomorphism:
# use the same domain_shape and codomain_affine as the field domain
if codomain_shape is None:
self.codomain_shape = self.domain_shape
else:
self.codomain_shape = np.asarray(codomain_shape, dtype = np.int32)
self.codomain_affine = codomain_affine
if codomain_affine is None:
self.codomain_affine_inv = None
else:
self.codomain_affine_inv = npl.inv(codomain_affine)
self.prealign = prealign
if prealign is None:
self.prealign_inv = None
else:
self.prealign_inv = npl.inv(prealign)
self.is_inverse = False
self.forward = None
self.backward = None
def get_forward_field(self):
r"""Deformation field to transform an image in the forward direction
Returns the deformation field that must be used to warp an image under
this transformation in the forward direction (note the 'is_inverse'
flag).
"""
if self.is_inverse:
return self.backward
else:
return self.forward
def get_backward_field(self):
r"""Deformation field to transform an image in the backward direction
Returns the deformation field that must be used to warp an image under
this transformation in the backward direction (note the 'is_inverse'
flag).
"""
if self.is_inverse:
return self.forward
else:
return self.backward
def allocate(self):
r"""Creates a zero displacement field
Creates a zero displacement field (the identity transformation).
"""
self.forward = np.zeros(tuple(self.disp_shape)+(self.dim,),
dtype=floating)
self.backward = np.zeros(tuple(self.disp_shape)+(self.dim,),
dtype=floating)
def _get_warping_function(self, interpolation):
r"""Appropriate warping function for the given interpolation type
Returns the right warping function from vector_fields that must be
called for the specified data dimension and interpolation type
"""
if self.dim == 2:
if interpolation == 'linear':
return vfu.warp_2d
else:
return vfu.warp_2d_nn
else:
if interpolation == 'linear':
return vfu.warp_3d
else:
return vfu.warp_3d_nn
def _warp_forward(self, image, interpolation='linear', world_to_image=None,
sampling_shape=None, sampling_affine=None):
r"""Warps an image in the forward direction
Deforms the input image under this diffeomorphic map in the forward
direction. Since the mapping is defined in the physical space, the user
must specify the sampling grid shape and its space-to-voxel mapping.
By default, the transformation will use the discretization information
given at initialization.
Parameters
----------
image : array, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the forward
direction
interpolation : string, either 'linear' or 'nearest'
the type of interpolation to be used for warping, either 'linear'
(for k-linear interpolation) or 'nearest' for nearest neighbor
world_to_image : array, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel
coordinates of the image given as input
sampling_shape : array, shape (dim,)
the number of slices, rows and columns of the desired warped image
sampling_affine : the transformation bringing voxel coordinates of the
warped image to physical space
Returns
-------
warped : array, shape = sampling_shape or self.codomain_shape if None
the warped image under this transformation in the forward direction
Notes
-----
A diffeomorphic map must be thought as a mapping between points
in space. Warping an image J towards an image I means transforming
each voxel with (discrete) coordinates i in I to (floating-point) voxel
coordinates j in J. The transformation we consider 'forward' is
precisely mapping coordinates i from the input image to coordinates j
from reference image, which has the effect of warping an image with
reference discretization (typically, the "static image") "towards" an
image with input discretization (typically, the "moving image"). More
precisely, the warped image is produced by the following interpolation:
warped[i] = image[W * forward[Dinv * P * S * i] + W * P * S * i )]
where i denotes the coordinates of a voxel in the input grid, W is
the world-to-grid transformation of the image given as input, Dinv
is the world-to-grid transformation of the deformation field
discretization, P is the pre-aligning matrix (transforming input
points to reference points), S is the voxel-to-space transformation of
the sampling grid (see comment below) and forward is the forward
deformation field.
If we want to warp an image, we also must specify on what grid we
want to sample the resulting warped image (the images are considered as
points in space and its representation on a grid depends on its
grid-to-space transform telling us for each grid voxel what point in
space we need to bring via interpolation). So, S is the matrix that
converts the sampling grid (whose shape is given as parameter
'sampling_shape' ) to space coordinates.
"""
#if no world-to-image transform is provided, we use the codomain info
if world_to_image is None:
world_to_image = self.codomain_affine_inv
#if no sampling info is provided, we use the domain info
if sampling_shape is None:
if self.domain_shape is None:
raise ValueError('Unable to infer sampling info. '
'Provide a valid sampling_shape.')
sampling_shape = self.domain_shape
else:
sampling_shape = np.asarray(sampling_shape, dtype=np.int32)
if sampling_affine is None:
sampling_affine = self.domain_affine
W = None if world_to_image == 'identity' else world_to_image
Dinv = self.disp_affine_inv
P = self.prealign
S = None if sampling_affine == 'identity' else sampling_affine
#this is the matrix which we need to multiply the voxel coordinates
#to interpolate on the forward displacement field ("in"side the
#'forward' brackets in the expression above)
affine_idx_in = mult_aff(Dinv, mult_aff(P, S))
#this is the matrix which we need to multiply the voxel coordinates
#to add to the displacement ("out"side the 'forward' brackets in the
#expression above)
affine_idx_out = mult_aff(W, mult_aff(P, S))
#this is the matrix which we need to multiply the displacement vector
#prior to adding to the transformed input point
affine_disp = W
#Convert the data to the required types to use the cythonized functions
if interpolation == 'nearest':
if image.dtype is np.dtype('float64') and floating is np.float32:
image = image.astype(floating)
elif image.dtype is np.dtype('int64'):
image = image.astype(np.int32)
else:
image = np.asarray(image, dtype=floating)
warp_f = self._get_warping_function(interpolation)
warped = warp_f(image, self.forward, affine_idx_in, affine_idx_out,
affine_disp, sampling_shape)
return warped
def _warp_backward(self, image, interpolation='linear', world_to_image=None,
sampling_shape=None, sampling_affine=None):
r"""Warps an image in the backward direction
Deforms the input image under this diffeomorphic map in the backward
direction. Since the mapping is defined in the physical space, the user
must specify the sampling grid shape and its space-to-voxel mapping.
By default, the transformation will use the discretization information
given at initialization.
Parameters
----------
image : array, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the backward
direction
interpolation : string, either 'linear' or 'nearest'
the type of interpolation to be used for warping, either 'linear'
(for k-linear interpolation) or 'nearest' for nearest neighbor
world_to_image : array, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel
coordinates of the image given as input
sampling_shape : array, shape (dim,)
the number of slices, rows and columns of the desired warped image
sampling_affine : the transformation bringing voxel coordinates of the
warped image to physical space
Returns
-------
warped : array, shape = sampling_shape or self.domain_shape if None
the warped image under this transformation in the backward direction
Notes
-----
A diffeomorphic map must be thought as a mapping between points
in space. Warping an image J towards an image I means transforming
each voxel with (discrete) coordinates i in I to (floating-point) voxel
coordinates j in J. The transformation we consider 'backward' is
precisely mapping coordinates i from the reference grid to coordinates j
from the input image (that's why it's "backward"), which has the effect
of warping the input image (moving) "towards" the reference. More
precisely, the warped image is produced by the following interpolation:
warped[i]= image[W * Pinv * backward[Dinv * S * i] + W * Pinv * S * i )]
where i denotes the coordinates of a voxel in the input grid, W is
the world-to-grid transformation of the image given as input, Dinv
is the world-to-grid transformation of the deformation field
discretization, Pinv is the pre-aligning matrix's inverse (transforming
reference points to input points), S is the grid-to-space transformation
of the sampling grid (see comment below) and backward is the backward
deformation field.
If we want to warp an image, we also must specify on what grid we
want to sample the resulting warped image (the images are considered as
points in space and its representation on a grid depends on its
grid-to-space transform telling us for each grid voxel what point in
space we need to bring via interpolation). So, S is the matrix that
converts the sampling grid (whose shape is given as parameter
'sampling_shape' ) to space coordinates.
"""
#if no world-to-image transform is provided, we use the domain info
if world_to_image is None:
world_to_image = self.domain_affine_inv
#if no sampling info is provided, we use the codomain info
if sampling_shape is None:
if self.codomain_shape is None:
raise ValueError('Unable to infer sampling info. Provide a valid sampling_shape.')
sampling_shape = self.codomain_shape
if sampling_affine is None:
sampling_affine = self.codomain_affine
W = None if world_to_image == 'identity' else world_to_image
Dinv = self.disp_affine_inv
Pinv = self.prealign_inv
S = None if sampling_affine == 'identity' else sampling_affine
#this is the matrix which we need to multiply the voxel coordinates
#to interpolate on the backward displacement field ("in"side the
#'backward' brackets in the expression above)
affine_idx_in = mult_aff(Dinv, S)
#this is the matrix which we need to multiply the voxel coordinates
#to add to the displacement ("out"side the 'backward' brackets in the
#expression above)
affine_idx_out = mult_aff(W, mult_aff(Pinv, S))
#this is the matrix which we need to multiply the displacement vector
#prior to adding to the transformed input point
affine_disp = mult_aff(W, Pinv)
if interpolation == 'nearest':
if image.dtype is np.dtype('float64') and floating is np.float32:
image = image.astype(floating)
elif image.dtype is np.dtype('int64'):
image = image.astype(np.int32)
else:
image = np.asarray(image, dtype=floating)
warp_f = self._get_warping_function(interpolation)
warped = warp_f(image, self.backward, affine_idx_in, affine_idx_out,
affine_disp, sampling_shape)
return warped
def transform(self, image, interpolation='linear', world_to_image=None,
sampling_shape=None, sampling_affine=None):
r"""Warps an image in the forward direction
Transforms the input image under this transformation in the forward
direction. It uses the "is_inverse" flag to switch between "forward"
and "backward" (if is_inverse is False, then transform(...) warps the
image forwards, else it warps the image backwards).
Parameters
----------
image : array, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the forward
direction
interpolation : string, either 'linear' or 'nearest'
the type of interpolation to be used for warping, either 'linear'
(for k-linear interpolation) or 'nearest' for nearest neighbor
world_to_image : array, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel
coordinates of the image given as input
sampling_shape : array, shape (dim,)
the number of slices, rows and columns of the desired warped image
sampling_affine : the transformation bringing voxel coordinates of the
warped image to physical space
Returns
-------
warped : array, shape = sampling_shape or self.codomain_shape if None
the warped image under this transformation in the forward direction
Notes
-----
See _warp_forward and _warp_backward documentation for further
information.
"""
if sampling_shape is not None:
sampling_shape = np.asarray(sampling_shape, dtype=np.int32)
if self.is_inverse:
warped = self._warp_backward(image, interpolation, world_to_image,
sampling_shape, sampling_affine)
else:
warped = self._warp_forward(image, interpolation, world_to_image,
sampling_shape, sampling_affine)
return np.asarray(warped)
def transform_inverse(self, image, interpolation='linear', world_to_image=None,
sampling_shape=None, sampling_affine=None):
r"""Warps an image in the backward direction
Transforms the input image under this transformation in the backward
direction. It uses the "is_inverse" flag to switch between "forward"
and "backward" (if is_inverse is False, then transform_inverse(...)
warps the image backwards, else it warps the image forwards)
Parameters
----------
image : array, shape (s, r, c) if dim = 3 or (r, c) if dim = 2
the image to be warped under this transformation in the forward
direction
interpolation : string, either 'linear' or 'nearest'
the type of interpolation to be used for warping, either 'linear'
(for k-linear interpolation) or 'nearest' for nearest neighbor
world_to_image : array, shape (dim+1, dim+1)
the transformation bringing world (space) coordinates to voxel
coordinates of the image given as input
sampling_shape : array, shape (dim,)
the number of slices, rows and columns of the desired warped image
sampling_affine : the transformation bringing voxel coordinates of the
warped image to physical space
Returns
-------
warped : array, shape = sampling_shape or self.codomain_shape if None
the warped image under this transformation in the backward direction
Notes
-----
See _warp_forward and _warp_backward documentation for further
information.
"""
if self.is_inverse:
warped = self._warp_forward(image, interpolation, world_to_image,
sampling_shape, sampling_affine)
else:
warped = self._warp_backward(image, interpolation, world_to_image,
sampling_shape, sampling_affine)
return np.asarray(warped)
def inverse(self):
r"""Inverse of this DiffeomorphicMap instance
Returns a diffeomorphic map object representing the inverse of this
transformation. The internal arrays are not copied but just referenced.
Returns
-------
inv : DiffeomorphicMap object
the inverse of this diffeomorphic map.
"""
inv = DiffeomorphicMap(self.dim,
self.disp_shape,
self.disp_affine,
self.domain_shape,
self.domain_affine,
self.codomain_shape,
self.codomain_affine,
self.prealign)
inv.forward = self.forward
inv.backward = self.backward
inv.is_inverse = True
return inv
def expand_fields(self, expand_factors, new_shape):
r"""Expands the displacement fields from current shape to new_shape
Up-samples the discretization of the displacement fields to be of
new_shape shape.
Parameters
----------
expand_factors : array, shape (dim,)
the factors scaling current spacings (voxel sizes) to spacings in
the expanded discretization.
new_shape : array, shape (dim,)
the shape of the arrays holding the up-sampled discretization
"""
if self.dim == 2:
expand_f = vfu.resample_displacement_field_2d
else:
expand_f = vfu.resample_displacement_field_3d
expanded_forward = expand_f(self.forward, expand_factors, new_shape)
expanded_backward = expand_f(self.backward, expand_factors, new_shape)
expand_factors = np.append(expand_factors, [1])
expanded_affine = mult_aff(self.disp_affine, np.diag(expand_factors))
expanded_affine_inv = npl.inv(expanded_affine)
self.forward = expanded_forward
self.backward = expanded_backward
self.disp_shape = new_shape
self.disp_affine = expanded_affine
self.disp_affine_inv = expanded_affine_inv
def compute_inversion_error(self):
r"""Inversion error of the displacement fields
Estimates the inversion error of the displacement fields by computing
statistics of the residual vectors obtained after composing the forward
and backward displacement fields.
Returns
-------
residual : array, shape (R, C) or (S, R, C)
the displacement field resulting from composing the forward and
backward displacement fields of this transformation (the residual
should be zero for a perfect diffeomorphism)
stats : array, shape (3,)
statistics from the norms of the vectors of the residual
displacement field: maximum, mean and standard deviation
Notes
-----
Since the forward and backward displacement fields have the same
discretization, the final composition is given by
comp[i] = forward[ i + Dinv * backward[i]]
where Dinv is the space-to-grid transformation of the displacement
fields
"""
Dinv = self.disp_affine_inv
if self.dim == 2:
compose_f = vfu.compose_vector_fields_2d
else:
compose_f = vfu.compose_vector_fields_3d
residual, stats = compose_f(self.backward, self.forward,
None, Dinv, 1.0, None)
return np.asarray(residual), np.asarray(stats)
def shallow_copy(self):
r"""Shallow copy of this DiffeomorphicMap instance
Creates a shallow copy of this diffeomorphic map (the arrays are not
copied but just referenced)
Returns
-------
new_map : DiffeomorphicMap object
the shallow copy of this diffeomorphic map
"""
new_map = DiffeomorphicMap(self.dim,
self.disp_shape,
self.disp_affine,
self.domain_shape,
self.domain_affine,
self.codomain_shape,
self.codomain_affine,
self.prealign)
new_map.forward = self.forward
new_map.backward = self.backward
new_map.is_inverse = self.is_inverse
return new_map
def warp_endomorphism(self, phi):
r"""Composition of this DiffeomorphicMap with a given endomorphism
Creates a new DiffeomorphicMap C with the same properties as self and
composes its displacement fields with phi's corresponding fields.
The resulting diffeomorphism is of the form C(x) = phi(self(x)) with
inverse C^{-1}(y) = self^{-1}(phi^{-1}(y)). We assume that phi is an
endomorphism with the same discretization and domain affine as self
to ensure that the composition inherits self's properties (we also
assume that the pre-aligning matrix of phi is None or identity).
Parameters
----------
phi : DiffeomorphicMap object
the endomorphism to be warped by this diffeomorphic map
Returns
-------
composition : the composition of this diffeomorphic map with the
endomorphism given as input