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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
from copy import copy
import math
import textwrap
from abc import ABC, abstractmethod
from typing import Self
import warnings

import numpy as np
from scipy import spatial

from .._shared.utils import (
    safe_as_int,
    _deprecate_estimate,
    _update_from_estimate_docstring,
    _deprecate_inherited_estimate,
    FailedEstimation,
)
from .._shared.compat import NP_COPY_IF_NEEDED


def _affine_matrix_from_vector(v):
    """Affine matrix from linearized (d, d + 1) matrix entries."""
    nparam = v.size
    # solve for d in: d * (d + 1) = nparam
    d = (1 + np.sqrt(1 + 4 * nparam)) / 2 - 1
    dimensionality = int(np.round(d))  # round to prevent approx errors
    if d != dimensionality:
        raise ValueError(
            'Invalid number of elements for ' f'linearized matrix: {nparam}'
        )
    matrix = np.eye(dimensionality + 1)
    matrix[:-1, :] = np.reshape(v, (dimensionality, dimensionality + 1))
    return matrix


def _calc_center_normalize(points, scaling='rms'):
    """Calculate transformation `matrix` to center and normalize image points.

    Points are an array of shape (N, D).

    For `scaling` of 'raw', transformation returned `matrix` will be ``np.eye(D
    + 1)``.  For other values of `scaling`, `matrix` expresses a two-step
    translation and scaling procedure.  Points transformed with this `matrix`
    usually give better conditioning for fundamental matrix estimation than the
    original `points` [1]_.

    The two steps of transformation, for `scaling` other than 'raw', are:

    * 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 coordinate value of the
      centered points is 1 (`scaling` == 'rms') or such that the
      mean distance from the points to the origin of the coordinate system is
      ``sqrt(D)`` (`scaling` == 'mrs').

    If `scaling` != 'raw' and the points are all identical, the returned
    `matrix` will be all ``np.nan``.

    The 'mrs' scaling corresponds to the isotropic transformation
    algorithm in [1]_. 'rms' is the default, and gives very similar
    conditioning.

    Parameters
    ----------
    points : (N, D) array
        The coordinates of the image points.
    scaling : {'rms', 'mrs', 'raw'}, optional
        Scaling algorithm adjusting for magnitude of `points` after applying
        calculated translation. See above for explanation.

    Returns
    -------
    matrix : (D+1, D+1) array_like
        The transformation matrix to obtain the new 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.

    """
    n, d = points.shape
    scaling = scaling.lower()
    matrix = np.eye(d + 1)
    if scaling == 'raw':
        return matrix
    centroid = np.mean(points, axis=0)
    centered = points - centroid
    if scaling == 'rms':
        divisor = np.sqrt(np.mean(centered**2))
    elif scaling == 'mrs':
        divisor = np.mean(np.sqrt(np.sum(centered**2, axis=1))) / np.sqrt(d)
    else:
        raise ValueError(f'Unexpected "scaling" of "{scaling}"')

    # if all the points are the same, the transformation matrix cannot be
    # created. We return an equivalent matrix with np.nans as sentinel values.
    # This obviates the need for try/except blocks in functions calling this
    # one, and those are only needed when actual 0 is reached, rather than some
    # small value; ie, we don't need to worry about numerical stability here,
    # only actual 0.
    if divisor == 0:
        return matrix + np.nan

    matrix[:d, d] = -centroid
    matrix[:d, :] /= divisor
    return matrix


def _center_and_normalize_points(points, scaling='rms'):
    """Convenience function to calculate and apply scaling

    See: :func:`_calc_center_normalize` for details of the algorithm.
    """
    matrix = _calc_center_normalize(points, scaling)
    if not np.all(np.isfinite(matrix)):
        return matrix + np.nan, np.full_like(points, np.nan)
    return matrix, _apply_homogeneous(matrix, points)


def _apply_homogeneous(matrix, points):
    """Transform (N, D) `points` array with homogeneous (D+1, D+1) `matrix`.

    Parameters
    ----------
    matrix : (D+1, D+1) array_like
        The transformation matrix to obtain the new points. Note that any
        object with an `__array__` method [1]_ that returns a matrix with the
        correct dimensions can be used as input here. This includes all
        subclasses of :class:`ProjectiveTransform`, for example.
    points : (N, D) array
        The coordinates of the image points.

    Returns
    -------
    new_points : (N, D) array
        The transformed image points.

    References
    ----------
    .. [1]:
        https://numpy.org/doc/stable/user/basics.interoperability.html#using-arbitrary-objects-in-numpy
    """
    points = np.array(points, copy=NP_COPY_IF_NEEDED, ndmin=2)
    points_h = _append_homogeneous_dim(points)
    new_points_h = points_h @ matrix.T
    # We 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.
    divs = new_points_h[:, -1]
    divs = np.where(divs == 0, np.finfo(float).eps, divs)
    return new_points_h[:, :-1] / divs[:, None]


def _append_homogeneous_dim(points):
    """Append a column of ones to the right of `points`.

    This creates the representation of the points in the homogeneous coordinate
    space used by homogeneous matrix transforms.

    Parameters
    ----------
    points : array, shape (N, D)
        The input coordinates, where N is the number of points and D is the
        dimension of the coordinate space.

    Returns
    -------
    points_h : array, shape (N, D+1)
        The same points as homogeneous coordinates.
    """
    return np.hstack((points, np.ones((len(points), 1))))


def _umeyama(src, dst, estimate_scale):
    """Estimate N-D similarity transformation with or without scaling.

    Parameters
    ----------
    src : (M, N) array_like
        Source coordinates.
    dst : (M, N) array_like
        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`

    """
    src = np.asarray(src)
    dst = np.asarray(dst)

    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.float64)
    if np.linalg.det(A) < 0:
        d[dim - 1] = -1

    T = np.eye(dim + 1, dtype=np.float64)

    U, S, V = np.linalg.svd(A)

    # Eq. (40) and (43).
    # Matrix rank calculation from SVD (see numpy.linalg._linalg::matrix_rank code).
    # (this does SVD to check for small singular values, replicated here).
    tol = S.max() * np.max(A.shape) * np.finfo(float).eps
    rank = np.count_nonzero(S > tol)
    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(ABC):
    """Abstract base class for geometric transformations."""

    @abstractmethod
    def __call__(self, coords):
        """Apply forward transformation.

        Parameters
        ----------
        coords : (N, 2) array_like
            Source coordinates.

        Returns
        -------
        coords : (N, 2) array
            Destination coordinates.

        """

    @property
    @abstractmethod
    def inverse(self):
        """Return a transform object representing the inverse."""

    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))

    @classmethod
    @abstractmethod
    def identity(cls, dimensionality=None):
        """Identity transform

        Parameters
        ----------
        dimensionality : {None, 2}, optional
            This transform only allows dimensionality of 2, where None
            corresponds to 2. The parameter exists for compatibility with other
            transforms.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        """

    @classmethod
    def _prepare_estimation(cls, src, dst):
        """Create identity transform and make sure points are arrays."""
        src = np.asarray(src)
        dst = np.asarray(dst)
        return cls.identity(src.shape[1]), src, dst

    @classmethod
    def from_estimate(cls, src, dst, *args, **kwargs) -> Self | FailedEstimation:
        r"""Estimate transform.

        Parameters
        ----------
        src : (N, M) array_like
            Source coordinates.
        dst : (N, M) array_like
            Destination coordinates.
        \*args : sequence
            Any other positional arguments.
        \*\*kwargs : dict
            Any other keyword arguments.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = TransformClass.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")
        """
        return _from_estimate(cls, src, dst, *args, **kwargs)


