Repository navigation
Expand file tree
/
Copy pathtransform.py
More file actions
1626 lines (1386 loc) · 51.3 KB
/
Copy pathtransform.py
File metadata and controls
1626 lines (1386 loc) · 51.3 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
#!/usr/bin/env python
"""handling mpicbg transforms in python
Currently only implemented to facilitate Affine and Polynomial2D
used in Khaled Khairy's EM aligner workflow
"""
import json
import logging
from collections import Iterable
import numpy as np
from .errors import ConversionError, EstimationError, RenderError
from .utils import NullHandler
logger = logging.getLogger(__name__)
logger.addHandler(NullHandler())
try:
from scipy.linalg import svd, LinAlgError
except ImportError as e:
logger.info(e)
logger.info('scipy-based linalg may or may not lead '
'to better parameter fitting')
from numpy.linalg import svd
from numpy.linalg.linalg import LinAlgError
class TransformList:
"""A list of Transforms
Attributes
----------
tforms : :obj:`list` of :class:`Transform`
transforms to apply
transformId : str, optional
uniqueId for this TransformList
"""
def __init__(self, tforms=None, transformId=None, json=None):
"""Initialize TransformList
Parameters
----------
tforms : :obj:`list` of :class:`Transform`
transforms to apply
transformId : str, optional
uniqueId for this TransformList
json : dict, optional
json compatible dictionary to create
:class:`TransformList` via :method:`from_dict`
(will supersede tforms and transformId if not None)
"""
if json is not None:
self.from_dict(json)
else:
if tforms is None:
self.tforms = []
else:
if not isinstance(tforms, list):
raise RenderError(
'unexpected type {} for transforms!'.format(
type(tforms)))
self.tforms = tforms
self.transformId = transformId
def to_dict(self,prefer_affine=True):
"""serialization function
Parameters
----------
prefer_affine: bool
prefer to represent all linear transform as affine's (True)
Returns
-------
dict
json & render compatible representation of this TransformList
"""
d = {}
d['type'] = 'list'
d['specList'] = [tform.to_dict(prefer_affine=True) for tform in self.tforms]
if self.transformId is not None:
d['id'] = self.transformId
return d
def to_json(self):
"""serialization function
Returns
-------
str
string representation of the json & render
representation of this TransformList
"""
return json.dumps(self.to_dict())
def tform(self,pts):
for tf in self.tforms:
pts = tf.tform(pts)
return pts
def from_dict(self, d):
"""deserialization function
Parameters
----------
d : dict
json compatible dictionary representation of this TransformList
"""
self.tforms = []
if d is not None:
self.transformId = d.get('id')
for td in d['specList']:
self.tforms.append(load_transform_json(td))
return self.tforms
def load_transform_json(d, default_type='leaf'):
"""function to get the proper deserialization function
Parameters
----------
d : dict
json compatible representation of Transform
default_type : str
what kind of transform should we assume this
if it is not specified in 'type' ('leaf','list','ref','interpolated')
Returns
-------
renderapi.transform.Transform
deserialized transformation using the most appropriate class
Raises
------
RenderError
if d['type'] isn't one of ('leaf','list','ref','interpolated')
"""
handle_load_tform = {'leaf': load_leaf_json,
'list': lambda x: TransformList(json=x),
'ref': lambda x: ReferenceTransform(json=x),
'interpolated':
lambda x: InterpolatedTransform(json=x)}
try:
return handle_load_tform[d.get('type', default_type)](d)
except KeyError as e:
raise RenderError('Unknown Transform Type {}'.format(e))
def load_leaf_json(d):
"""function to get the proper deserialization function for leaf transforms
Parameters
----------
d : dict
json compatible representation of leaf transform to deserialize
Returns
-------
renderapi.transform.Transform
deserialized transformation
Raises
------
RenderError
if d['type'] != leaf or is omitted
"""
handle_load_leaf = {
AffineModel.className: lambda x: AffineModel(json=x),
Polynomial2DTransform.className:
lambda x: Polynomial2DTransform(json=x),
TranslationModel.className: lambda x: TranslationModel(json=x),
RigidModel.className: lambda x: RigidModel(json=x),
SimilarityModel.className: lambda x: SimilarityModel(json=x),
NonLinearTransform.className: lambda x: NonLinearTransform(json=x),
LensCorrection.className: lambda x: LensCorrection(json=x),
NonLinearCoordinateTransform.className:
lambda x: NonLinearCoordinateTransform(json=x)}
tform_type = d.get('type', 'leaf')
if tform_type != 'leaf':
raise RenderError(
'Unexpected or unknown Transform Type {}'.format(tform_type))
tform_class = d['className']
try:
return handle_load_leaf[tform_class](d)
except KeyError as e:
logger.info('Leaf transform class {} not defined in '
'transform module, using generic'.format(e))
return Transform(json=d)
class InterpolatedTransform:
"""Transform spec defined by linear interpolation of
two other transform specs
Attributes
----------
a : :class:`Transform` or :class:`TransformList` or :class:`InterpolatedTransform`
transform at minimum weight
b : :class:`Transform` or :class:`TransformList` or :class:`InterpolatedTransform`
transform at maximum weight
lambda_ : float
value in interval [0.,1.] which defines evaluation of the
linear interpolation between a (at 0) and b (at 1)
"""
def __init__(self, a=None, b=None, lambda_=None, json=None):
"""Initialize InterpolatedTransform
Parameters
----------
a : :class:`Transform` or :class:`TransformList`
or :class:`InterpolatedTransform`
transform at minimum weight
b : :class:`Transform` or :class:`TransformList`
or :class:`InterpolatedTransform`
transform at maximum weight
lambda_ : float
value in interval [0.,1.] which defines evaluation of the
linear interpolation between a (at 0) and b (at 1)
json : dict
json compatible representation of this transform to
initialize via :method:`self.from_dict`
(will supersede a, b, and lambda_ if not None)
"""
if json is not None:
self.from_dict(json)
else:
self.a = a
self.b = b
self.lambda_ = lambda_
def to_dict(self,**kwargs):
"""serialization routine
Returns
-------
dict
json compatible representation
"""
return dict(self)
def from_dict(self, d):
"""deserialization routine
Parameters
----------
d : dict
json compatible representation
"""
self.a = load_transform_json(d['a'])
self.b = load_transform_json(d['b'])
self.lambda_ = d['lambda']
def __iter__(self):
return iter([('type', 'interpolated'),
('a', self.a.to_dict()),
('b', self.b.to_dict()),
('lambda', self.lambda_)])
class ReferenceTransform:
"""Transform which is simply a reference to a transform stored elsewhere
Attributes
----------
refId : str
transformId of the referenced transform
"""
def __init__(self, refId=None, json=None):
"""Initialize ReferenceTransform
Parameters
----------
refId : str
transformId of the referenced transform
json : dict
json compatible representation of this transform
(will supersede refId if not None)
"""
if json is not None:
self.from_dict(json)
else:
self.refId = refId
def to_dict(self,**kwargs):
"""serialization routine
Returns
-------
dict
json compatible representation of this transform
"""
d = {}
d['type'] = 'ref'
d['refId'] = self.refId
return d
def from_dict(self, d):
"""deserialization routine
Parameters
----------
d : dict
json compatible representation of this transform
"""
self.refId = d['refId']
def __str__(self):
return 'ReferenceTransform(%s)' % self.refId
def __repr__(self):
return self.__str__()
def __iter__(self):
return iter([('type', 'ref'), ('refId', self.refId)])
class Transform(object):
"""Base transformation class
Attributes
----------
className : str
mpicbg java classname of this transform
dataString : str
string reprsentation of this transform as speced by
mpicbg java class library
transformId : str, optional
unique Id for this transform (optional)
"""
def __init__(self, className=None, dataString=None,
transformId=None, labels=None, json=None):
"""Initialize Transform
Parameters
----------
className : str
mpicbg java classname of this transform
dataString : str
string reprsentation of this transform as speced
by mpicbg java class library
transformId : str, optional
unique Id for this transform (optional)
labels : list of str
list of labels to give this transform
json : dict
json compatible representation of this transform
(supersedes className, dataString, and transformId if not None)
"""
if json is not None:
self.from_dict(json)
else:
self.className = className
self.dataString = dataString
self.transformId = transformId
self.labels = labels
def to_dict(self,**kwargs):
"""serialization routine
Returns
-------
dict
json compatible representation of this transform
"""
d = {}
d['type'] = 'leaf'
d['className'] = self.className
d['dataString'] = self.dataString
if self.transformId is not None:
d['id'] = self.transformId
if self.labels is not None:
d['metaData'] = {'labels': self.labels}
return d
def from_dict(self, d):
"""deserialization routine
Parameters
----------
d : dict
json compatible representation of this transform
"""
self.className = d['className']
self.transformId = d.get('id', None)
self._process_dataString(d['dataString'])
md = d.get('metaData', None)
if md is not None:
self.labels = md.get('labels', None)
else:
self.labels = None
def _process_dataString(self, datastring):
"""method meant to set state of transform from datastring
generic implementation only saves datastring at self.dataString.
should rewrite for all transform classes that want to
implement tform,fit,etc
Parameters
----------
dataString : str
string which can be used to initialize mpicbg transforms in java
"""
self.dataString = datastring
def __str__(self):
return 'className:%s\ndataString:%s' % (
self.className, self.dataString)
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return self.__str__() == other.__str__()
def __hash__(self):
return hash((self.__str__()))
class AffineModel(Transform):
"""Linear 2d Transformation
mpicbg classname: mpicbg.trakem2.transform.AffineModel2D
implements this simple math
x'=M00*x + M01*x + B0
y'=M10*x + M11*y + B1
Attributes
----------
M00 : float
x'+=M00*x
M01 : float
x'+=M01*y
M10 : float
y'+=M10*x
M11 : float
y'+=M11*y
B0 : float
x'+=B0
B1 : float
y'+=B1
transformId : str, optional
unique transformId for this transform
labels : list of str
list of labels to give this transform
M : numpy.array
3x3 numpy array representing 2d Affine with homogeneous coordinates
populates with values from M00, M01, M10, M11, B0, B1 with load_M()
"""
className = 'mpicbg.trakem2.transform.AffineModel2D'
def __init__(self, M00=1.0, M01=0.0, M10=0.0, M11=1.0, B0=0.0, B1=0.0,
transformId=None, labels=None, json=None):
"""Initialize AffineModel, defaulting to identity
Parameters
----------
M00 : float
x'+=M00*x
M01 : float
x'+=M01*y
M10 : float
y'+=M10*x
M11 : float
y'+=M11*y
B0 : float
x'+=B0
B1 : float
y'+=B1
transformId : str
unique transformId for this transform (optional)
labels : list of str
list of labels to give this transform
json : dict
json compatible representation of this transform
(will supersede all other parameters if not None)
"""
if json is not None:
self.from_dict(json)
else:
self.M00 = M00
self.M01 = M01
self.M10 = M10
self.M11 = M11
self.B0 = B0
self.B1 = B1
self.labels = labels
self.load_M()
self.transformId = transformId
self.className = 'mpicbg.trakem2.transform.AffineModel2D'
@property
def dataString(self):
"""dataString string for this transform"""
return "%.10f %.10f %.10f %.10f %.10f %.10f" % (
self.M[0, 0], self.M[1, 0], self.M[0, 1],
self.M[1, 1], self.M[0, 2], self.M[1, 2])
def _process_dataString(self, datastring):
"""generate datastring and param attributes from datastring"""
dsList = datastring.split()
self.M00 = float(dsList[0])
self.M10 = float(dsList[1])
self.M01 = float(dsList[2])
self.M11 = float(dsList[3])
self.B0 = float(dsList[4])
self.B1 = float(dsList[5])
self.load_M()
def load_M(self):
"""method to take the attribute of self and fill in self.M"""
self.M = np.identity(3, np.double)
self.M[0, 0] = self.M00
self.M[0, 1] = self.M01
self.M[1, 0] = self.M10
self.M[1, 1] = self.M11
self.M[0, 2] = self.B0
self.M[1, 2] = self.B1
@staticmethod
def fit(A, B):
"""function to fit this transform given the corresponding sets of points A & B
Parameters
----------
A : numpy.array
a Nx2 matrix of source points
B : numpy.array
a Nx2 matrix of destination points
Returns
-------
numpy.array
a 6x1 matrix with the best fit parameters
ordered M00,M01,M10,M11,B0,B1
"""
if not all([A.shape[0] == B.shape[0], A.shape[1] == B.shape[1] == 2]):
raise EstimationError(
'shape mismatch! A shape: {}, B shape {}'.format(
A.shape, B.shape))
N = A.shape[0] # total points
M = np.zeros((2 * N, 6))
Y = np.zeros((2 * N, 1))
for i in range(N):
M[2 * i, :] = [A[i, 0], A[i, 1], 0, 0, 1, 0]
M[2 * i + 1, :] = [0, 0, A[i, 0], A[i, 1], 0, 1]
Y[2 * i] = B[i, 0]
Y[2 * i + 1] = B[i, 1]
(Tvec, residuals, rank, s) = np.linalg.lstsq(M, Y)
return Tvec
def estimate(self, A, B, return_params=True, **kwargs):
"""method for setting this transformation with the best fit
given the corresponding points A,B
Parameters
----------
A : numpy.array
a Nx2 matrix of source points
B : numpy.array
a Nx2 matrix of destination points
return_params : boolean
whether to return the parameter matrix
**kwargs
keyword arguments to pass to self.fit
Returns
-------
numpy.array
a 2x3 matrix of parameters for this matrix,
laid out (x,y) x (x,y,offset)
(or None if return_params=False)
"""
Tvec = self.fit(A, B, **kwargs)
self.M00 = Tvec[0, 0]
self.M10 = Tvec[2, 0]
self.M01 = Tvec[1, 0]
self.M11 = Tvec[3, 0]
self.B0 = Tvec[4, 0]
self.B1 = Tvec[5, 0]
self.load_M()
if return_params:
return self.M
def concatenate(self, model):
"""concatenate a model to this model -- ported from trakEM2 below:
::
final double a00 = m00 * model.m00 + m01 * model.m10;
final double a01 = m00 * model.m01 + m01 * model.m11;
final double a02 = m00 * model.m02 + m01 * model.m12 + m02;
final double a10 = m10 * model.m00 + m11 * model.m10;
final double a11 = m10 * model.m01 + m11 * model.m11;
final double a12 = m10 * model.m02 + m11 * model.m12 + m12;
Parameters
----------
model : AffineModel
model to concatenate to this one
Returns
-------
AffineModel
model after concatenating model with this model
"""
a00 = self.M[0, 0] * model.M[0, 0] + self.M[0, 1] * model.M[1, 0]
a01 = self.M[0, 0] * model.M[0, 1] + self.M[0, 1] * model.M[1, 1]
a02 = (self.M[0, 0] * model.M[0, 2] + self.M[0, 1] * model.M[1, 2] +
self.M[0, 2])
a10 = self.M[1, 0] * model.M[0, 0] + self.M[1, 1] * model.M[1, 0]
a11 = self.M[1, 0] * model.M[0, 1] + self.M[1, 1] * model.M[1, 1]
a12 = (self.M[1, 0] * model.M[0, 2] + self.M[1, 1] * model.M[1, 2] +
self.M[1, 2])
newmodel = AffineModel(a00, a01, a10, a11, a02, a12)
return newmodel
def invert(self):
"""return an inverted version of this transformation
Returns
-------
AffineModel
an inverted version of this transformation
"""
inv_M = np.linalg.inv(self.M)
Ai = AffineModel(inv_M[0, 0], inv_M[0, 1], inv_M[1, 0],
inv_M[1, 1], inv_M[0, 2], inv_M[1, 2])
return Ai
@staticmethod
def convert_to_point_vector(points):
"""method to help reshape x,y points to x,y,1 vectors
Parameters
----------
points : numpy.array
a Nx2 array of x,y points
Returns
-------
numpy.array
a Nx3 array of x,y,1 points used for transformations
"""
Np = points.shape[0]
onevec = np.ones((Np, 1), np.double)
if points.shape[1] != 2:
raise ConversionError('Points must be of shape (:, 2) '
'-- got {}'.format(points.shape))
Nd = 2
points = np.concatenate((points, onevec), axis=1)
return points, Nd
@staticmethod
def convert_points_vector_to_array(points, Nd=2):
"""method for convertion x,y,K points to x,y vectors
Parameters
----------
points : numpy.array
a Nx3 vector of points after transformation
Nd : int
the number of dimensions to cutoff (should be 2)
Returns
-------
numpy.array: a Nx2 array of x,y points
"""
points = points[:, 0:Nd] / np.tile(points[:, 2], (Nd, 1)).T
return points
def tform(self, points):
"""transform a set of points through this transformation
Parameters
----------
points : numpy.array
a Nx2 array of x,y points
Returns
-------
numpy.array
a Nx2 array of x,y points after transformation
"""
points, Nd = self.convert_to_point_vector(points)
pt = np.dot(self.M, points.T).T
return self.convert_points_vector_to_array(pt, Nd)
def inverse_tform(self, points):
"""transform a set of points through the inverse of this transformation
Parameters
----------
points : numpy.array
a Nx2 array of x,y points
Returns
-------
numpy.array
a Nx2 array of x,y points after inverse transformation
"""
points, Nd = self.convert_to_point_vector(points)
pt = np.dot(np.linalg.inv(self.M), points.T).T
return self.convert_points_vector_to_array(pt, Nd)
@property
def scale(self):
"""tuple of scale for x, y"""
return tuple([np.sqrt(sum([i ** 2 for i in self.M[:, j]]))
for j in range(self.M.shape[1])])[:2]
@property
def shear(self):
"""counter-clockwise shear angle"""
return np.arctan2(-self.M[0, 1], self.M[1, 1]) - self.rotation
@property
def translation(self):
"""tuple of translation in x, y"""
return tuple(self.M[:2, 2])
@property
def rotation(self):
"""counter-clockwise rotation"""
return np.arctan2(self.M[1, 0], self.M[0, 0])
def __str__(self):
return "M=[[%f,%f],[%f,%f]] B=[%f,%f]" % (
self.M[0, 0], self.M[0, 1], self.M[1, 0],
self.M[1, 1], self.M[0, 2], self.M[1, 2])
class TranslationModel(AffineModel):
"""Translation fitting and estimation as an :class:`AffineModel`
Linear 2d Transformation
mpicbg classname: mpicbg.trakem2.transform.AffineModel2D
implements this simple math
x'=M00*x + M01*x + B0
y'=M10*x + M11*y + B1
Attributes
----------
M00 : float
x'+=M00*x
M01 : float
x'+=M01*y
M10 : float
y'+=M10*x
M11 : float
y'+=M11*y
B0 : float
x'+=B0
B1 : float
y'+=B1
transformId : str, optional
unique transformId for this transform
labels : list of str
list of labels to give this transform
M : numpy.array
3x3 numpy array representing 2d Affine with homogeneous coordinates
populates with values from M00, M01, M10, M11, B0, B1 with load_M()
"""
className = 'mpicbg.trakem2.transform.TranslationModel2D'
def __init__(self, *args, **kwargs):
super(TranslationModel, self).__init__(*args, **kwargs)
self.className = 'mpicbg.trakem2.transform.TranslationModel2D'
@property
def dataString(self):
"""dataString string for this transform"""
return "%.10f %.10f" % (self.B0, self.B1)
def _process_dataString(self, dataString):
"""expected dataString is 'tx ty'"""
tx, ty = map(float,dataString.split(' '))
self.B0 = tx
self.B1 = ty
self.M00 = 1.0
self.M11 = 1.0
self.M01 = 0.0
self.M10 = 0.0
self.load_M()
@staticmethod
def fit(src, dst):
"""function to fit Translation transform given
the corresponding sets of points src & dst
Parameters
----------
src : numpy.array
a Nx2 matrix of source points
dst : numpy.array
a Nx2 matrix of destination points
Returns
-------
numpy.array
a 6x1 matrix with the best fit parameters
ordered M00,M01,M10,M11,B0,B1
"""
t = dst.mean(axis=0) - src.mean(axis=0)
T = np.eye(3)
T[:2, 2] = t
return T
def estimate(self, src, dst, return_params=True):
"""method for setting this transformation with the best fit
given the corresponding points src,dst
Parameters
----------
src : numpy.array
a Nx2 matrix of source points
dst : numpy.array
a Nx2 matrix of destination points
return_params : bool
whether to return the parameter matrix
Returns
-------
numpy.array
a 2x3 matrix of parameters for this matrix,
laid out (x,y) x (x,y,offset)
(or None if return_params=False)
"""
self.M = self.fit(src, dst)
if return_params:
return self.M
class RigidModel(AffineModel):
"""model for fitting Rigid only transformations
(rotation+translation)
or
(determinate=1, orthonormal eigenvectors)
implemented as an :class:`AffineModel`
Attributes
----------
M00 : float
x'+=M00*x
M01 : float
x'+=M01*y
M10 : float
y'+=M10*x
M11 : float
y'+=M11*y
B0 : float
x'+=B0
B1 : float
y'+=B1
transformId : str, optional
unique transformId for this transform
labels : list of str
list of labels to give this transform
M : numpy.array
3x3 numpy array representing 2d Affine with homogeneous coordinates
populates with values from M00, M01, M10, M11, B0, B1 with load_M()
"""
className = 'mpicbg.trakem2.transform.RigidModel2D'
def __init__(self, *args, **kwargs):
super(RigidModel, self).__init__(*args, **kwargs)
self.className = 'mpicbg.trakem2.transform.RigidModel2D'
@property
def dataString(self):
return "%0.10f %0.10f %0.10f"%(np.arctan2(self.M10,self.M00), self.B0,self.B1)
def _process_dataString(self, dataString):
"""expected datastring is 'theta tx ty'"""
theta, tx, ty = map(float,dataString.split(' '))
self.M00 = np.cos(theta)
self.M01 = -np.sin(theta)
self.M10 = np.sin(theta)
self.M11 = np.cos(theta)
self.B0 = tx
self.B1 = ty
self.load_M()
@staticmethod
def fit(src, dst, rigid=True, **kwargs):
"""function to fit this transform given the corresponding
sets of points src & dst
Umeyama estimation of similarity transformation
Parameters
----------
src : numpy.array
a Nx2 matrix of source points
dst : numpy.array
a Nx2 matrix of destination points
rigid : bool
whether to constrain this transform to be rigid
Returns
-------
numpy.array
a 6x1 matrix with the best fit parameters
ordered M00,M01,M10,M11,B0,B1
"""
# TODO shape assertion
num, dim = src.shape
src_cld = src - src.mean(axis=0)
dst_cld = dst - dst.mean(axis=0)
A = np.dot(dst_cld.T, src_cld) / num
d = np.ones((dim, ), dtype=np.double)
if np.linalg.det(A) < 0:
d[dim - 1] = -1
T = np.eye(dim + 1, dtype=np.double)
rank = np.linalg.matrix_rank(A)
if rank == 0:
raise EstimationError('zero rank matrix A unacceptable -- '
'likely poorly conditioned')
U, S, V = svd(A)
if rank == dim - 1:
if np.linalg.det(U) * np.linalg.det(V) > 0:
T[:dim, :dim] = np.dot(U, V)
else:
s = d[dim - 1]
d[dim - 1] = -1
T[:dim, :dim] = np.dot(U, np.dot(np.diag(d), V))
d[dim - 1] = s
else:
T[:dim, :dim] = np.dot(U, np.dot(np.diag(d), V.T))
fit_scale = (1.0 if rigid else
1.0 / src_cld.var(axis=0).sum() * np.dot(S, d))
T[:dim, dim] = dst.mean(axis=0) - fit_scale * np.dot(
T[:dim, :dim], src.mean(axis=0).T)
T[:dim, :dim] *= fit_scale
return T
def estimate(self, A, B, return_params=True, **kwargs):
"""method for setting this transformation with the
best fit given the corresponding points src,dst
Parameters
----------
A : numpy.array
a Nx2 matrix of source points
B : numpy.array
a Nx2 matrix of destination points
return_params : bool
whether to return the parameter matrix
Returns
-------
numpy.array
a 2x3 matrix of parameters for this matrix,
laid out (x,y) x (x,y,offset)
(or None if return_params=False)
"""
self.M = self.fit(A, B, **kwargs)
if return_params:
return self.M
class SimilarityModel(RigidModel):
"""class for fitting Similarity transformations
(translation+rotation+scaling)
or
(orthogonal eigen vectors with equal eigenvalues)
implemented as an :class:`AffineModel`
Attributes
----------
M00 : float
x'+=M00*x
M01 : float
x'+=M01*y
M10 : float
y'+=M10*x
M11 : float
y'+=M11*y
B0 : float
x'+=B0
B1 : float