-
Notifications
You must be signed in to change notification settings - Fork 152
/
similaritytransform.py
1370 lines (1055 loc) · 40.9 KB
/
similaritytransform.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
# From scikit-image
import math
import numpy as np
import sys
import textwrap
def get_bound_method_class(m):
"""Return the class for a bound method.
"""
return m.im_class if sys.version < '3' else m.__self__.__class__
def safe_as_int(val, atol=1e-3):
"""
Attempt to safely cast values to integer format.
Parameters
----------
val : scalar or iterable of scalars
Number or container of numbers which are intended to be interpreted as
integers, e.g., for indexing purposes, but which may not carry integer
type.
atol : float
Absolute tolerance away from nearest integer to consider values in
``val`` functionally integers.
Returns
-------
val_int : NumPy scalar or ndarray of dtype `np.int64`
Returns the input value(s) coerced to dtype `np.int64` assuming all
were within ``atol`` of the nearest integer.
Notes
-----
This operation calculates ``val`` modulo 1, which returns the mantissa of
all values. Then all mantissas greater than 0.5 are subtracted from one.
Finally, the absolute tolerance from zero is calculated. If it is less
than ``atol`` for all value(s) in ``val``, they are rounded and returned
in an integer array. Or, if ``val`` was a scalar, a NumPy scalar type is
returned.
If any value(s) are outside the specified tolerance, an informative error
is raised.
Examples
--------
>>> safe_as_int(7.0)
7
>>> safe_as_int([9, 4, 2.9999999999])
array([9, 4, 3])
>>> safe_as_int(53.1)
Traceback (most recent call last):
...
ValueError: Integer argument required but received 53.1, check inputs.
>>> safe_as_int(53.01, atol=0.01)
53
"""
mod = np.asarray(val) % 1 # Extract mantissa
# Check for and subtract any mod values > 0.5 from 1
if mod.ndim == 0: # Scalar input, cannot be indexed
if mod > 0.5:
mod = 1 - mod
else: # Iterable input, now ndarray
mod[mod > 0.5] = 1 - mod[mod > 0.5] # Test on each side of nearest int
try:
np.testing.assert_allclose(mod, 0, atol=atol)
except AssertionError:
raise ValueError("Integer argument required but received "
"{0}, check inputs.".format(val))
return np.round(val).astype(np.int64)
def _to_ndimage_mode(mode):
"""Convert from `numpy.pad` mode name to the corresponding ndimage mode."""
mode_translation_dict = dict(edge='nearest', symmetric='reflect',
reflect='mirror')
if mode in mode_translation_dict:
mode = mode_translation_dict[mode]
return mode
def _center_and_normalize_points(points):
"""Center and normalize image points.
The points are transformed in a two-step procedure that is expressed
as a transformation matrix. The matrix of the resulting points is usually
better conditioned than the matrix of the original points.
Center the image points, such that the new coordinate system has its
origin at the centroid of the image points.
Normalize the image points, such that the mean distance from the points
to the origin of the coordinate system is sqrt(2).
Parameters
----------
points : (N, 2) array
The coordinates of the image points.
Returns
-------
matrix : (3, 3) array
The transformation matrix to obtain the new points.
new_points : (N, 2) array
The transformed image points.
References
----------
.. [1] Hartley, Richard I. "In defense of the eight-point algorithm."
Pattern Analysis and Machine Intelligence, IEEE Transactions on 19.6
(1997): 580-593.
"""
centroid = np.mean(points, axis=0)
rms = math.sqrt(np.sum((points - centroid) ** 2) / points.shape[0])
norm_factor = math.sqrt(2) / rms
matrix = np.array([[norm_factor, 0, -norm_factor * centroid[0]],
[0, norm_factor, -norm_factor * centroid[1]],
[0, 0, 1]])
pointsh = np.row_stack([points.T, np.ones((points.shape[0]),)])
new_pointsh = (matrix @ pointsh).T
new_points = new_pointsh[:, :2]
new_points[:, 0] /= new_pointsh[:, 2]
new_points[:, 1] /= new_pointsh[:, 2]
return matrix, new_points
def _umeyama(src, dst, estimate_scale):
"""Estimate N-D similarity transformation with or without scaling.
Parameters
----------
src : (M, N) array
Source coordinates.
dst : (M, N) array
Destination coordinates.
estimate_scale : bool
Whether to estimate scaling factor.
Returns
-------
T : (N + 1, N + 1)
The homogeneous similarity transformation matrix. The matrix contains
NaN values only if the problem is not well-conditioned.
References
----------
.. [1] "Least-squares estimation of transformation parameters between two
point patterns", Shinji Umeyama, PAMI 1991, :DOI:`10.1109/34.88573`
"""
num = src.shape[0]
dim = src.shape[1]
# Compute mean of src and dst.
src_mean = src.mean(axis=0)
dst_mean = dst.mean(axis=0)
# Subtract mean from src and dst.
src_demean = src - src_mean
dst_demean = dst - dst_mean
# Eq. (38).
A = dst_demean.T @ src_demean / num
# Eq. (39).
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)
U, S, V = np.linalg.svd(A)
# Eq. (40) and (43).
rank = np.linalg.matrix_rank(A)
if rank == 0:
return np.nan * T
elif rank == dim - 1:
if np.linalg.det(U) * np.linalg.det(V) > 0:
T[:dim, :dim] = U @ V
else:
s = d[dim - 1]
d[dim - 1] = -1
T[:dim, :dim] = U @ np.diag(d) @ V
d[dim - 1] = s
else:
T[:dim, :dim] = U @ np.diag(d) @ V
if estimate_scale:
# Eq. (41) and (42).
scale = 1.0 / src_demean.var(axis=0).sum() * (S @ d)
else:
scale = 1.0
T[:dim, dim] = dst_mean - scale * (T[:dim, :dim] @ src_mean.T)
T[:dim, :dim] *= scale
return T
class GeometricTransform(object):
"""Base class for geometric transformations.
"""
def __call__(self, coords):
"""Apply forward transformation.
Parameters
----------
coords : (N, 2) array
Source coordinates.
Returns
-------
coords : (N, 2) array
Destination coordinates.
"""
raise NotImplementedError()
def inverse(self, coords):
"""Apply inverse transformation.
Parameters
----------
coords : (N, 2) array
Destination coordinates.
Returns
-------
coords : (N, 2) array
Source coordinates.
"""
raise NotImplementedError()
def residuals(self, src, dst):
"""Determine residuals of transformed destination coordinates.
For each transformed source coordinate the euclidean distance to the
respective destination coordinate is determined.
Parameters
----------
src : (N, 2) array
Source coordinates.
dst : (N, 2) array
Destination coordinates.
Returns
-------
residuals : (N, ) array
Residual for coordinate.
"""
return np.sqrt(np.sum((self(src) - dst)**2, axis=1))
def __add__(self, other):
"""Combine this transformation with another.
"""
raise NotImplementedError()
class FundamentalMatrixTransform(GeometricTransform):
"""Fundamental matrix transformation.
The fundamental matrix relates corresponding points between a pair of
uncalibrated images. The matrix transforms homogeneous image points in one
image to epipolar lines in the other image.
The fundamental matrix is only defined for a pair of moving images. In the
case of pure rotation or planar scenes, the homography describes the
geometric relation between two images (`ProjectiveTransform`). If the
intrinsic calibration of the images is known, the essential matrix describes
the metric relation between the two images (`EssentialMatrixTransform`).
References
----------
.. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in
computer vision. Cambridge university press, 2003.
Parameters
----------
matrix : (3, 3) array, optional
Fundamental matrix.
Attributes
----------
params : (3, 3) array
Fundamental matrix.
"""
def __init__(self, matrix=None):
if matrix is None:
# default to an identity transform
matrix = np.eye(3)
if matrix.shape != (3, 3):
raise ValueError("Invalid shape of transformation matrix")
self.params = matrix
def __call__(self, coords):
"""Apply forward transformation.
Parameters
----------
coords : (N, 2) array
Source coordinates.
Returns
-------
coords : (N, 3) array
Epipolar lines in the destination image.
"""
coords_homogeneous = np.column_stack([coords, np.ones(coords.shape[0])])
return coords_homogeneous @ self.params.T
def inverse(self, coords):
"""Apply inverse transformation.
Parameters
----------
coords : (N, 2) array
Destination coordinates.
Returns
-------
coords : (N, 3) array
Epipolar lines in the source image.
"""
coords_homogeneous = np.column_stack([coords, np.ones(coords.shape[0])])
return coords_homogeneous @ self.params
def _setup_constraint_matrix(self, src, dst):
"""Setup and solve the homogeneous epipolar constraint matrix::
dst' * F * src = 0.
Parameters
----------
src : (N, 2) array
Source coordinates.
dst : (N, 2) array
Destination coordinates.
Returns
-------
F_normalized : (3, 3) array
The normalized solution to the homogeneous system. If the system
is not well-conditioned, this matrix contains NaNs.
src_matrix : (3, 3) array
The transformation matrix to obtain the normalized source
coordinates.
dst_matrix : (3, 3) array
The transformation matrix to obtain the normalized destination
coordinates.
"""
if src.shape != dst.shape:
raise ValueError('src and dst shapes must be identical.')
if src.shape[0] < 8:
raise ValueError('src.shape[0] must be equal or larger than 8.')
# Center and normalize image points for better numerical stability.
try:
src_matrix, src = _center_and_normalize_points(src)
dst_matrix, dst = _center_and_normalize_points(dst)
except ZeroDivisionError:
self.params = np.full((3, 3), np.nan)
return 3 * [np.full((3, 3), np.nan)]
# Setup homogeneous linear equation as dst' * F * src = 0.
A = np.ones((src.shape[0], 9))
A[:, :2] = src
A[:, :3] *= dst[:, 0, np.newaxis]
A[:, 3:5] = src
A[:, 3:6] *= dst[:, 1, np.newaxis]
A[:, 6:8] = src
# Solve for the nullspace of the constraint matrix.
_, _, V = np.linalg.svd(A)
F_normalized = V[-1, :].reshape(3, 3)
return F_normalized, src_matrix, dst_matrix
def estimate(self, src, dst):
"""Estimate fundamental matrix using 8-point algorithm.
The 8-point algorithm requires at least 8 corresponding point pairs for
a well-conditioned solution, otherwise the over-determined solution is
estimated.
Parameters
----------
src : (N, 2) array
Source coordinates.
dst : (N, 2) array
Destination coordinates.
Returns
-------
success : bool
True, if model estimation succeeds.
"""
F_normalized, src_matrix, dst_matrix = \
self._setup_constraint_matrix(src, dst)
# Enforcing the internal constraint that two singular values must be
# non-zero and one must be zero.
U, S, V = np.linalg.svd(F_normalized)
S[2] = 0
F = U @ np.diag(S) @ V
self.params = dst_matrix.T @ F @ src_matrix
return True
def residuals(self, src, dst):
"""Compute the Sampson distance.
The Sampson distance is the first approximation to the geometric error.
Parameters
----------
src : (N, 2) array
Source coordinates.
dst : (N, 2) array
Destination coordinates.
Returns
-------
residuals : (N, ) array
Sampson distance.
"""
src_homogeneous = np.column_stack([src, np.ones(src.shape[0])])
dst_homogeneous = np.column_stack([dst, np.ones(dst.shape[0])])
F_src = self.params @ src_homogeneous.T
Ft_dst = self.params.T @ dst_homogeneous.T
dst_F_src = np.sum(dst_homogeneous * F_src.T, axis=1)
return np.abs(dst_F_src) / np.sqrt(F_src[0] ** 2 + F_src[1] ** 2
+ Ft_dst[0] ** 2 + Ft_dst[1] ** 2)
class EssentialMatrixTransform(FundamentalMatrixTransform):
"""Essential matrix transformation.
The essential matrix relates corresponding points between a pair of
calibrated images. The matrix transforms normalized, homogeneous image
points in one image to epipolar lines in the other image.
The essential matrix is only defined for a pair of moving images capturing a
non-planar scene. In the case of pure rotation or planar scenes, the
homography describes the geometric relation between two images
(`ProjectiveTransform`). If the intrinsic calibration of the images is
unknown, the fundamental matrix describes the projective relation between
the two images (`FundamentalMatrixTransform`).
References
----------
.. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in
computer vision. Cambridge university press, 2003.
Parameters
----------
rotation : (3, 3) array, optional
Rotation matrix of the relative camera motion.
translation : (3, 1) array, optional
Translation vector of the relative camera motion. The vector must
have unit length.
matrix : (3, 3) array, optional
Essential matrix.
Attributes
----------
params : (3, 3) array
Essential matrix.
"""
def __init__(self, rotation=None, translation=None, matrix=None):
if rotation is not None:
if translation is None:
raise ValueError("Both rotation and translation required")
if rotation.shape != (3, 3):
raise ValueError("Invalid shape of rotation matrix")
if abs(np.linalg.det(rotation) - 1) > 1e-6:
raise ValueError("Rotation matrix must have unit determinant")
if translation.size != 3:
raise ValueError("Invalid shape of translation vector")
if abs(np.linalg.norm(translation) - 1) > 1e-6:
raise ValueError("Translation vector must have unit length")
# Matrix representation of the cross product for t.
t_x = np.array([0, -translation[2], translation[1],
translation[2], 0, -translation[0],
-translation[1], translation[0], 0]).reshape(3, 3)
self.params = t_x @ rotation
elif matrix is not None:
if matrix.shape != (3, 3):
raise ValueError("Invalid shape of transformation matrix")
self.params = matrix
else:
# default to an identity transform
self.params = np.eye(3)
def estimate(self, src, dst):
"""Estimate essential matrix using 8-point algorithm.
The 8-point algorithm requires at least 8 corresponding point pairs for
a well-conditioned solution, otherwise the over-determined solution is
estimated.
Parameters
----------
src : (N, 2) array
Source coordinates.
dst : (N, 2) array
Destination coordinates.
Returns
-------
success : bool
True, if model estimation succeeds.
"""
E_normalized, src_matrix, dst_matrix = \
self._setup_constraint_matrix(src, dst)
# Enforcing the internal constraint that two singular values must be
# equal and one must be zero.
U, S, V = np.linalg.svd(E_normalized)
S[0] = (S[0] + S[1]) / 2.0
S[1] = S[0]
S[2] = 0
E = U @ np.diag(S) @ V
self.params = dst_matrix.T @ E @ src_matrix
return True
class ProjectiveTransform(GeometricTransform):
r"""Projective transformation.
Apply a projective transformation (homography) on coordinates.
For each homogeneous coordinate :math:`\mathbf{x} = [x, y, 1]^T`, its
target position is calculated by multiplying with the given matrix,
:math:`H`, to give :math:`H \mathbf{x}`::
[[a0 a1 a2]
[b0 b1 b2]
[c0 c1 1 ]].
E.g., to rotate by theta degrees clockwise, the matrix should be::
[[cos(theta) -sin(theta) 0]
[sin(theta) cos(theta) 0]
[0 0 1]]
or, to translate x by 10 and y by 20::
[[1 0 10]
[0 1 20]
[0 0 1 ]].
Parameters
----------
matrix : (3, 3) array, optional
Homogeneous transformation matrix.
Attributes
----------
params : (3, 3) array
Homogeneous transformation matrix.
"""
_coeffs = range(8)
def __init__(self, matrix=None):
if matrix is None:
# default to an identity transform
matrix = np.eye(3)
if matrix.shape != (3, 3):
raise ValueError("invalid shape of transformation matrix")
self.params = matrix
@property
def _inv_matrix(self):
return np.linalg.inv(self.params)
def _apply_mat(self, coords, matrix):
coords = np.array(coords, copy=False, ndmin=2)
x, y = np.transpose(coords)
src = np.vstack((x, y, np.ones_like(x)))
dst = src.T @ matrix.T
# below, we will divide by the last dimension of the homogeneous
# coordinate matrix. In order to avoid division by zero,
# we replace exact zeros in this column with a very small number.
dst[dst[:, 2] == 0, 2] = np.finfo(float).eps
# rescale to homogeneous coordinates
dst[:, :2] /= dst[:, 2:3]
return dst[:, :2]
def __call__(self, coords):
"""Apply forward transformation.
Parameters
----------
coords : (N, 2) array
Source coordinates.
Returns
-------
coords : (N, 2) array
Destination coordinates.
"""
return self._apply_mat(coords, self.params)
def inverse(self, coords):
"""Apply inverse transformation.
Parameters
----------
coords : (N, 2) array
Destination coordinates.
Returns
-------
coords : (N, 2) array
Source coordinates.
"""
return self._apply_mat(coords, self._inv_matrix)
def estimate(self, src, dst):
"""Estimate the transformation from a set of corresponding points.
You can determine the over-, well- and under-determined parameters
with the total least-squares method.
Number of source and destination coordinates must match.
The transformation is defined as::
X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)
Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)
These equations can be transformed to the following form::
0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X
0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y
which exist for each set of corresponding points, so we have a set of
N * 2 equations. The coefficients appear linearly so we can write
A x = 0, where::
A = [[x y 1 0 0 0 -x*X -y*X -X]
[0 0 0 x y 1 -x*Y -y*Y -Y]
...
...
]
x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]
In case of total least-squares the solution of this homogeneous system
of equations is the right singular vector of A which corresponds to the
smallest singular value normed by the coefficient c3.
In case of the affine transformation the coefficients c0 and c1 are 0.
Thus the system of equations is::
A = [[x y 1 0 0 0 -X]
[0 0 0 x y 1 -Y]
...
...
]
x.T = [a0 a1 a2 b0 b1 b2 c3]
Parameters
----------
src : (N, 2) array
Source coordinates.
dst : (N, 2) array
Destination coordinates.
Returns
-------
success : bool
True, if model estimation succeeds.
"""
try:
src_matrix, src = _center_and_normalize_points(src)
dst_matrix, dst = _center_and_normalize_points(dst)
except ZeroDivisionError:
self.params = np.nan * np.empty((3, 3))
return False
xs = src[:, 0]
ys = src[:, 1]
xd = dst[:, 0]
yd = dst[:, 1]
rows = src.shape[0]
# params: a0, a1, a2, b0, b1, b2, c0, c1
A = np.zeros((rows * 2, 9))
A[:rows, 0] = xs
A[:rows, 1] = ys
A[:rows, 2] = 1
A[:rows, 6] = - xd * xs
A[:rows, 7] = - xd * ys
A[rows:, 3] = xs
A[rows:, 4] = ys
A[rows:, 5] = 1
A[rows:, 6] = - yd * xs
A[rows:, 7] = - yd * ys
A[:rows, 8] = xd
A[rows:, 8] = yd
# Select relevant columns, depending on params
A = A[:, list(self._coeffs) + [8]]
_, _, V = np.linalg.svd(A)
# if the last element of the vector corresponding to the smallest
# singular value is close to zero, this implies a degenerate case
# because it is a rank-defective transform, which would map points
# to a line rather than a plane.
if np.isclose(V[-1, -1], 0):
return False
H = np.zeros((3, 3))
# solution is right singular vector that corresponds to smallest
# singular value
H.flat[list(self._coeffs) + [8]] = - V[-1, :-1] / V[-1, -1]
H[2, 2] = 1
# De-center and de-normalize
H = np.linalg.inv(dst_matrix) @ H @ src_matrix
self.params = H
return True
def __add__(self, other):
"""Combine this transformation with another.
"""
if isinstance(other, ProjectiveTransform):
# combination of the same types result in a transformation of this
# type again, otherwise use general projective transformation
if type(self) == type(other):
tform = self.__class__
else:
tform = ProjectiveTransform
return tform(other.params @ self.params)
elif (hasattr(other, '__name__')
and other.__name__ == 'inverse'
and hasattr(get_bound_method_class(other), '_inv_matrix')):
return ProjectiveTransform(other.__self__._inv_matrix @ self.params)
else:
raise TypeError("Cannot combine transformations of differing "
"types.")
def __nice__(self):
"""common 'paramstr' used by __str__ and __repr__"""
npstring = np.array2string(self.params, separator=', ')
paramstr = 'matrix=\n' + textwrap.indent(npstring, ' ')
return paramstr
def __repr__(self):
"""Add standard repr formatting around a __nice__ string"""
paramstr = self.__nice__()
classname = self.__class__.__name__
classstr = classname
return '<{}({}) at {}>'.format(classstr, paramstr, hex(id(self)))
def __str__(self):
"""Add standard str formatting around a __nice__ string"""
paramstr = self.__nice__()
classname = self.__class__.__name__
classstr = classname
return '<{}({})>'.format(classstr, paramstr)
class AffineTransform(ProjectiveTransform):
"""2D affine transformation.
Has the following form::
X = a0*x + a1*y + a2 =
= sx*x*cos(rotation) - sy*y*sin(rotation + shear) + a2
Y = b0*x + b1*y + b2 =
= sx*x*sin(rotation) + sy*y*cos(rotation + shear) + b2
where ``sx`` and ``sy`` are scale factors in the x and y directions,
and the homogeneous transformation matrix is::
[[a0 a1 a2]
[b0 b1 b2]
[0 0 1]]
Parameters
----------
matrix : (3, 3) array, optional
Homogeneous transformation matrix.
scale : {s as float or (sx, sy) as array, list or tuple}, optional
Scale factor(s). If a single value, it will be assigned to both
sx and sy.
.. versionadded:: 0.17
Added support for supplying a single scalar value.
rotation : float, optional
Rotation angle in counter-clockwise direction as radians.
shear : float, optional
Shear angle in counter-clockwise direction as radians.
translation : (tx, ty) as array, list or tuple, optional
Translation parameters.
Attributes
----------
params : (3, 3) array
Homogeneous transformation matrix.
"""
_coeffs = range(6)
def __init__(self, matrix=None, scale=None, rotation=None, shear=None,
translation=None):
params = any(param is not None
for param in (scale, rotation, shear, translation))
if params and matrix is not None:
raise ValueError("You cannot specify the transformation matrix and"
" the implicit parameters at the same time.")
elif matrix is not None:
if matrix.shape != (3, 3):
raise ValueError("Invalid shape of transformation matrix.")
self.params = matrix
elif params:
if scale is None:
scale = (1, 1)
if rotation is None:
rotation = 0
if shear is None:
shear = 0
if translation is None:
translation = (0, 0)
if np.isscalar(scale):
sx = sy = scale
else:
sx, sy = scale
self.params = np.array([
[sx * math.cos(rotation), -sy * math.sin(rotation + shear), 0],
[sx * math.sin(rotation), sy * math.cos(rotation + shear), 0],
[ 0, 0, 1]
])
self.params[0:2, 2] = translation
else:
# default to an identity transform
self.params = np.eye(3)
@property
def scale(self):
sx = math.sqrt(self.params[0, 0] ** 2 + self.params[1, 0] ** 2)
sy = math.sqrt(self.params[0, 1] ** 2 + self.params[1, 1] ** 2)
return sx, sy
@property
def rotation(self):
return math.atan2(self.params[1, 0], self.params[0, 0])
@property
def shear(self):
beta = math.atan2(- self.params[0, 1], self.params[1, 1])
return beta - self.rotation
@property
def translation(self):
return self.params[0:2, 2]
class EuclideanTransform(ProjectiveTransform):
"""2D Euclidean transformation.
Has the following form::
X = a0 * x - b0 * y + a1 =
= x * cos(rotation) - y * sin(rotation) + a1
Y = b0 * x + a0 * y + b1 =
= x * sin(rotation) + y * cos(rotation) + b1
where the homogeneous transformation matrix is::
[[a0 b0 a1]
[b0 a0 b1]
[0 0 1]]
The Euclidean transformation is a rigid transformation with rotation and
translation parameters. The similarity transformation extends the Euclidean
transformation with a single scaling factor.
Parameters
----------
matrix : (3, 3) array, optional
Homogeneous transformation matrix.
rotation : float, optional
Rotation angle in counter-clockwise direction as radians.
translation : (tx, ty) as array, list or tuple, optional
x, y translation parameters.
Attributes
----------
params : (3, 3) array
Homogeneous transformation matrix.
"""
def __init__(self, matrix=None, rotation=None, translation=None):
params = any(param is not None
for param in (rotation, translation))
if params and matrix is not None:
raise ValueError("You cannot specify the transformation matrix and"
" the implicit parameters at the same time.")
elif matrix is not None:
if matrix.shape != (3, 3):
raise ValueError("Invalid shape of transformation matrix.")
self.params = matrix
elif params:
if rotation is None:
rotation = 0
if translation is None:
translation = (0, 0)
self.params = np.array([
[math.cos(rotation), - math.sin(rotation), 0],
[math.sin(rotation), math.cos(rotation), 0],
[ 0, 0, 1]
])
self.params[0:2, 2] = translation
else:
# default to an identity transform
self.params = np.eye(3)
def estimate(self, src, dst):
"""Estimate the transformation from a set of corresponding points.
You can determine the over-, well- and under-determined parameters
with the total least-squares method.
Number of source and destination coordinates must match.
Parameters
----------
src : (N, 2) array
Source coordinates.
dst : (N, 2) array
Destination coordinates.
Returns
-------