def _from_estimate(cls, src, dst, *args, **kwargs):
    """Detached function for from_estimate base implementation."""
    tf, src, dst = cls._prepare_estimation(src, dst)
    msg = tf._estimate(src, dst, *args, **kwargs)
    return tf if msg is None else FailedEstimation(f'{cls.__name__}: {msg}')


class _HMatrixTransform(_GeometricTransform):
    """Transform accepting homogeneous matrix as input."""

    def __init__(self, matrix=None, *, dimensionality=None):
        if matrix is None:
            d = 2 if dimensionality is None else dimensionality
            matrix = np.eye(d + 1)
        else:
            matrix = np.asarray(matrix)
        self._check_matrix(matrix, dimensionality)
        self._check_dims(matrix.shape[0] - 1)
        self.params = matrix

    def _check_matrix(self, matrix, dimensionality):
        if dimensionality is not None:
            if dimensionality != matrix.shape[0] - 1:
                raise ValueError(
                    f'Dimensionality {dimensionality} does not match matrix '
                    f'{matrix}'
                )
        m = matrix.shape[0]
        if matrix.shape != (m, m):
            raise ValueError("Invalid shape of transformation matrix")

    def _check_dims(self, d):
        if d == 2:
            return
        raise NotImplementedError(
            f'Input for {type(self)} should result in 2D transform'
        )

    @classmethod
    def identity(cls, dimensionality=None):
        """Identity transform

        Parameters
        ----------
        dimensionality : {None, 2}, optional
            This transform only allows dimensionality of 2, where None
            corresponds to 2. The parameter exists for compatibility with other
            transforms.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        """
        d = 2 if dimensionality is None else dimensionality
        return cls(matrix=np.eye(d + 1))

    @property
    def dimensionality(self):
        return self.matrix.shape[0] - 1


class FundamentalMatrixTransform(_HMatrixTransform):
    """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`).

    Notes
    -----
    See [1]_ and [2]_ for details of the estimation procedure.  [2]_ is a good
    place to start.

    References
    ----------
    .. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in
           computer vision. Cambridge university press, 2003.
    .. [2] Zhang, Zhengyou. "Determining the epipolar geometry and its
           uncertainty: A review." International journal of computer vision 27
           (1998): 161-195.
           :DOI:`10.1023/A:1007941100561`
           https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/RR-2927.pdf

    Parameters
    ----------
    matrix : (3, 3) array_like, optional
        Fundamental matrix.
    dimensionality : int, optional
        Fallback number of dimensions when `matrix` not specified, in which
        case, must equal 2 (the default).

    Attributes
    ----------
    params : (3, 3) array
        Fundamental matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define source and destination points:

    >>> src = np.array([1.839035, 1.924743,
    ...                 0.543582, 0.375221,
    ...                 0.473240, 0.142522,
    ...                 0.964910, 0.598376,
    ...                 0.102388, 0.140092,
    ...                15.994343, 9.622164,
    ...                 0.285901, 0.430055,
    ...                 0.091150, 0.254594]).reshape(-1, 2)
    >>> dst = np.array([1.002114, 1.129644,
    ...                 1.521742, 1.846002,
    ...                 1.084332, 0.275134,
    ...                 0.293328, 0.588992,
    ...                 0.839509, 0.087290,
    ...                 1.779735, 1.116857,
    ...                 0.878616, 0.602447,
    ...                 0.642616, 1.028681]).reshape(-1, 2)

    Estimate the transformation matrix:

    >>> tform = ski.transform.FundamentalMatrixTransform.from_estimate(
    ...      src, dst)
    >>> tform.params
    array([[-0.21785884,  0.41928191, -0.03430748],
           [-0.07179414,  0.04516432,  0.02160726],
           [ 0.24806211, -0.42947814,  0.02210191]])

    Compute the Sampson distance:

    >>> tform.residuals(src, dst)
    array([0.0053886 , 0.00526101, 0.08689701, 0.01850534, 0.09418259,
           0.00185967, 0.06160489, 0.02655136])

    Apply inverse transformation:

    >>> tform.inverse(dst)
    array([[-0.0513591 ,  0.04170974,  0.01213043],
           [-0.21599496,  0.29193419,  0.00978184],
           [-0.0079222 ,  0.03758889, -0.00915389],
           [ 0.14187184, -0.27988959,  0.02476507],
           [ 0.05890075, -0.07354481, -0.00481342],
           [-0.21985267,  0.36717464, -0.01482408],
           [ 0.01339569, -0.03388123,  0.00497605],
           [ 0.03420927, -0.1135812 ,  0.02228236]])

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((8, 2))
    >>> bad_tform = ski.transform.FundamentalMatrixTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    """

    scaling = 'rms'

    def __call__(self, coords):
        """Apply forward transformation.

        Parameters
        ----------
        coords : (N, 2) array_like
            Source coordinates.

        Returns
        -------
        coords : (N, 3) array
            Epipolar lines in the destination image.

        """
        return _append_homogeneous_dim(coords) @ self.params.T

    @property
    def inverse(self):
        """Return a transform object representing the inverse.

        See Hartley & Zisserman, Ch. 8: Epipolar Geometry and the Fundamental
        Matrix, for an explanation of why F.T gives the inverse.

        """
        return type(self)(matrix=self.params.T)

    def _setup_constraint_matrix(self, src, dst):
        """Setup and solve the homogeneous epipolar constraint matrix::

            dst' * F * src = 0.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            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.

        """
        src = np.asarray(src)
        dst = np.asarray(dst)
        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.
        src_matrix = _calc_center_normalize(src, self.scaling)
        dst_matrix = _calc_center_normalize(dst, self.scaling)
        if np.any(np.isnan(src_matrix + dst_matrix)):
            self.params = np.full((3, 3), np.nan)
            return 3 * [np.full((3, 3), np.nan)]
        src_h = _append_homogeneous_dim(_apply_homogeneous(src_matrix, src))
        dst_h = _append_homogeneous_dim(_apply_homogeneous(dst_matrix, dst))

        # Setup homogeneous linear equation as dst' * F * src = 0.
        # Hartley notation u -> src[:, 0], v -> src[:, 1],
        # u' -> dst[:, 0], v' -> dst[:, 1].  Required output cols are:
        # uu', vu', u', uv', vv', v', u, v, 1
        cols = [(d_v * s_v) for d_v in dst_h.T for s_v in src_h.T]
        A = np.stack(cols, axis=1)

        # 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

    @classmethod
    def from_estimate(cls, src, dst):
        """Estimate fundamental matrix using 8-point algorithm.

        The 8-point algorithm requires at least 8 corresponding point pairs.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = FundamentalMatrixTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        Raises
        ------
        ValueError
            If `src` has fewer than 8 rows.
        """
        return super().from_estimate(src, dst)

    def _estimate(self, src, dst):
        F_normalized, src_matrix, dst_matrix = self._setup_constraint_matrix(src, dst)
        if np.any(np.isnan(F_normalized + src_matrix + dst_matrix)):
            return 'Scaling failed for input points'

        # Enforcing the internal constraint that two singular values must be
        # non-zero and one must be zero (rank 2).
        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 None

    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 = _append_homogeneous_dim(src)
        dst_homogeneous = _append_homogeneous_dim(dst)

        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
        )

    @_deprecate_estimate
    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_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        """
        return self._estimate(src, dst) is None


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_like, optional
        Rotation matrix of the relative camera motion.
    translation : (3, 1) array_like, optional
        Translation vector of the relative camera motion. The vector must
        have unit length.
    matrix : (3, 3) array_like, optional
        Essential matrix.
    dimensionality : int, optional
        Fallback number of dimensions when `matrix` not specified, in which
        case, must equal 2 (the default).

    Attributes
    ----------
    params : (3, 3) array
        Essential matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski
    >>>
    >>> tform = ski.transform.EssentialMatrixTransform(
    ...     rotation=np.eye(3), translation=np.array([0, 0, 1])
    ... )
    >>> tform.params
    array([[ 0., -1.,  0.],
           [ 1.,  0.,  0.],
           [ 0.,  0.,  0.]])
    >>> src = np.array([[ 1.839035, 1.924743],
    ...                 [ 0.543582, 0.375221],
    ...                 [ 0.47324 , 0.142522],
    ...                 [ 0.96491 , 0.598376],
    ...                 [ 0.102388, 0.140092],
    ...                 [15.994343, 9.622164],
    ...                 [ 0.285901, 0.430055],
    ...                 [ 0.09115 , 0.254594]])
    >>> dst = np.array([[1.002114, 1.129644],
    ...                 [1.521742, 1.846002],
    ...                 [1.084332, 0.275134],
    ...                 [0.293328, 0.588992],
    ...                 [0.839509, 0.08729 ],
    ...                 [1.779735, 1.116857],
    ...                 [0.878616, 0.602447],
    ...                 [0.642616, 1.028681]])
    >>> tform = ski.transform.EssentialMatrixTransform.from_estimate(src, dst)
    >>> tform.residuals(src, dst)
    array([0.42455187, 0.01460448, 0.13847034, 0.12140951, 0.27759346,
           0.32453118, 0.00210776, 0.26512283])

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((8, 2))
    >>> bad_tform = ski.transform.EssentialMatrixTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    """

    # Threshold for determinant of rotation matrix.
    _rot_det_tol = 1e-6

    # Threshold for difference of translation vector from unit length.
    _trans_len_tol = 1e-6

    def __init__(
        self, *, rotation=None, translation=None, matrix=None, dimensionality=None
    ):
        n_rt_none = sum(p is None for p in (rotation, translation))
        if n_rt_none == 1:
            raise ValueError(
                "Both rotation and translation required when one is specified."
            )
        elif n_rt_none == 0:
            if matrix is not None:
                raise ValueError(
                    "Do not specify rotation or translation when "
                    "matrix is specified."
                )
            matrix = self._rt2matrix(rotation, translation)
        super().__init__(matrix=matrix, dimensionality=dimensionality)

    def _rt2matrix(self, rotation, translation):
        rotation = np.asarray(rotation)
        translation = np.asarray(translation)
        if rotation.shape != (3, 3):
            raise ValueError("Invalid shape of rotation matrix")
        if abs(np.linalg.det(rotation) - 1) > self._rot_det_tol:
            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) > self._trans_len_tol:
            raise ValueError("Translation vector must have unit length")
        # Matrix representation of the cross product for t.
        t0, t1, t2 = translation
        t_arr = np.array([[0, -t2, t1], [t2, 0, -t0], [-t1, t0, 0]], dtype=float)
        return t_arr @ rotation

    @classmethod
    def from_estimate(cls, 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_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = EssentialMatrixTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        Raises
        ------
        ValueError
            If `src` has fewer than 8 rows.

        """
        return super().from_estimate(src, dst)

    def _estimate(self, src, dst):
        E_normalized, src_matrix, dst_matrix = self._setup_constraint_matrix(src, dst)
        if np.any(np.isnan(E_normalized + src_matrix + dst_matrix)):
            return 'Scaling failed for input points'

        # 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 None

    @_deprecate_estimate
    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_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        """
        return self._estimate(src, dst) is None


class ProjectiveTransform(_HMatrixTransform):
    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 : (D+1, D+1) array_like, optional
        Homogeneous transformation matrix.
    dimensionality : int, optional
        Fallback number of dimensions when `matrix` not specified.

    Attributes
    ----------
    params : (D+1, D+1) array
        Homogeneous transformation matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.ProjectiveTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.ProjectiveTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[ -16.56,    5.82,  895.81],
    ...                            [ -10.31,   -8.29, 2075.43],
    ...                            [  -0.05,    0.02,    1.  ]], atol=0.01)
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.ProjectiveTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    """

    scaling = 'rms'

    @property
    def _coeff_inds(self):
        """Indices into flat ``self.params`` with coefficients to estimate"""
        return range(self.params.size - 1)

    def _check_dims(self, d):
        if d >= 2:
            return
        raise NotImplementedError(
            f'Input for {type(self)} should result in transform of >=2D'
        )

    @property
    def _inv_matrix(self):
        return np.linalg.inv(self.params)

    def __array__(self, dtype=None, copy=None):
        return self.params if dtype is None else self.params.astype(dtype)

    def __call__(self, coords):
        """Apply forward transformation.

        Parameters
        ----------
        coords : (N, D) array_like
            Source coordinates.

        Returns
        -------
        coords_out : (N, D) array
            Destination coordinates.

        """
        return _apply_homogeneous(self.params, coords)

    @property
    def inverse(self):
        """Return a transform object representing the inverse."""
        return type(self)(matrix=self._inv_matrix)

    @classmethod
    def from_estimate(cls, src, dst, weights=None):
        """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.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        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_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = ProjectiveTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        """
        return super().from_estimate(src, dst, weights)

    def _estimate(self, src, dst, weights=None):
        src = np.asarray(src)
        dst = np.asarray(dst)
        n, d = src.shape
        fail_matrix = np.full((d + 1, d + 1), np.nan)

        src_matrix, src = _center_and_normalize_points(src)
        dst_matrix, dst = _center_and_normalize_points(dst)
        if not np.all(np.isfinite(src_matrix + dst_matrix)):
            self.params = fail_matrix
            return 'Scaling generated NaN values'

        # params: a0, a1, a2, b0, b1, b2, c0, c1
        A = np.zeros((n * d, (d + 1) ** 2))
        # fill the A matrix with the appropriate block matrices; see docstring
        # for 2D example — this can be generalised to more blocks in the 3D and
        # higher-dimensional cases.
        for ddim in range(d):
            A[ddim * n : (ddim + 1) * n, ddim * (d + 1) : ddim * (d + 1) + d] = src
            A[ddim * n : (ddim + 1) * n, ddim * (d + 1) + d] = 1
            A[ddim * n : (ddim + 1) * n, -d - 1 : -1] = src
            A[ddim * n : (ddim + 1) * n, -1] = -1
            A[ddim * n : (ddim + 1) * n, -d - 1 :] *= -dst[:, ddim : (ddim + 1)]

        # Select relevant columns, depending on params
        A = A[:, list(self._coeff_inds) + [-1]]

        # Get the vectors that correspond to singular values, also applying
        # the weighting if provided
        if weights is None:
            _, _, V = np.linalg.svd(A)
        else:
            weights = np.asarray(weights)
            W = np.diag(np.tile(np.sqrt(weights / np.max(weights)), d))
            _, _, V = np.linalg.svd(W @ A)

        H = np.zeros((d + 1, d + 1))
        # Solution is right singular vector that corresponds to smallest
        # singular value.
        if np.isclose(V[-1, -1], 0):
            self.params = fail_matrix
            return 'Right singular vector has 0 final element'

        H.flat[list(self._coeff_inds) + [-1]] = -V[-1, :-1] / V[-1, -1]
        H[d, d] = 1

        # De-center and de-normalize
        H = np.linalg.inv(dst_matrix) @ H @ src_matrix

        # Small errors can creep in if points are not exact, causing the last
        # element of H to deviate from unity. Correct for that here.
        H /= H[-1, -1]

        self.params = H

        return None

    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)
        else:
            raise TypeError("Cannot combine transformations of differing " "types.")

    def __nice__(self):
        """common 'paramstr' used by __str__ and __repr__"""
        if not hasattr(self, 'params'):
            return '<not yet initialized>'
        npstring = np.array2string(self.params, separator=', ')
        return 'matrix=\n' + textwrap.indent(npstring, '    ')

    def __repr__(self):
        """Add standard repr formatting around a __nice__ string"""
        return f'<{type(self).__name__}({self.__nice__()}) at {hex(id(self))}>'

    def __str__(self):
        """Add standard str formatting around a __nice__ string"""
        return f'<{type(self).__name__}({self.__nice__()})>'

    @property
    def dimensionality(self):
        """The dimensionality of the transformation."""
        return self.params.shape[0] - 1

    @classmethod
    def identity(cls, dimensionality=None):
        """Identity transform

        Parameters
        ----------
        dimensionality : {None, int}, optional
            Dimensionality of identity transform.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        """
        return super().identity(dimensionality=dimensionality)

    @_deprecate_estimate
    def estimate(self, src, dst, weights=None):
        """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.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        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_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        """
        return self._estimate(src, dst, weights) is None


@_update_from_estimate_docstring
@_deprecate_inherited_estimate
class AffineTransform(ProjectiveTransform):
    """Affine transformation.

    Has the following form::

        X = a0 * x + a1 * y + a2
          =   sx * x * [cos(rotation) + tan(shear_y) * sin(rotation)]
            - sy * y * [tan(shear_x) * cos(rotation) + sin(rotation)]
            + translation_x

        Y = b0 * x + b1 * y + b2
          =   sx * x * [sin(rotation) - tan(shear_y) * cos(rotation)]
            - sy * y * [tan(shear_x) * sin(rotation) - cos(rotation)]
            + translation_y

    where ``sx`` and ``sy`` are scale factors in the x and y directions.

    This is equivalent to applying the operations in the following order:

    1. Scale
    2. Shear
    3. Rotate
    4. Translate

    The homogeneous transformation matrix is::

        [[a0  a1  a2]
         [b0  b1  b2]
         [0   0    1]]

    In 2D, the transformation parameters can be given as the homogeneous
    transformation matrix, above, or as the implicit parameters, scale,
    rotation, shear, and translation in x (a2) and y (b2). For 3D and higher,
    only the matrix form is allowed.

    In narrower transforms, such as the Euclidean (only rotation and
    translation) or Similarity (rotation, translation, and a global scale
    factor) transforms, it is possible to specify 3D transforms using implicit
    parameters also.

    Parameters
    ----------
    matrix : (D+1, D+1) array_like, optional
        Homogeneous transformation matrix. If this matrix is provided, it is an
        error to provide any of scale, rotation, shear, or translation.
    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. Only available for 2D.

        .. versionadded:: 0.17
           Added support for supplying a single scalar value.
    shear : float or 2-tuple of float, optional
        The x and y shear angles, clockwise, by which these axes are
        rotated around the origin [2].
        If a single value is given, take that to be the x shear angle, with
        the y angle remaining 0. Only available in 2D.
    rotation : float, optional
        Rotation angle, clockwise, as radians. Only available for 2D.
    translation : (tx, ty) as array, list or tuple, optional
        Translation parameters. Only available for 2D.
    dimensionality : int, optional
        Fallback number of dimensions for transform when none of `matrix`,
        `scale`, `rotation`, `shear` or `translation` are specified.  If any of
        `scale`, `rotation`, `shear` or `translation` are specified, must equal
        2 (the default).

    Attributes
    ----------
    params : (D+1, D+1) array
        Homogeneous transformation matrix.

    Raises
    ------
    ValueError
        If both ``matrix`` and any of the other parameters are provided.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.AffineTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    Define a transform with parameters:

    >>> tform = ski.transform.AffineTransform(scale=4, rotation=0.2)
    >>> np.round(tform.params, 2)
    array([[ 3.92, -0.79,  0.  ],
           [ 0.79,  3.92,  0.  ],
           [ 0.  ,  0.  ,  1.  ]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.AffineTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[   0.5,   -1. ,  275. ],
    ...                            [   1.5,    4. , -625. ],
    ...                            [   0. ,    0. ,    1. ]])
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.AffineTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    References
    ----------
    .. [1] Wikipedia, "Affine transformation",
           https://en.wikipedia.org/wiki/Affine_transformation#Image_transformation
    .. [2] Wikipedia, "Shear mapping",
           https://en.wikipedia.org/wiki/Shear_mapping
    """

    def __init__(
        self,
        matrix=None,
        *,
        scale=None,
        shear=None,
        rotation=None,
        translation=None,
        dimensionality=None,
    ):
        n_srst_none = sum(p is None for p in (scale, rotation, shear, translation))
        if n_srst_none != 4:
            if matrix is not None:
                raise ValueError(
                    "Do not specify any implicit parameters when "
                    "matrix is specified."
                )
            if dimensionality is not None and dimensionality > 2:
                raise ValueError('Implicit parameters only valid for 2D transforms')
            # 2D parameter checks explicit or implicit in _srst2matrix.
            matrix = self._srst2matrix(scale, rotation, shear, translation)
            if matrix.shape[0] != 3:
                raise ValueError('Implicit parameters must give 2D transforms')
        super().__init__(matrix=matrix, dimensionality=dimensionality)

    @property
    def _coeff_inds(self):
        """Indices into flat ``self.params`` with coefficients to estimate"""
        return range(self.dimensionality * (self.dimensionality + 1))

    def _srst2matrix(self, scale, rotation, shear, translation):
        scale = (1, 1) if scale is None else scale
        sx, sy = (scale, scale) if np.isscalar(scale) else scale
        rotation = 0 if rotation is None else rotation
        if not np.isscalar(rotation):
            raise ValueError('rotation must be scalar (2D rotation)')
        shear = 0 if shear is None else shear
        shear_x, shear_y = (shear, 0) if np.isscalar(shear) else shear
        translation = (0, 0) if translation is None else translation
        if np.isscalar(translation):
            raise ValueError('translation must be length 2')
        a2, b2 = translation

        a0 = sx * (math.cos(rotation) + math.tan(shear_y) * math.sin(rotation))
        a1 = -sy * (math.tan(shear_x) * math.cos(rotation) + math.sin(rotation))

        b0 = sx * (math.sin(rotation) - math.tan(shear_y) * math.cos(rotation))
        b1 = -sy * (math.tan(shear_x) * math.sin(rotation) - math.cos(rotation))
        return np.array([[a0, a1, a2], [b0, b1, b2], [0, 0, 1]])

    @property
    def scale(self):
        if self.dimensionality != 2:
            return np.sqrt(np.sum(self.params**2, axis=0))[: self.dimensionality]
        ss = np.sum(self.params**2, axis=0)
        ss[1] = ss[1] / (math.tan(self.shear) ** 2 + 1)
        return np.sqrt(ss)[: self.dimensionality]

    @property
    def rotation(self):
        if self.dimensionality != 2:
            raise NotImplementedError(
                'The rotation property is only implemented for 2D transforms.'
            )
        return math.atan2(self.params[1, 0], self.params[0, 0])

    @property
    def shear(self):
        if self.dimensionality != 2:
            raise NotImplementedError(
                'The shear property is only implemented for 2D transforms.'
            )
        beta = math.atan2(-self.params[0, 1], self.params[1, 1])
        return beta - self.rotation

    @property
    def translation(self):
        return self.params[0 : self.dimensionality, self.dimensionality]


class PiecewiseAffineTransform(_GeometricTransform):
    """Piecewise affine transformation.

    Control points are used to define the mapping. The transform is based on
    a Delaunay triangulation of the points to form a mesh. Each triangle is
    used to find a local affine transform.

    Attributes
    ----------
    affines : list of AffineTransform objects
        Affine transformations for each triangle in the mesh.
    inverse_affines : list of AffineTransform objects
        Inverse affine transformations for each triangle in the mesh.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transformation by estimation:

    >>> src = [[-12.3705, -10.5075],
    ...        [-10.7865, 15.4305],
    ...        [8.6985, 10.8675],
    ...        [11.4975, -9.5715],
    ...        [7.8435, 7.4835],
    ...        [-5.3325, 6.5025],
    ...        [6.7905, -6.3765],
    ...        [-6.1695, -0.8235]]
    >>> dst = [[0, 0],
    ...        [0, 5800],
    ...        [4900, 5800],
    ...        [4900, 0],
    ...        [4479, 4580],
    ...        [1176, 3660],
    ...        [3754, 790],
    ...        [1024, 1931]]
    >>> tform = ski.transform.PiecewiseAffineTransform.from_estimate(src, dst)

    Calling the transform applies the transformation to the points:

    >>> np.allclose(tform(src), dst)
    True

    You can apply the inverse transform:

    >>> np.allclose(tform.inverse(dst), src)
    True

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = [[1, 1]] * 6 + src[6:]
    >>> bad_tform = ski.transform.PiecewiseAffineTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    """

    def __init__(self):
        self._tesselation = None
        self._inverse_tesselation = None
        self.affines = None
        self.inverse_affines = None

    @classmethod
    def from_estimate(cls, src, dst):
        """Estimate the transformation from a set of corresponding points.

        Number of source and destination coordinates must match.

        Parameters
        ----------
        src : (N, D) array_like
            Source coordinates.
        dst : (N, D) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = PiecewiseAffineTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        """
        return super().from_estimate(src, dst)

    def _estimate(self, src, dst):
        src = np.asarray(src)
        dst = np.asarray(dst)
        N, D = src.shape

        # forward piecewise affine
        # triangulate input positions into mesh
        self._tesselation = spatial.Delaunay(src)

        fail_matrix = np.full((D + 1, D + 1), np.nan)

        # find affine mapping from source positions to destination
        self.affines = []
        messages = []
        for i, tri in enumerate(self._tesselation.simplices):
            affine = AffineTransform.from_estimate(src[tri, :], dst[tri, :])
            if not affine:
                messages.append(f'Failure at forward simplex {i}: {affine}')
                affine = AffineTransform(fail_matrix.copy())
            self.affines.append(affine)

        # inverse piecewise affine
        # triangulate input positions into mesh
        self._inverse_tesselation = spatial.Delaunay(dst)
        # find affine mapping from source positions to destination
        self.inverse_affines = []
        for i, tri in enumerate(self._inverse_tesselation.simplices):
            affine = AffineTransform.from_estimate(dst[tri, :], src[tri, :])
            if not affine:
                messages.append(f'Failure at inverse simplex {i}: {affine}')
                affine = AffineTransform(fail_matrix.copy())
            self.inverse_affines.append(affine)

        return '; '.join(messages) if messages else None

    def __call__(self, coords):
        """Apply forward transformation.

        Coordinates outside of the mesh will be set to `- 1`.

        Parameters
        ----------
        coords : (N, D) array_like
            Source coordinates.

        Returns
        -------
        coords : (N, 2) array
            Transformed coordinates.

        """
        coords = np.asarray(coords)
        out = np.empty_like(coords, np.float64)

        # determine triangle index for each coordinate
        simplex = self._tesselation.find_simplex(coords)

        # coordinates outside of mesh
        out[simplex == -1, :] = -1

        for index in range(len(self._tesselation.simplices)):
            # affine transform for triangle
            affine = self.affines[index]
            # all coordinates within triangle
            index_mask = simplex == index

            out[index_mask, :] = affine(coords[index_mask, :])

        return out

    @property
    def inverse(self):
        """Return a transform object representing the inverse."""
        tform = type(self)()
        # Copy parameters (None or list) for safety.
        tform._tesselation = copy(self._inverse_tesselation)
        tform._inverse_tesselation = copy(self._tesselation)
        tform.affines = copy(self.inverse_affines)
        tform.inverse_affines = copy(self.affines)
        return tform

    @classmethod
    def identity(cls, dimensionality=None):
        """Identity transform

        Parameters
        ----------
        dimensionality : optional
            This transform does not use the `dimensionality` parameter, so the
            value is ignored.  The parameter exists for compatibility with
            other transforms.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        """
        return cls()

    @_deprecate_estimate
    def estimate(self, src, dst):
        """Estimate the transformation from a set of corresponding points.

        Number of source and destination coordinates must match.

        Parameters
        ----------
        src : (N, D) array_like
            Source coordinates.
        dst : (N, D) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if all pieces of the model are successfully estimated.

        """
        return self._estimate(src, dst) is None


def _euler_rotation_matrix(angles, degrees=False):
    """Produce an Euler rotation matrix from the given intrinsic rotation angles
    for the axes x, y and z.

    Parameters
    ----------
    angles : array of float, shape (3,)
        The transformation angles in radians.
    degrees : bool, optional
        If True, then the given angles are assumed to be in degrees. Default is False.

    Returns
    -------
    R : array of float, shape (3, 3)
        The Euler rotation matrix.

    """
    return spatial.transform.Rotation.from_euler(
        'XYZ', angles=angles, degrees=degrees
    ).as_matrix()


class EuclideanTransform(ProjectiveTransform):
    """Euclidean transformation, also known as a rigid transform.

    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.

    In 2D and 3D, the transformation parameters may be provided either via
    `matrix`, the homogeneous transformation matrix, above, or via the
    implicit parameters `rotation` and/or `translation` (where `a1` is the
    translation along `x`, `b1` along `y`, etc.). Beyond 3D, if the
    transformation is only a translation, you may use the implicit parameter
    `translation`; otherwise, you must use `matrix`.

    The implicit parameters are applied in the following order:

    1. Rotation;
    2. Translation.

    Parameters
    ----------
    matrix : (D+1, D+1) array_like, optional
        Homogeneous transformation matrix.
    rotation : float or sequence of float, optional
        Rotation angle, clockwise, in radians. If given as a vector, it is
        interpreted as Euler rotation angles [1]_. Only 2D (single rotation)
        and 3D (Euler rotations) values are supported. For higher dimensions,
        you must provide or estimate the transformation matrix instead, and
        pass that as `matrix` above.
    translation : (x, y[, z, ...]) sequence of float, length D, optional
        Translation parameters for each axis.
    dimensionality : int, optional
        Fallback number of dimensions for transform when no other parameter
        is specified.  Otherwise ignored, and we infer dimensionality from the
        input parameters.

    Attributes
    ----------
    params : (D+1, D+1) array
        Homogeneous transformation matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.EuclideanTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    Define a transform with parameters:

    >>> tform = ski.transform.EuclideanTransform(
    ...             rotation=0.2, translation=[1, 2])
    >>> np.round(tform.params, 2)
    array([[ 0.98, -0.2 ,  1.  ],
           [ 0.2 ,  0.98,  2.  ],
           [ 0.  ,  0.  ,  1.  ]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.EuclideanTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[ 0.99, 0.12,  16.77],
    ...                            [-0.12, 0.99, 122.91],
    ...                            [ 0.  , 0.  ,   1.  ]], atol=0.01)
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.EuclideanTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions

    """

    # Whether to estimate scale during estimation.
    _estimate_scale = False

    def __init__(
        self, matrix=None, *, rotation=None, translation=None, dimensionality=None
    ):
        n_rt_none = sum(p is None for p in (rotation, translation))
        if n_rt_none != 2:
            if matrix is not None:
                raise ValueError(
                    "Do not specify any implicit parameters when "
                    "matrix is specified."
                )
            n_dims, chk_msg = self._rt2ndims_msg(rotation, translation)
            if chk_msg is not None:
                raise ValueError(chk_msg)
            matrix = self._rt2matrix(rotation, translation, n_dims)
        super().__init__(matrix=matrix, dimensionality=dimensionality)

    def _rt2ndims_msg(self, rotation, translation):
        if rotation is not None:
            N = 1 if np.isscalar(rotation) else len(rotation)
            msg = (
                '``rotations`` must be scalar (3D) or length 3 (3D)'
                if N not in (1, 3)
                else None
            )
            return 2 if N == 1 else N, msg
        if translation is not None:
            return (2 if np.isscalar(translation) else len(translation), None)
        return None, None

    def _rt2matrix(self, rotation, translation, n_dims):
        if translation is None:
            translation = (0,) * n_dims
        if rotation is None:
            rotation = 0 if n_dims == 2 else np.zeros(3)
        matrix = np.eye(n_dims + 1)
        if n_dims == 2:
            cos_r, sin_r = math.cos(rotation), math.sin(rotation)
            matrix[:2, :2] = [[cos_r, -sin_r], [sin_r, cos_r]]
        elif n_dims == 3:
            matrix[:3, :3] = _euler_rotation_matrix(rotation)
        matrix[0:n_dims, n_dims] = translation
        return matrix

    @classmethod
    def from_estimate(cls, src, dst) -> Self | FailedEstimation:
        """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_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = EuclideanTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        """
        # Use base implementation to avoid weights argument of
        # ProjectiveTransform ancestor class.
        return _from_estimate(cls, src, dst)

    def _estimate(self, src, dst):
        self.params = _umeyama(src, dst, self._estimate_scale)

        # _umeyama will return nan if the problem is not well-conditioned.
        return (
            'Poor conditioning for estimation'
            if np.any(np.isnan(self.params))
            else None
        )

    @property
    def rotation(self):
        if self.dimensionality == 2:
            return math.atan2(self.params[1, 0], self.params[1, 1])
        elif self.dimensionality == 3:
            # Returning 3D Euler rotation matrix
            return self.params[:3, :3]
        else:
            raise NotImplementedError(
                'Rotation only implemented for 2D and 3D transforms.'
            )

    @property
    def translation(self):
        return self.params[0 : self.dimensionality, self.dimensionality]

    @_deprecate_estimate
    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_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        """
        return self._estimate(src, dst) is None


@_update_from_estimate_docstring
@_deprecate_inherited_estimate
class SimilarityTransform(EuclideanTransform):
    """Similarity transformation.

    Has the following form in 2D::

        X = a0 * x - b0 * y + a1 =
          = s * x * cos(rotation) - s * y * sin(rotation) + a1

        Y = b0 * x + a0 * y + b1 =
          = s * x * sin(rotation) + s * y * cos(rotation) + b1

    where ``s`` is a scale factor and the homogeneous transformation matrix is::

        [[a0 -b0  a1]
         [b0  a0  b1]
         [0   0   1 ]]

    The similarity transformation extends the Euclidean transformation with a
    single scaling factor in addition to the rotation and translation
    parameters.

    The implicit parameters are applied in the following order:

    1. Scale;
    2. Rotation;
    3. Translation.

    Parameters
    ----------
    matrix : (dim+1, dim+1) array_like, optional
        Homogeneous transformation matrix.
    scale : float, optional
        Scale factor. Implemented only for 2D and 3D.
    rotation : float, optional
        Rotation angle, clockwise, as radians.
        Implemented only for 2D and 3D. For 3D, this is given in ZYX Euler
        angles.
    translation : (dim,) array_like, optional
        x, y[, z] translation parameters. Implemented only for 2D and 3D.
    dimensionality : int, optional
        The dimensionality of the transform, corresponding to ``dim`` above.
        Ignored if `matrix` is not None, and set to ``matrix.shape[0] - 1``.
        Otherwise, must be one of 2 or 3.

    Attributes
    ----------
    params : (dim+1, dim+1) array
        Homogeneous transformation matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.SimilarityTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    Define a transform with parameters:

    >>> tform = ski.transform.SimilarityTransform(
    ...             rotation=0.2, translation=[1, 2])
    >>> np.round(tform.params, 2)
    array([[ 0.98, -0.2 ,  1.  ],
           [ 0.2 ,  0.98,  2.  ],
           [ 0.  ,  0.  ,  1.  ]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.SimilarityTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[ 1.79, 0.21, -142.86],
    ...                            [-0.21, 1.79,   21.43],
    ...                            [ 0.  , 0.  ,    1.  ]], atol=0.01)
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.SimilarityTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    """

    # Whether to estimate scale during estimation.
    _estimate_scale = True

    def __init__(
        self,
        matrix=None,
        *,
        scale=None,
        rotation=None,
        translation=None,
        dimensionality=None,
    ):
        n_srt_none = sum(p is None for p in (scale, rotation, translation))
        if n_srt_none != 3:
            if matrix is not None:
                raise ValueError(
                    "Do not specify any implicit parameters when "
                    "matrix is specified."
                )
            self._check_scale(scale, (rotation, translation), dimensionality)
            # Scale is special.  Scalar scale does not tell us the dimensions.
            if scale is not None and not np.isscalar(scale):
                n_dims, chk_msg = len(scale), None
            else:
                n_dims, chk_msg = self._rt2ndims_msg(rotation, translation)
            if chk_msg is not None:
                raise ValueError(chk_msg)
            # n_dims can be None for scalar scale, other parameters are None.
            n_dims = (
                n_dims
                if n_dims is not None
                else dimensionality
                if dimensionality is not None
                else 2
            )
            matrix = self._rt2matrix(rotation, translation, n_dims)
            if scale not in (None, 1):
                matrix[:n_dims, :n_dims] *= scale
        super().__init__(matrix=matrix, dimensionality=dimensionality)

    def _check_scale(self, scale, other_params, dimensionality):
        """Check, warn for scalar scaling"""
        if dimensionality in (None, 2) or scale is None or not np.isscalar(scale):
            return
        if all(p is None for p in other_params):
            warnings.warn(
                'In the future, it will be a ValueError to pass a '
                'scalar `scale` value with a ``dimensionality`` '
                '> 2\n,and without other implicit parameters '
                'to indicate the dimensionality of the transform.\n'
                'Please indicate dimensionality by passing a vector '
                'of suitable length to `scale`.',
                FutureWarning,
                stacklevel=2,
            )

    @property
    def scale(self):
        # det = scale**(# of dimensions), therefore scale = det**(1/ndim)
        if self.dimensionality == 2:
            return np.sqrt(np.linalg.det(self.params))
        elif self.dimensionality == 3:
            return np.cbrt(np.linalg.det(self.params))
        else:
            raise NotImplementedError('Scale is only implemented for 2D and 3D.')


class PolynomialTransform(_GeometricTransform):
    """2D polynomial transformation.

    Has the following form::

        X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
        Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))

    Parameters
    ----------
    params : (2, N) array_like, optional
        Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So,
        a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`.
    dimensionality : int, optional
        Must have value 2 (the default) for polynomial transforms.

    Attributes
    ----------
    params : (2, N) array
        Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So,
        a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transformation by estimation:

    >>> src = [[-12.3705, -10.5075],
    ...        [-10.7865, 15.4305],
    ...        [8.6985, 10.8675],
    ...        [11.4975, -9.5715],
    ...        [7.8435, 7.4835],
    ...        [-5.3325, 6.5025],
    ...        [6.7905, -6.3765],
    ...        [-6.1695, -0.8235]]
    >>> dst = [[0, 0],
    ...        [0, 5800],
    ...        [4900, 5800],
    ...        [4900, 0],
    ...        [4479, 4580],
    ...        [1176, 3660],
    ...        [3754, 790],
    ...        [1024, 1931]]
    >>> tform = ski.transform.PolynomialTransform.from_estimate(src, dst)

    Calling the transform applies the transformation to the points:

    >>> pts = tform(src)
    >>> np.allclose(pts, [[   7.54,   12.27],
    ...                   [   2.98, 5796.95],
    ...                   [4870.44, 5766.59],
    ...                   [4889.72,   -6.72],
    ...                   [4515.62, 4617.5 ],
    ...                   [1183.25, 3694.  ],
    ...                   [3767.57,  800.53],
    ...                   [ 998.02, 1881.97]], atol=0.01)
    True
    """

    def __init__(self, params=None, *, dimensionality=None):
        if dimensionality is None:
            dimensionality = 2
        elif dimensionality != 2:
            raise NotImplementedError(
                'Polynomial transforms are only implemented for 2D.'
            )
        self.params = np.array([[0, 1, 0], [0, 0, 1]] if params is None else params)
        if self.params.shape == () or self.params.shape[0] != 2:
            raise ValueError("Transformation parameters must be shape (2, N)")

    @classmethod
    def from_estimate(cls, src, dst, order=2, weights=None):
        """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 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
            Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))

        These equations can be transformed to the following form::

            0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X
            0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - 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   = [[1 x y x**2 x*y y**2 ... 0 ...             0 -X]
                   [0 ...                 0 1 x y x**2 x*y y**2 -Y]
                    ...
                    ...
                  ]
            x.T = [a00 a10 a11 a20 a21 a22 ... ann
                   b00 b10 b11 b20 b21 b22 ... bnn 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.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        order : int, optional
            Polynomial order (number of coefficients is order + 1).
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = PolynomialTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        """
        return super().from_estimate(src, dst, order, weights)

    def _estimate(self, src, dst, order=2, weights=None):
        src = np.asarray(src)
        dst = np.asarray(dst)
        xs = src[:, 0]
        ys = src[:, 1]
        xd = dst[:, 0]
        yd = dst[:, 1]
        rows = src.shape[0]

        # number of unknown polynomial coefficients
        order = safe_as_int(order)
        u = (order + 1) * (order + 2)

        A = np.zeros((rows * 2, u + 1))
        pidx = 0
        for j in range(order + 1):
            for i in range(j + 1):
                A[:rows, pidx] = xs ** (j - i) * ys**i
                A[rows:, pidx + u // 2] = xs ** (j - i) * ys**i
                pidx += 1

        A[:rows, -1] = xd
        A[rows:, -1] = yd

        # Get the vectors that correspond to singular values, also applying
        # the weighting if provided
        if weights is None:
            _, _, V = np.linalg.svd(A)
        else:
            weights = np.asarray(weights)
            W = np.diag(np.tile(np.sqrt(weights / np.max(weights)), 2))
            _, _, V = np.linalg.svd(W @ A)

        # solution is right singular vector that corresponds to smallest
        # singular value
        params = -V[-1, :-1] / V[-1, -1]

        self.params = params.reshape((2, u // 2))

        return None

    def __call__(self, coords):
        """Apply forward transformation.

        Parameters
        ----------
        coords : (N, 2) array_like
            source coordinates

        Returns
        -------
        coords : (N, 2) array
            Transformed coordinates.

        """
        coords = np.asarray(coords)
        x = coords[:, 0]
        y = coords[:, 1]
        u = len(self.params.ravel())
        # number of coefficients -> u = (order + 1) * (order + 2)
        order = int((-3 + math.sqrt(9 - 4 * (2 - u))) / 2)
        dst = np.zeros(coords.shape)

        pidx = 0
        for j in range(order + 1):
            for i in range(j + 1):
                dst[:, 0] += self.params[0, pidx] * x ** (j - i) * y**i
                dst[:, 1] += self.params[1, pidx] * x ** (j - i) * y**i
                pidx += 1

        return dst

    @classmethod
    def identity(cls, dimensionality=None):
        """Identity transform

        Parameters
        ----------
        dimensionality : {None, 2}, optional
            This transform only allows dimensionality of 2, where None
            corresponds to 2. The parameter exists for compatibility with other
            transforms.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        """
        return cls(params=None, dimensionality=dimensionality)

    @property
    def inverse(self):
        raise NotImplementedError(
            'There is no explicit way to do the inverse polynomial '
            'transformation. Instead, estimate the inverse transformation '
            'parameters by exchanging source and destination coordinates,'
            'then apply the forward transformation.'
        )

    @_deprecate_estimate
    def estimate(self, src, dst, order=2, weights=None):
        """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 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
            Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))

        These equations can be transformed to the following form::

            0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X
            0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - 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   = [[1 x y x**2 x*y y**2 ... 0 ...             0 -X]
                   [0 ...                 0 1 x y x**2 x*y y**2 -Y]
                    ...
                    ...
                  ]
            x.T = [a00 a10 a11 a20 a21 a22 ... ann
                   b00 b10 b11 b20 b21 b22 ... bnn 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.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        order : int, optional
            Polynomial order (number of coefficients is order + 1).
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        """
        return self._estimate(src, dst, order, weights) is None


TRANSFORMS = {
    'euclidean': EuclideanTransform,
    'similarity': SimilarityTransform,
    'affine': AffineTransform,
    'piecewise-affine': PiecewiseAffineTransform,
    'projective': ProjectiveTransform,
    'fundamental': FundamentalMatrixTransform,
    'essential': EssentialMatrixTransform,
    'polynomial': PolynomialTransform,
}


def estimate_transform(ttype, src, dst, *args, **kwargs):
    """Estimate 2D geometric transformation parameters.

    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
    ----------
    ttype : {'euclidean', similarity', 'affine', 'piecewise-affine', \
             'projective', 'polynomial'}
        Type of transform.
    kwargs : array_like or int
        Function parameters (src, dst, n, angle)::

            NAME / TTYPE        FUNCTION PARAMETERS
            'euclidean'         `src, `dst`
            'similarity'        `src, `dst`
            'affine'            `src, `dst`
            'piecewise-affine'  `src, `dst`
            'projective'        `src, `dst`
            'polynomial'        `src, `dst`, `order` (polynomial order,
                                                      default order is 2)

        Also see examples below.

    Returns
    -------
    tf : :class:`_GeometricTransform` or ``FailedEstimation``
        An instance of the requested transformation if the estimation
        Otherwise, we return a special ``FailedEstimation`` object to signal a
        failed estimation. Testing the truth value of the failed estimation
        object will return ``False``. E.g.

        .. code-block:: python

            tf = estimate_transform(...)
            if not tf:
                raise RuntimeError(f"Failed estimation: {tf}")

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    >>> # estimate transformation parameters
    >>> src = np.array([0, 0, 10, 10]).reshape((2, 2))
    >>> dst = np.array([12, 14, 1, -20]).reshape((2, 2))

    >>> tform = ski.transform.estimate_transform('similarity', src, dst)

    >>> np.allclose(tform.inverse(tform(src)), src)
    True

    >>> # warp image using the estimated transformation
    >>> image = ski.data.camera()

    >>> ski.transform.warp(image, inverse_map=tform.inverse) # doctest: +SKIP

    >>> # create transformation with explicit parameters
    >>> tform2 = ski.transform.SimilarityTransform(scale=1.1, rotation=1,
    ...     translation=(10, 20))

    >>> # unite transformations, applied in order from left to right
    >>> tform3 = tform + tform2
    >>> np.allclose(tform3(src), tform2(tform(src)))
    True

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((2, 2))
    >>> bad_tform = ski.transform.estimate_transform('similarity',
    ...                                              bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    """
    ttype = ttype.lower()
    if ttype not in TRANSFORMS:
        raise ValueError(f'the transformation type \'{ttype}\' is not implemented')

    return TRANSFORMS[ttype].from_estimate(src, dst, *args, **kwargs)


def matrix_transform(coords, matrix):
    """Apply 2D matrix transform.

    Parameters
    ----------
    coords : (N, 2) array_like
        x, y coordinates to transform
    matrix : (3, 3) array_like
        Homogeneous transformation matrix.

    Returns
    -------
    coords : (N, 2) array
        Transformed coordinates.

    """
    return ProjectiveTransform(matrix)(coords)