File size: 131,672 Bytes
b4d7ac8 |
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 |
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A collection of dictionary-based wrappers around the "vanilla" transforms for spatial operations
defined in :py:class:`monai.transforms.spatial.array`.
Class names are ended with 'd' to denote dictionary-based transforms.
"""
from __future__ import annotations
import warnings
from collections.abc import Hashable, Mapping, Sequence
from typing import Any, cast
import numpy as np
import torch
from monai.config import DtypeLike, KeysCollection, SequenceStr
from monai.config.type_definitions import NdarrayOrTensor
from monai.data.meta_obj import get_track_meta
from monai.data.meta_tensor import MetaTensor
from monai.networks.layers.simplelayers import GaussianFilter
from monai.transforms.croppad.array import CenterSpatialCrop
from monai.transforms.inverse import InvertibleTransform
from monai.transforms.spatial.array import (
Affine,
Flip,
GridDistortion,
GridPatch,
GridSplit,
Orientation,
Rand2DElastic,
Rand3DElastic,
RandAffine,
RandAxisFlip,
RandGridDistortion,
RandGridPatch,
RandRotate,
RandSimulateLowResolution,
RandZoom,
ResampleToMatch,
Resize,
Rotate,
Rotate90,
Spacing,
SpatialResample,
Zoom,
)
from monai.transforms.traits import MultiSampleTrait
from monai.transforms.transform import LazyTransform, MapTransform, RandomizableTransform
from monai.transforms.utils import create_grid
from monai.utils import (
GridSampleMode,
GridSamplePadMode,
InterpolateMode,
NumpyPadMode,
convert_to_tensor,
ensure_tuple,
ensure_tuple_rep,
fall_back_tuple,
)
from monai.utils.enums import TraceKeys
from monai.utils.module import optional_import
nib, _ = optional_import("nibabel")
__all__ = [
"SpatialResampled",
"ResampleToMatchd",
"Spacingd",
"Orientationd",
"Rotate90d",
"RandRotate90d",
"Resized",
"Affined",
"RandAffined",
"Rand2DElasticd",
"Rand3DElasticd",
"Flipd",
"RandFlipd",
"GridDistortiond",
"RandGridDistortiond",
"RandAxisFlipd",
"Rotated",
"RandRotated",
"Zoomd",
"RandZoomd",
"SpatialResampleD",
"SpatialResampleDict",
"SpacingD",
"SpacingDict",
"OrientationD",
"OrientationDict",
"Rotate90D",
"Rotate90Dict",
"RandRotate90D",
"RandRotate90Dict",
"ResizeD",
"ResizeDict",
"AffineD",
"AffineDict",
"RandAffineD",
"RandAffineDict",
"Rand2DElasticD",
"Rand2DElasticDict",
"Rand3DElasticD",
"Rand3DElasticDict",
"FlipD",
"FlipDict",
"RandFlipD",
"RandFlipDict",
"GridDistortionD",
"GridDistortionDict",
"RandGridDistortionD",
"RandGridDistortionDict",
"RandAxisFlipD",
"RandAxisFlipDict",
"RotateD",
"RotateDict",
"RandRotateD",
"RandRotateDict",
"ZoomD",
"ZoomDict",
"RandZoomD",
"RandZoomDict",
"GridSplitd",
"GridSplitD",
"GridSplitDict",
"GridPatchd",
"GridPatchD",
"GridPatchDict",
"RandGridPatchd",
"RandGridPatchD",
"RandGridPatchDict",
"RandSimulateLowResolutiond",
"RandSimulateLowResolutionD",
"RandSimulateLowResolutionDict",
]
class SpatialResampled(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.SpatialResample`.
This transform assumes the ``data`` dictionary has a key for the input
data's metadata and contains ``src_affine`` and ``dst_affine`` required by
`SpatialResample`. The key is formed by ``key_{meta_key_postfix}``. The
transform will swap ``src_affine`` and ``dst_affine`` affine (with potential data type
changes) in the dictionary so that ``src_affine`` always refers to the current
status of affine.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
See also:
:py:class:`monai.transforms.SpatialResample`
"""
backend = SpatialResample.backend
def __init__(
self,
keys: KeysCollection,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.BORDER,
align_corners: Sequence[bool] | bool = False,
dtype: Sequence[DtypeLike] | DtypeLike = np.float64,
dst_keys: KeysCollection | None = "dst_affine",
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"border"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
align_corners: Geometrically, we consider the pixels of the input as squares rather than points.
See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
It also can be a sequence of bool, each element corresponds to a key in ``keys``.
dtype: data type for resampling computation. Defaults to ``float64`` for best precision.
If None, use the data type of input data. To be compatible with other modules,
the output data type is always ``float32``.
It also can be a sequence of dtypes, each element corresponds to a key in ``keys``.
dst_keys: the key of the corresponding ``dst_affine`` in the metadata dictionary.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.sp_transform = SpatialResample(lazy=lazy)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
self.dst_keys = ensure_tuple_rep(dst_keys, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.sp_transform.lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
lazy_ = self.lazy if lazy is None else lazy
d: dict = dict(data)
for key, mode, padding_mode, align_corners, dtype, dst_key in self.key_iterator(
d, self.mode, self.padding_mode, self.align_corners, self.dtype, self.dst_keys
):
d[key] = self.sp_transform(
img=d[key],
dst_affine=d[dst_key],
spatial_size=None, # None means shape auto inferred
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
dtype=dtype,
lazy=lazy_,
)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.sp_transform.inverse(d[key])
return d
class ResampleToMatchd(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.ResampleToMatch`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = ResampleToMatch.backend
def __init__(
self,
keys: KeysCollection,
key_dst: str,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.BORDER,
align_corners: Sequence[bool] | bool = False,
dtype: Sequence[DtypeLike] | DtypeLike = np.float64,
allow_missing_keys: bool = False,
lazy: bool = False,
):
"""
Args:
keys: keys of the corresponding items to be transformed.
key_dst: key of image to resample to match.
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"border"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
align_corners: Geometrically, we consider the pixels of the input as squares rather than points.
See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample
It also can be a sequence of bool, each element corresponds to a key in ``keys``.
dtype: data type for resampling computation. Defaults to ``float64`` for best precision.
If None, use the data type of input data. To be compatible with other modules,
the output data type is always ``float32``.
It also can be a sequence of dtypes, each element corresponds to a key in ``keys``.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.key_dst = key_dst
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
self.resampler = ResampleToMatch(lazy=lazy)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.resampler.lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
lazy_ = self.lazy if lazy is None else lazy
d = dict(data)
for key, mode, padding_mode, align_corners, dtype in self.key_iterator(
d, self.mode, self.padding_mode, self.align_corners, self.dtype
):
d[key] = self.resampler(
img=d[key],
img_dst=d[self.key_dst],
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
dtype=dtype,
lazy=lazy_,
)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.resampler.inverse(d[key])
return d
class Spacingd(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Spacing`.
This transform assumes the ``data`` dictionary has a key for the input
data's metadata and contains `affine` field. The key is formed by ``key_{meta_key_postfix}``.
After resampling the input array, this transform will write the new affine
to the `affine` field of metadata which is formed by ``key_{meta_key_postfix}``.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
see also:
:py:class:`monai.transforms.Spacing`
"""
backend = Spacing.backend
def __init__(
self,
keys: KeysCollection,
pixdim: Sequence[float] | float,
diagonal: bool = False,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.BORDER,
align_corners: Sequence[bool] | bool = False,
dtype: Sequence[DtypeLike] | DtypeLike = np.float64,
scale_extent: bool = False,
recompute_affine: bool = False,
min_pixdim: Sequence[float] | float | None = None,
max_pixdim: Sequence[float] | float | None = None,
ensure_same_shape: bool = True,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
pixdim: output voxel spacing. if providing a single number, will use it for the first dimension.
items of the pixdim sequence map to the spatial dimensions of input image, if length
of pixdim sequence is longer than image spatial dimensions, will ignore the longer part,
if shorter, will pad with `1.0`.
if the components of the `pixdim` are non-positive values, the transform will use the
corresponding components of the original pixdim, which is computed from the `affine`
matrix of input image.
diagonal: whether to resample the input to have a diagonal affine matrix.
If True, the input data is resampled to the following affine::
np.diag((pixdim_0, pixdim_1, pixdim_2, 1))
This effectively resets the volume to the world coordinate system (RAS+ in nibabel).
The original orientation, rotation, shearing are not preserved.
If False, the axes orientation, orthogonal rotation and
translations components from the original affine will be
preserved in the target affine. This option will not flip/swap
axes against the original ones.
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"border"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
align_corners: Geometrically, we consider the pixels of the input as squares rather than points.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
It also can be a sequence of bool, each element corresponds to a key in ``keys``.
dtype: data type for resampling computation. Defaults to ``float64`` for best precision.
If None, use the data type of input data. To be compatible with other modules,
the output data type is always ``float32``.
It also can be a sequence of dtypes, each element corresponds to a key in ``keys``.
scale_extent: whether the scale is computed based on the spacing or the full extent of voxels,
default False. The option is ignored if output spatial size is specified when calling this transform.
See also: :py:func:`monai.data.utils.compute_shape_offset`. When this is True, `align_corners`
should be `True` because `compute_shape_offset` already provides the corner alignment shift/scaling.
recompute_affine: whether to recompute affine based on the output shape. The affine computed
analytically does not reflect the potential quantization errors in terms of the output shape.
Set this flag to True to recompute the output affine based on the actual pixdim. Default to ``False``.
min_pixdim: minimal input spacing to be resampled. If provided, input image with a larger spacing than this
value will be kept in its original spacing (not be resampled to `pixdim`). Set it to `None` to use the
value of `pixdim`. Default to `None`.
max_pixdim: maximal input spacing to be resampled. If provided, input image with a smaller spacing than this
value will be kept in its original spacing (not be resampled to `pixdim`). Set it to `None` to use the
value of `pixdim`. Default to `None`.
ensure_same_shape: when the inputs have the same spatial shape, and almost the same pixdim,
whether to ensure exactly the same output spatial shape. Default to True.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.spacing_transform = Spacing(
pixdim,
diagonal=diagonal,
recompute_affine=recompute_affine,
min_pixdim=min_pixdim,
max_pixdim=max_pixdim,
lazy=lazy,
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
self.scale_extent = ensure_tuple_rep(scale_extent, len(self.keys))
self.ensure_same_shape = ensure_same_shape
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.spacing_transform.lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d: dict = dict(data)
_init_shape, _pixdim, should_match = None, None, False
output_shape_k = None # tracking output shape
lazy_ = self.lazy if lazy is None else lazy
for key, mode, padding_mode, align_corners, dtype, scale_extent in self.key_iterator(
d, self.mode, self.padding_mode, self.align_corners, self.dtype, self.scale_extent
):
if self.ensure_same_shape and isinstance(d[key], MetaTensor):
if _init_shape is None and _pixdim is None:
_init_shape, _pixdim = d[key].peek_pending_shape(), d[key].pixdim
else:
should_match = np.allclose(_init_shape, d[key].peek_pending_shape()) and np.allclose(
_pixdim, d[key].pixdim, atol=1e-3
)
d[key] = self.spacing_transform(
data_array=d[key],
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
dtype=dtype,
scale_extent=scale_extent,
output_spatial_shape=output_shape_k if should_match else None,
lazy=lazy_,
)
if output_shape_k is None:
output_shape_k = d[key].peek_pending_shape() if isinstance(d[key], MetaTensor) else d[key].shape[1:]
return d
def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.spacing_transform.inverse(cast(torch.Tensor, d[key]))
return d
class Orientationd(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Orientation`.
This transform assumes the channel-first input format.
In the case of using this transform for normalizing the orientations of images,
it should be used before any anisotropic spatial transforms.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = Orientation.backend
def __init__(
self,
keys: KeysCollection,
axcodes: str | None = None,
as_closest_canonical: bool = False,
labels: Sequence[tuple[str, str]] | None = (("L", "R"), ("P", "A"), ("I", "S")),
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
axcodes: N elements sequence for spatial ND input's orientation.
e.g. axcodes='RAS' represents 3D orientation:
(Left, Right), (Posterior, Anterior), (Inferior, Superior).
default orientation labels options are: 'L' and 'R' for the first dimension,
'P' and 'A' for the second, 'I' and 'S' for the third.
as_closest_canonical: if True, load the image as closest to canonical axis format.
labels: optional, None or sequence of (2,) sequences
(2,) sequences are labels for (beginning, end) of output axis.
Defaults to ``(('L', 'R'), ('P', 'A'), ('I', 'S'))``.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
See Also:
`nibabel.orientations.ornt2axcodes`.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.ornt_transform = Orientation(
axcodes=axcodes, as_closest_canonical=as_closest_canonical, labels=labels, lazy=lazy
)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.ornt_transform.lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d: dict = dict(data)
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(d):
d[key] = self.ornt_transform(d[key], lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.ornt_transform.inverse(d[key])
return d
class Rotate90d(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Rotate90`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = Rotate90.backend
def __init__(
self,
keys: KeysCollection,
k: int = 1,
spatial_axes: tuple[int, int] = (0, 1),
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
k: number of times to rotate by 90 degrees.
spatial_axes: 2 int numbers, defines the plane to rotate with 2 spatial axes.
Default: (0, 1), this is the first two axis in spatial dimensions.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.rotator = Rotate90(k, spatial_axes, lazy=lazy)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.rotator.lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(d):
d[key] = self.rotator(d[key], lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.rotator.inverse(d[key])
return d
class RandRotate90d(RandomizableTransform, MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based version :py:class:`monai.transforms.RandRotate90`.
With probability `prob`, input arrays are rotated by 90 degrees
in the plane specified by `spatial_axes`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = Rotate90.backend
def __init__(
self,
keys: KeysCollection,
prob: float = 0.1,
max_k: int = 3,
spatial_axes: tuple[int, int] = (0, 1),
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
prob: probability of rotating.
(Default 0.1, with 10% probability it returns a rotated array.)
max_k: number of rotations will be sampled from `np.random.randint(max_k) + 1`.
(Default 3)
spatial_axes: 2 int numbers, defines the plane to rotate with 2 spatial axes.
Default: (0, 1), this is the first two axis in spatial dimensions.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
LazyTransform.__init__(self, lazy=lazy)
self.max_k = max_k
self.spatial_axes = spatial_axes
self._rand_k = 0
def randomize(self, data: Any | None = None) -> None:
self._rand_k = self.R.randint(self.max_k) + 1
super().randomize(None)
def __call__(
self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None
) -> Mapping[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
self.randomize()
d = dict(data)
# FIXME: here we didn't use array version `RandRotate90` transform as others, because we need
# to be compatible with the random status of some previous integration tests
lazy_ = self.lazy if lazy is None else lazy
rotator = Rotate90(self._rand_k, self.spatial_axes, lazy=lazy_)
for key in self.key_iterator(d):
d[key] = rotator(d[key]) if self._do_transform else convert_to_tensor(d[key], track_meta=get_track_meta())
self.push_transform(d[key], replace=True, lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
if not isinstance(d[key], MetaTensor):
continue
xform = self.pop_transform(d[key])
if xform[TraceKeys.DO_TRANSFORM]:
d[key] = Rotate90().inverse_transform(d[key], xform[TraceKeys.EXTRA_INFO])
return d
class Resized(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Resize`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: keys of the corresponding items to be transformed.
See also: :py:class:`monai.transforms.compose.MapTransform`
spatial_size: expected shape of spatial dimensions after resize operation.
if some components of the `spatial_size` are non-positive values, the transform will use the
corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted
to `(32, 64)` if the second spatial dimension size of img is `64`.
size_mode: should be "all" or "longest", if "all", will use `spatial_size` for all the spatial dims,
if "longest", rescale the image so that only the longest side is equal to specified `spatial_size`,
which must be an int number in this case, keeping the aspect ratio of the initial image, refer to:
https://albumentations.ai/docs/api_reference/augmentations/geometric/resize/
#albumentations.augmentations.geometric.resize.LongestMaxSize.
mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}
The interpolation mode. Defaults to ``"area"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
align_corners: This only has an effect when mode is
'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of bool or None, each element corresponds to a key in ``keys``.
anti_aliasing: bool
Whether to apply a Gaussian filter to smooth the image prior
to downsampling. It is crucial to filter when downsampling
the image to avoid aliasing artifacts. See also ``skimage.transform.resize``
anti_aliasing_sigma: {float, tuple of floats}, optional
Standard deviation for Gaussian filtering used when anti-aliasing.
By default, this value is chosen as (s - 1) / 2 where s is the
downsampling factor, where s > 1. For the up-size case, s < 1, no
anti-aliasing is performed prior to rescaling.
dtype: data type for resampling computation. Defaults to ``float32``.
If None, use the data type of input data.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
backend = Resize.backend
def __init__(
self,
keys: KeysCollection,
spatial_size: Sequence[int] | int,
size_mode: str = "all",
mode: SequenceStr = InterpolateMode.AREA,
align_corners: Sequence[bool | None] | bool | None = None,
anti_aliasing: Sequence[bool] | bool = False,
anti_aliasing_sigma: Sequence[Sequence[float] | float | None] | Sequence[float] | float | None = None,
dtype: Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtype = np.float32,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
self.anti_aliasing = ensure_tuple_rep(anti_aliasing, len(self.keys))
self.anti_aliasing_sigma = ensure_tuple_rep(anti_aliasing_sigma, len(self.keys))
self.resizer = Resize(spatial_size=spatial_size, size_mode=size_mode, lazy=lazy)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.resizer.lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
lazy_ = self.lazy if lazy is None else lazy
for key, mode, align_corners, anti_aliasing, anti_aliasing_sigma, dtype in self.key_iterator(
d, self.mode, self.align_corners, self.anti_aliasing, self.anti_aliasing_sigma, self.dtype
):
d[key] = self.resizer(
d[key],
mode=mode,
align_corners=align_corners,
anti_aliasing=anti_aliasing,
anti_aliasing_sigma=anti_aliasing_sigma,
dtype=dtype,
lazy=lazy_,
)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.resizer.inverse(d[key])
return d
class Affined(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Affine`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = Affine.backend
def __init__(
self,
keys: KeysCollection,
rotate_params: Sequence[float] | float | None = None,
shear_params: Sequence[float] | float | None = None,
translate_params: Sequence[float] | float | None = None,
scale_params: Sequence[float] | float | None = None,
affine: NdarrayOrTensor | None = None,
spatial_size: Sequence[int] | int | None = None,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.REFLECTION,
device: torch.device | None = None,
dtype: DtypeLike | torch.dtype = np.float32,
align_corners: bool = False,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
rotate_params: a rotation angle in radians, a scalar for 2D image, a tuple of 3 floats for 3D.
Defaults to no rotation.
shear_params: shearing factors for affine matrix, take a 3D affine as example::
[
[1.0, params[0], params[1], 0.0],
[params[2], 1.0, params[3], 0.0],
[params[4], params[5], 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
a tuple of 2 floats for 2D, a tuple of 6 floats for 3D. Defaults to no shearing.
translate_params: a tuple of 2 floats for 2D, a tuple of 3 floats for 3D. Translation is in
pixel/voxel relative to the center of the input image. Defaults to no translation.
scale_params: scale factor for every spatial dims. a tuple of 2 floats for 2D,
a tuple of 3 floats for 3D. Defaults to `1.0`.
affine: if applied, ignore the params (`rotate_params`, etc.) and use the
supplied matrix. Should be square with each side = num of image spatial
dimensions + 1.
spatial_size: output image spatial size.
if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1,
the transform will use the spatial size of `img`.
if some components of the `spatial_size` are non-positive values, the transform will use the
corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted
to `(32, 64)` if the second spatial dimension size of img is `64`.
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"reflection"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
device: device on which the tensor will be allocated.
dtype: data type for resampling computation. Defaults to ``float32``.
If ``None``, use the data type of input data. To be compatible with other modules,
the output data type is always `float32`.
align_corners: Defaults to False.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
See also:
- :py:class:`monai.transforms.compose.MapTransform`
- :py:class:`RandAffineGrid` for the random affine parameters configurations.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.affine = Affine(
rotate_params=rotate_params,
shear_params=shear_params,
translate_params=translate_params,
scale_params=scale_params,
affine=affine,
spatial_size=spatial_size,
device=device,
dtype=dtype, # type: ignore
align_corners=align_corners,
lazy=lazy,
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.affine.lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
lazy_ = self.lazy if lazy is None else lazy
d = dict(data)
for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode):
d[key], _ = self.affine(d[key], mode=mode, padding_mode=padding_mode, lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.affine.inverse(d[key])
return d
class RandAffined(RandomizableTransform, MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.RandAffine`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
"""
backend = RandAffine.backend
def __init__(
self,
keys: KeysCollection,
spatial_size: Sequence[int] | int | None = None,
prob: float = 0.1,
rotate_range: Sequence[tuple[float, float] | float] | float | None = None,
shear_range: Sequence[tuple[float, float] | float] | float | None = None,
translate_range: Sequence[tuple[float, float] | float] | float | None = None,
scale_range: Sequence[tuple[float, float] | float] | float | None = None,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.REFLECTION,
cache_grid: bool = False,
device: torch.device | None = None,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
spatial_size: output image spatial size.
if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1,
the transform will use the spatial size of `img`.
if some components of the `spatial_size` are non-positive values, the transform will use the
corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted
to `(32, 64)` if the second spatial dimension size of img is `64`.
prob: probability of returning a randomized affine grid.
defaults to 0.1, with 10% chance returns a randomized grid.
rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then
`uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter
for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used.
This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be
in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]`
for dim0 and nothing for the remaining dimensions.
shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select
shearing factors(a tuple of 2 floats for 2D, a tuple of 6 floats for 3D) for affine matrix,
take a 3D affine as example::
[
[1.0, params[0], params[1], 0.0],
[params[2], 1.0, params[3], 0.0],
[params[4], params[5], 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
translate_range: translate range with format matching `rotate_range`, it defines the range to randomly
select pixel/voxel to translate for every spatial dims.
scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select
the scale factor to translate for every spatial dims. A value of 1.0 is added to the result.
This allows 0 to correspond to no change (i.e., a scaling of 1.0).
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"reflection"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
cache_grid: whether to cache the identity sampling grid.
If the spatial size is not dynamically defined by input image, enabling this option could
accelerate the transform.
device: device on which the tensor will be allocated.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
See also:
- :py:class:`monai.transforms.compose.MapTransform`
- :py:class:`RandAffineGrid` for the random affine parameters configurations.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
LazyTransform.__init__(self, lazy=lazy)
self.rand_affine = RandAffine(
prob=1.0, # because probability handled in this class
rotate_range=rotate_range,
shear_range=shear_range,
translate_range=translate_range,
scale_range=scale_range,
spatial_size=spatial_size,
cache_grid=cache_grid,
device=device,
lazy=lazy,
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool) -> None:
self._lazy = val
self.rand_affine.lazy = val
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandAffined:
self.rand_affine.set_random_state(seed, state)
super().set_random_state(seed, state)
return self
def __call__(
self, data: Mapping[Hashable, NdarrayOrTensor], lazy: bool | None = None
) -> dict[Hashable, NdarrayOrTensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
first_key: Hashable = self.first_key(d)
if first_key == ():
out: dict[Hashable, NdarrayOrTensor] = convert_to_tensor(d, track_meta=get_track_meta())
return out
self.randomize(None)
# all the keys share the same random Affine factor
self.rand_affine.randomize()
item = d[first_key]
spatial_size = item.peek_pending_shape() if isinstance(item, MetaTensor) else item.shape[1:]
lazy_ = self.lazy if lazy is None else lazy
sp_size = fall_back_tuple(self.rand_affine.spatial_size, spatial_size)
# change image size or do random transform
do_resampling = self._do_transform or (sp_size != ensure_tuple(spatial_size))
# converting affine to tensor because the resampler currently only support torch backend
grid = None
if do_resampling: # need to prepare grid
grid = self.rand_affine.get_identity_grid(sp_size, lazy=lazy_)
if self._do_transform: # add some random factors
grid = self.rand_affine.rand_affine_grid(sp_size, grid=grid, lazy=lazy_)
grid = 0 if grid is None else grid # always provide a grid to self.rand_affine
for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode):
# do the transform
if do_resampling:
d[key] = self.rand_affine(d[key], None, mode, padding_mode, True, grid, lazy=lazy_) # type: ignore
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta(), dtype=torch.float32)
self._do_transform = do_resampling # TODO: unify self._do_transform and do_resampling
self.push_transform(d[key], replace=True, lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
tr = self.pop_transform(d[key])
if TraceKeys.EXTRA_INFO not in tr[TraceKeys.EXTRA_INFO]:
continue
do_resampling = tr[TraceKeys.EXTRA_INFO][TraceKeys.EXTRA_INFO]["do_resampling"]
if do_resampling:
d[key].applied_operations.append(tr[TraceKeys.EXTRA_INFO]) # type: ignore
d[key] = self.rand_affine.inverse(d[key]) # type: ignore
return d
class Rand2DElasticd(RandomizableTransform, MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Rand2DElastic`.
"""
backend = Rand2DElastic.backend
def __init__(
self,
keys: KeysCollection,
spacing: tuple[float, float] | float,
magnitude_range: tuple[float, float],
spatial_size: tuple[int, int] | int | None = None,
prob: float = 0.1,
rotate_range: Sequence[tuple[float, float] | float] | float | None = None,
shear_range: Sequence[tuple[float, float] | float] | float | None = None,
translate_range: Sequence[tuple[float, float] | float] | float | None = None,
scale_range: Sequence[tuple[float, float] | float] | float | None = None,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.REFLECTION,
device: torch.device | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
spacing: distance in between the control points.
magnitude_range: 2 int numbers, the random offsets will be generated from
``uniform[magnitude[0], magnitude[1])``.
spatial_size: specifying output image spatial size [h, w].
if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1,
the transform will use the spatial size of `img`.
if some components of the `spatial_size` are non-positive values, the transform will use the
corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted
to `(32, 64)` if the second spatial dimension size of img is `64`.
prob: probability of returning a randomized affine grid.
defaults to 0.1, with 10% chance returns a randomized grid,
otherwise returns a ``spatial_size`` centered area extracted from the input image.
rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then
`uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter
for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used.
This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be
in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]`
for dim0 and nothing for the remaining dimensions.
shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select
shearing factors(a tuple of 2 floats for 2D) for affine matrix, take a 2D affine as example::
[
[1.0, params[0], 0.0],
[params[1], 1.0, 0.0],
[0.0, 0.0, 1.0],
]
translate_range: translate range with format matching `rotate_range`, it defines the range to randomly
select pixel to translate for every spatial dims.
scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select
the scale factor to translate for every spatial dims. A value of 1.0 is added to the result.
This allows 0 to correspond to no change (i.e., a scaling of 1.0).
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"reflection"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
device: device on which the tensor will be allocated.
allow_missing_keys: don't raise exception if key is missing.
See also:
- :py:class:`RandAffineGrid` for the random affine parameters configurations.
- :py:class:`Affine` for the affine transformation parameters configurations.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
self.rand_2d_elastic = Rand2DElastic(
spacing=spacing,
magnitude_range=magnitude_range,
prob=1.0, # because probability controlled by this class
rotate_range=rotate_range,
shear_range=shear_range,
translate_range=translate_range,
scale_range=scale_range,
spatial_size=spatial_size,
device=device,
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> Rand2DElasticd:
self.rand_2d_elastic.set_random_state(seed, state)
super().set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
first_key: Hashable = self.first_key(d)
if first_key == ():
out: dict[Hashable, NdarrayOrTensor] = convert_to_tensor(d, track_meta=get_track_meta())
return out
self.randomize(None)
device = self.rand_2d_elastic.device
if device is None and isinstance(d[first_key], torch.Tensor):
device = d[first_key].device # type: ignore
self.rand_2d_elastic.set_device(device)
if isinstance(d[first_key], MetaTensor) and d[first_key].pending_operations: # type: ignore
warnings.warn(f"data['{first_key}'] has pending operations, transform may return incorrect results.")
sp_size = fall_back_tuple(self.rand_2d_elastic.spatial_size, d[first_key].shape[1:])
# all the keys share the same random elastic factor
self.rand_2d_elastic.randomize(sp_size)
if self._do_transform:
grid = self.rand_2d_elastic.deform_grid(spatial_size=sp_size)
grid = self.rand_2d_elastic.rand_affine_grid(grid=grid)
grid = torch.nn.functional.interpolate(
recompute_scale_factor=True,
input=grid.unsqueeze(0),
scale_factor=ensure_tuple_rep(self.rand_2d_elastic.deform_grid.spacing, 2),
mode=InterpolateMode.BICUBIC.value,
align_corners=False,
)
grid = CenterSpatialCrop(roi_size=sp_size)(grid[0])
else:
grid = cast(torch.Tensor, create_grid(spatial_size=sp_size, device=device, backend="torch"))
for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode):
d[key] = self.rand_2d_elastic.resampler(d[key], grid, mode=mode, padding_mode=padding_mode) # type: ignore
return d
class Rand3DElasticd(RandomizableTransform, MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Rand3DElastic`.
"""
backend = Rand3DElastic.backend
def __init__(
self,
keys: KeysCollection,
sigma_range: tuple[float, float],
magnitude_range: tuple[float, float],
spatial_size: tuple[int, int, int] | int | None = None,
prob: float = 0.1,
rotate_range: Sequence[tuple[float, float] | float] | float | None = None,
shear_range: Sequence[tuple[float, float] | float] | float | None = None,
translate_range: Sequence[tuple[float, float] | float] | float | None = None,
scale_range: Sequence[tuple[float, float] | float] | float | None = None,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.REFLECTION,
device: torch.device | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
sigma_range: a Gaussian kernel with standard deviation sampled from
``uniform[sigma_range[0], sigma_range[1])`` will be used to smooth the random offset grid.
magnitude_range: the random offsets on the grid will be generated from
``uniform[magnitude[0], magnitude[1])``.
spatial_size: specifying output image spatial size [h, w, d].
if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1,
the transform will use the spatial size of `img`.
if some components of the `spatial_size` are non-positive values, the transform will use the
corresponding components of img size. For example, `spatial_size=(32, 32, -1)` will be adapted
to `(32, 32, 64)` if the third spatial dimension size of img is `64`.
prob: probability of returning a randomized affine grid.
defaults to 0.1, with 10% chance returns a randomized grid,
otherwise returns a ``spatial_size`` centered area extracted from the input image.
rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then
`uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter
for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used.
This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be
in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]`
for dim0 and nothing for the remaining dimensions.
shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select
shearing factors(a tuple of 6 floats for 3D) for affine matrix, take a 3D affine as example::
[
[1.0, params[0], params[1], 0.0],
[params[2], 1.0, params[3], 0.0],
[params[4], params[5], 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
translate_range: translate range with format matching `rotate_range`, it defines the range to randomly
select voxel to translate for every spatial dims.
scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select
the scale factor to translate for every spatial dims. A value of 1.0 is added to the result.
This allows 0 to correspond to no change (i.e., a scaling of 1.0).
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"reflection"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
device: device on which the tensor will be allocated.
allow_missing_keys: don't raise exception if key is missing.
See also:
- :py:class:`RandAffineGrid` for the random affine parameters configurations.
- :py:class:`Affine` for the affine transformation parameters configurations.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
self.rand_3d_elastic = Rand3DElastic(
sigma_range=sigma_range,
magnitude_range=magnitude_range,
prob=1.0, # because probability controlled by this class
rotate_range=rotate_range,
shear_range=shear_range,
translate_range=translate_range,
scale_range=scale_range,
spatial_size=spatial_size,
device=device,
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> Rand3DElasticd:
self.rand_3d_elastic.set_random_state(seed, state)
super().set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
first_key: Hashable = self.first_key(d)
if first_key == ():
out: dict[Hashable, torch.Tensor] = convert_to_tensor(d, track_meta=get_track_meta())
return out
self.randomize(None)
if isinstance(d[first_key], MetaTensor) and d[first_key].pending_operations: # type: ignore
warnings.warn(f"data['{first_key}'] has pending operations, transform may return incorrect results.")
sp_size = fall_back_tuple(self.rand_3d_elastic.spatial_size, d[first_key].shape[1:])
# all the keys share the same random elastic factor
self.rand_3d_elastic.randomize(sp_size)
device = self.rand_3d_elastic.device
if device is None and isinstance(d[first_key], torch.Tensor):
device = d[first_key].device
self.rand_3d_elastic.set_device(device)
grid = create_grid(spatial_size=sp_size, device=device, backend="torch")
if self._do_transform:
gaussian = GaussianFilter(spatial_dims=3, sigma=self.rand_3d_elastic.sigma, truncated=3.0).to(device)
offset = torch.as_tensor(self.rand_3d_elastic.rand_offset, device=device).unsqueeze(0)
grid[:3] += gaussian(offset)[0] * self.rand_3d_elastic.magnitude
grid = self.rand_3d_elastic.rand_affine_grid(grid=grid)
for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode):
d[key] = self.rand_3d_elastic.resampler(d[key], grid, mode=mode, padding_mode=padding_mode) # type: ignore
return d
class Flipd(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Flip`.
See `numpy.flip` for additional details.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: Keys to pick data for transformation.
spatial_axis: Spatial axes along which to flip over. Default is None.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
backend = Flip.backend
def __init__(
self,
keys: KeysCollection,
spatial_axis: Sequence[int] | int | None = None,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.flipper = Flip(spatial_axis=spatial_axis)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool):
self.flipper.lazy = val
self._lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(d):
d[key] = self.flipper(d[key], lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.flipper.inverse(d[key])
return d
class RandFlipd(RandomizableTransform, MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based version :py:class:`monai.transforms.RandFlip`.
See `numpy.flip` for additional details.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: Keys to pick data for transformation.
prob: Probability of flipping.
spatial_axis: Spatial axes along which to flip over. Default is None.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
backend = Flip.backend
def __init__(
self,
keys: KeysCollection,
prob: float = 0.1,
spatial_axis: Sequence[int] | int | None = None,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
LazyTransform.__init__(self, lazy=lazy)
self.flipper = Flip(spatial_axis=spatial_axis, lazy=lazy)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool):
self.flipper.lazy = val
self._lazy = val
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandFlipd:
super().set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
self.randomize(None)
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(d):
if self._do_transform:
d[key] = self.flipper(d[key], lazy=lazy_)
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta())
self.push_transform(d[key], replace=True, lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
xform = self.pop_transform(d[key])
if not xform[TraceKeys.DO_TRANSFORM]:
continue
with self.flipper.trace_transform(False):
d[key] = self.flipper(d[key])
return d
class RandAxisFlipd(RandomizableTransform, MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based version :py:class:`monai.transforms.RandAxisFlip`.
See `numpy.flip` for additional details.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: Keys to pick data for transformation.
prob: Probability of flipping.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
backend = RandAxisFlip.backend
def __init__(
self, keys: KeysCollection, prob: float = 0.1, allow_missing_keys: bool = False, lazy: bool = False
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
LazyTransform.__init__(self, lazy=lazy)
self.flipper = RandAxisFlip(prob=1.0, lazy=lazy)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool):
self.flipper.lazy = val
self._lazy = val
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandAxisFlipd:
super().set_random_state(seed, state)
self.flipper.set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
first_key: Hashable = self.first_key(d)
if first_key == ():
return d
self.randomize(None)
# all the keys share the same random selected axis
self.flipper.randomize(d[first_key])
lazy_ = self.lazy if lazy is None else lazy
for key in self.key_iterator(d):
if self._do_transform:
d[key] = self.flipper(d[key], randomize=False, lazy=lazy_)
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta())
self.push_transform(d[key], replace=True, lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
xform = self.pop_transform(d[key])
if xform[TraceKeys.DO_TRANSFORM]:
d[key].applied_operations.append(xform[TraceKeys.EXTRA_INFO]) # type: ignore
d[key] = self.flipper.inverse(d[key])
return d
class Rotated(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Rotate`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: Keys to pick data for transformation.
angle: Rotation angle(s) in radians.
keep_size: If it is False, the output shape is adapted so that the
input array is contained completely in the output.
If it is True, the output shape is the same as the input. Default is True.
mode: {``"bilinear"``, ``"nearest"``}
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"border"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
align_corners: Defaults to False.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
It also can be a sequence of bool, each element corresponds to a key in ``keys``.
dtype: data type for resampling computation. Defaults to ``float32``.
If None, use the data type of input data. To be compatible with other modules,
the output data type is always ``float32``.
It also can be a sequence of dtype or None, each element corresponds to a key in ``keys``.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
backend = Rotate.backend
def __init__(
self,
keys: KeysCollection,
angle: Sequence[float] | float,
keep_size: bool = True,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.BORDER,
align_corners: Sequence[bool] | bool = False,
dtype: Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtype = np.float32,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.rotator = Rotate(angle=angle, keep_size=keep_size, lazy=lazy)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool):
self.rotator.lazy = val
self._lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
lazy_ = self.lazy if lazy is None else lazy
for key, mode, padding_mode, align_corners, dtype in self.key_iterator(
d, self.mode, self.padding_mode, self.align_corners, self.dtype
):
d[key] = self.rotator(
d[key], mode=mode, padding_mode=padding_mode, align_corners=align_corners, dtype=dtype, lazy=lazy_
)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.rotator.inverse(d[key])
return d
class RandRotated(RandomizableTransform, MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based version :py:class:`monai.transforms.RandRotate`
Randomly rotates the input arrays.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: Keys to pick data for transformation.
range_x: Range of rotation angle in radians in the plane defined by the first and second axes.
If single number, angle is uniformly sampled from (-range_x, range_x).
range_y: Range of rotation angle in radians in the plane defined by the first and third axes.
If single number, angle is uniformly sampled from (-range_y, range_y). only work for 3D data.
range_z: Range of rotation angle in radians in the plane defined by the second and third axes.
If single number, angle is uniformly sampled from (-range_z, range_z). only work for 3D data.
prob: Probability of rotation.
keep_size: If it is False, the output shape is adapted so that the
input array is contained completely in the output.
If it is True, the output shape is the same as the input. Default is True.
mode: {``"bilinear"``, ``"nearest"``}
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"border"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
align_corners: Defaults to False.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of bool, each element corresponds to a key in ``keys``.
dtype: data type for resampling computation. Defaults to ``float64`` for best precision.
If None, use the data type of input data. To be compatible with other modules,
the output data type is always ``float32``.
It also can be a sequence of dtype or None, each element corresponds to a key in ``keys``.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
"""
backend = RandRotate.backend
def __init__(
self,
keys: KeysCollection,
range_x: tuple[float, float] | float = 0.0,
range_y: tuple[float, float] | float = 0.0,
range_z: tuple[float, float] | float = 0.0,
prob: float = 0.1,
keep_size: bool = True,
mode: SequenceStr = GridSampleMode.BILINEAR,
padding_mode: SequenceStr = GridSamplePadMode.BORDER,
align_corners: Sequence[bool] | bool = False,
dtype: Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtype = np.float32,
allow_missing_keys: bool = False,
lazy: bool = False,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
LazyTransform.__init__(self, lazy=lazy)
self.rand_rotate = RandRotate(
range_x=range_x, range_y=range_y, range_z=range_z, prob=1.0, keep_size=keep_size, lazy=lazy
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool):
self.rand_rotate.lazy = val
self._lazy = val
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandRotated:
super().set_random_state(seed, state)
self.rand_rotate.set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
self.randomize(None)
# all the keys share the same random rotate angle
self.rand_rotate.randomize()
lazy_ = self.lazy if lazy is None else lazy
for key, mode, padding_mode, align_corners, dtype in self.key_iterator(
d, self.mode, self.padding_mode, self.align_corners, self.dtype
):
if self._do_transform:
d[key] = self.rand_rotate(
d[key],
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
dtype=dtype,
randomize=False,
lazy=lazy_,
)
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta(), dtype=torch.float32)
self.push_transform(d[key], replace=True, lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
xform = self.pop_transform(d[key])
if xform[TraceKeys.DO_TRANSFORM]:
d[key].applied_operations.append(xform[TraceKeys.EXTRA_INFO]) # type: ignore
d[key] = self.rand_rotate.inverse(d[key])
return d
class Zoomd(MapTransform, InvertibleTransform, LazyTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.Zoom`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: Keys to pick data for transformation.
zoom: The zoom factor along the spatial axes.
If a float, zoom is the same for each spatial axis.
If a sequence, zoom should contain one value for each spatial axis.
mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}
The interpolation mode. Defaults to ``"area"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``,
``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``}
available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}.
One of the listed string values or a user supplied function. Defaults to ``"edge"``.
The mode to pad data after zooming.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
align_corners: This only has an effect when mode is
'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of bool or None, each element corresponds to a key in ``keys``.
dtype: data type for resampling computation. Defaults to ``float32``.
If None, use the data type of input data.
keep_size: Should keep original size (pad if needed), default is True.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
kwargs: other arguments for the `np.pad` or `torch.pad` function.
note that `np.pad` treats channel dimension as the first dimension.
"""
backend = Zoom.backend
def __init__(
self,
keys: KeysCollection,
zoom: Sequence[float] | float,
mode: SequenceStr = InterpolateMode.AREA,
padding_mode: SequenceStr = NumpyPadMode.EDGE,
align_corners: Sequence[bool | None] | bool | None = None,
dtype: Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtype = np.float32,
keep_size: bool = True,
allow_missing_keys: bool = False,
lazy: bool = False,
**kwargs,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
LazyTransform.__init__(self, lazy=lazy)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
self.zoomer = Zoom(zoom=zoom, keep_size=keep_size, lazy=lazy, **kwargs)
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool):
self.zoomer.lazy = val
self._lazy = val
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
lazy_ = self.lazy if lazy is None else lazy
for key, mode, padding_mode, align_corners, dtype in self.key_iterator(
d, self.mode, self.padding_mode, self.align_corners, self.dtype
):
d[key] = self.zoomer(
d[key], mode=mode, padding_mode=padding_mode, align_corners=align_corners, dtype=dtype, lazy=lazy_
)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.zoomer.inverse(d[key])
return d
class RandZoomd(RandomizableTransform, MapTransform, InvertibleTransform, LazyTransform):
"""
Dict-based version :py:class:`monai.transforms.RandZoom`.
This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
for more information.
Args:
keys: Keys to pick data for transformation.
prob: Probability of zooming.
min_zoom: Min zoom factor. Can be float or sequence same size as image.
If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims
to keep the original spatial shape ratio.
If a sequence, min_zoom should contain one value for each spatial axis.
If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio.
max_zoom: Max zoom factor. Can be float or sequence same size as image.
If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims
to keep the original spatial shape ratio.
If a sequence, max_zoom should contain one value for each spatial axis.
If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio.
mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``}
The interpolation mode. Defaults to ``"area"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of string, each element corresponds to a key in ``keys``.
padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``,
``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``}
available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}.
One of the listed string values or a user supplied function. Defaults to ``"edge"``.
The mode to pad data after zooming.
See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
align_corners: This only has an effect when mode is
'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
It also can be a sequence of bool or None, each element corresponds to a key in ``keys``.
dtype: data type for resampling computation. Defaults to ``float32``.
If None, use the data type of input data.
keep_size: Should keep original size (pad if needed), default is True.
allow_missing_keys: don't raise exception if key is missing.
lazy: a flag to indicate whether this transform should execute lazily or not.
Defaults to False
kwargs: other args for `np.pad` API, note that `np.pad` treats channel dimension as the first dimension.
more details: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
"""
backend = RandZoom.backend
def __init__(
self,
keys: KeysCollection,
prob: float = 0.1,
min_zoom: Sequence[float] | float = 0.9,
max_zoom: Sequence[float] | float = 1.1,
mode: SequenceStr = InterpolateMode.AREA,
padding_mode: SequenceStr = NumpyPadMode.EDGE,
align_corners: Sequence[bool | None] | bool | None = None,
dtype: Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtype = np.float32,
keep_size: bool = True,
allow_missing_keys: bool = False,
lazy: bool = False,
**kwargs,
) -> None:
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
LazyTransform.__init__(self, lazy=lazy)
self.rand_zoom = RandZoom(
prob=1.0, min_zoom=min_zoom, max_zoom=max_zoom, keep_size=keep_size, lazy=lazy, **kwargs
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
self.dtype = ensure_tuple_rep(dtype, len(self.keys))
@LazyTransform.lazy.setter # type: ignore
def lazy(self, val: bool):
self.rand_zoom.lazy = val
self._lazy = val
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandZoomd:
super().set_random_state(seed, state)
self.rand_zoom.set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor], lazy: bool | None = None) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
lazy: a flag to indicate whether this transform should execute lazily or not
during this call. Setting this to False or True overrides the ``lazy`` flag set
during initialization for this call. Defaults to None.
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
first_key: Hashable = self.first_key(d)
if first_key == ():
out: dict[Hashable, torch.Tensor] = convert_to_tensor(d, track_meta=get_track_meta())
return out
self.randomize(None)
# all the keys share the same random zoom factor
self.rand_zoom.randomize(d[first_key])
lazy_ = self.lazy if lazy is None else lazy
for key, mode, padding_mode, align_corners, dtype in self.key_iterator(
d, self.mode, self.padding_mode, self.align_corners, self.dtype
):
if self._do_transform:
d[key] = self.rand_zoom(
d[key],
mode=mode,
padding_mode=padding_mode,
align_corners=align_corners,
dtype=dtype,
randomize=False,
lazy=lazy_,
)
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta(), dtype=torch.float32)
self.push_transform(d[key], replace=True, lazy=lazy_)
return d
def inverse(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
d = dict(data)
for key in self.key_iterator(d):
xform = self.pop_transform(d[key])
if xform[TraceKeys.DO_TRANSFORM]:
d[key].applied_operations.append(xform[TraceKeys.EXTRA_INFO]) # type: ignore
d[key] = self.rand_zoom.inverse(d[key])
return d
class GridDistortiond(MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.GridDistortion`.
"""
backend = GridDistortion.backend
def __init__(
self,
keys: KeysCollection,
num_cells: tuple[int] | int,
distort_steps: list[tuple],
mode: str = GridSampleMode.BILINEAR,
padding_mode: str = GridSamplePadMode.BORDER,
device: torch.device | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
num_cells: number of grid cells on each dimension.
distort_steps: This argument is a list of tuples, where each tuple contains the distort steps of the
corresponding dimensions (in the order of H, W[, D]). The length of each tuple equals to `num_cells + 1`.
Each value in the tuple represents the distort step of the related cell.
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"border"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
device: device on which the tensor will be allocated.
allow_missing_keys: don't raise exception if key is missing.
"""
super().__init__(keys, allow_missing_keys)
self.grid_distortion = GridDistortion(num_cells=num_cells, distort_steps=distort_steps, device=device)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode):
d[key] = self.grid_distortion(d[key], mode=mode, padding_mode=padding_mode)
return d
class RandGridDistortiond(RandomizableTransform, MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.RandGridDistortion`.
"""
backend = RandGridDistortion.backend
def __init__(
self,
keys: KeysCollection,
num_cells: tuple[int] | int = 5,
prob: float = 0.1,
distort_limit: tuple[float, float] | float = (-0.03, 0.03),
mode: str = GridSampleMode.BILINEAR,
padding_mode: str = GridSamplePadMode.BORDER,
device: torch.device | None = None,
allow_missing_keys: bool = False,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
num_cells: number of grid cells on each dimension.
prob: probability of returning a randomized grid distortion transform. Defaults to 0.1.
distort_limit: range to randomly distort.
If single number, distort_limit is picked from (-distort_limit, distort_limit).
Defaults to (-0.03, 0.03).
mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers).
Interpolation mode to calculate output values. Defaults to ``"bilinear"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used
and the value represents the order of the spline interpolation.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``}
Padding mode for outside grid values. Defaults to ``"border"``.
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html
When `mode` is an integer, using numpy/cupy backends, this argument accepts
{'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}.
See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html
It also can be a sequence, each element corresponds to a key in ``keys``.
device: device on which the tensor will be allocated.
allow_missing_keys: don't raise exception if key is missing.
"""
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
self.rand_grid_distortion = RandGridDistortion(
num_cells=num_cells, prob=1.0, distort_limit=distort_limit, device=device
)
self.mode = ensure_tuple_rep(mode, len(self.keys))
self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
def set_random_state(
self, seed: int | None = None, state: np.random.RandomState | None = None
) -> RandGridDistortiond:
super().set_random_state(seed, state)
self.rand_grid_distortion.set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, torch.Tensor]) -> dict[Hashable, torch.Tensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
self.randomize(None)
if not self._do_transform:
out: dict[Hashable, torch.Tensor] = convert_to_tensor(d, track_meta=get_track_meta())
return out
first_key: Hashable = self.first_key(d)
if first_key == ():
out = convert_to_tensor(d, track_meta=get_track_meta())
return out
if isinstance(d[first_key], MetaTensor) and d[first_key].pending_operations: # type: ignore
warnings.warn(f"data['{first_key}'] has pending operations, transform may return incorrect results.")
self.rand_grid_distortion.randomize(d[first_key].shape[1:])
for key, mode, padding_mode in self.key_iterator(d, self.mode, self.padding_mode):
d[key] = self.rand_grid_distortion(d[key], mode=mode, padding_mode=padding_mode, randomize=False)
return d
class GridSplitd(MapTransform, MultiSampleTrait):
"""
Split the image into patches based on the provided grid in 2D.
Args:
keys: keys of the corresponding items to be transformed.
grid: a tuple define the shape of the grid upon which the image is split. Defaults to (2, 2)
size: a tuple or an integer that defines the output patch sizes,
or a dictionary that define it separately for each key, like {"image": 3, "mask", (2, 2)}.
If it's an integer, the value will be repeated for each dimension.
The default is None, where the patch size will be inferred from the grid shape.
allow_missing_keys: don't raise exception if key is missing.
Note: This transform currently support only image with two spatial dimensions.
"""
backend = GridSplit.backend
def __init__(
self,
keys: KeysCollection,
grid: tuple[int, int] = (2, 2),
size: int | tuple[int, int] | dict[Hashable, int | tuple[int, int] | None] | None = None,
allow_missing_keys: bool = False,
):
super().__init__(keys, allow_missing_keys)
self.grid = grid
self.size = size if isinstance(size, dict) else {key: size for key in self.keys}
self.splitter = GridSplit(grid=grid)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> list[dict[Hashable, NdarrayOrTensor]]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
n_outputs = np.prod(self.grid)
output: list[dict[Hashable, NdarrayOrTensor]] = [dict(d) for _ in range(n_outputs)]
for key in self.key_iterator(d):
result = self.splitter(d[key], self.size[key])
for i in range(n_outputs):
output[i][key] = result[i]
return output
class GridPatchd(MapTransform, MultiSampleTrait):
"""
Extract all the patches sweeping the entire image in a row-major sliding-window manner with possible overlaps.
It can sort the patches and return all or a subset of them.
Args:
keys: keys of the corresponding items to be transformed.
patch_size: size of patches to generate slices for, 0 or None selects whole dimension
offset: starting position in the array, default is 0 for each dimension.
np.random.randint(0, patch_size, 2) creates random start between 0 and `patch_size` for a 2D image.
num_patches: number of patches (or maximum number of patches) to return.
If the requested number of patches is greater than the number of available patches,
padding will be applied to provide exactly `num_patches` patches unless `threshold` is set.
When `threshold` is set, this value is treated as the maximum number of patches.
Defaults to None, which does not limit number of the patches.
overlap: amount of overlap between patches in each dimension. Default to 0.0.
sort_fn: when `num_patches` is provided, it determines if keep patches with highest values (`"max"`),
lowest values (`"min"`), or in their default order (`None`). Default to None.
threshold: a value to keep only the patches whose sum of intensities are less than the threshold.
Defaults to no filtering.
pad_mode: the mode for padding the input image by `patch_size` to include patches that cross boundaries.
Available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``,
``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``}
(PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}.
One of the listed string values or a user supplied function.
Defaults to `None`, which means no padding will be applied.
See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
requires pytorch >= 1.10 for best compatibility.
allow_missing_keys: don't raise exception if key is missing.
pad_kwargs: other arguments for the `np.pad` or `torch.pad` function.
note that `np.pad` treats channel dimension as the first dimension.
Returns:
dictionary, contains the all the original key/value with the values for `keys`
replaced by the patches, a MetaTensor with following metadata:
- `PatchKeys.LOCATION`: the starting location of the patch in the image,
- `PatchKeys.COUNT`: total number of patches in the image,
- "spatial_shape": spatial size of the extracted patch, and
- "offset": the amount of offset for the patches in the image (starting position of the first patch)
"""
backend = GridPatch.backend
def __init__(
self,
keys: KeysCollection,
patch_size: Sequence[int],
offset: Sequence[int] | None = None,
num_patches: int | None = None,
overlap: float = 0.0,
sort_fn: str | None = None,
threshold: float | None = None,
pad_mode: str | None = None,
allow_missing_keys: bool = False,
**pad_kwargs,
):
super().__init__(keys, allow_missing_keys)
self.patcher = GridPatch(
patch_size=patch_size,
offset=offset,
num_patches=num_patches,
overlap=overlap,
sort_fn=sort_fn,
threshold=threshold,
pad_mode=pad_mode,
**pad_kwargs,
)
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
for key in self.key_iterator(d):
d[key] = self.patcher(d[key])
return d
class RandGridPatchd(RandomizableTransform, MapTransform, MultiSampleTrait):
"""
Extract all the patches sweeping the entire image in a row-major sliding-window manner with possible overlaps,
and with random offset for the minimal corner of the image, (0,0) for 2D and (0,0,0) for 3D.
It can sort the patches and return all or a subset of them.
Args:
keys: keys of the corresponding items to be transformed.
patch_size: size of patches to generate slices for, 0 or None selects whole dimension
min_offset: the minimum range of starting position to be selected randomly. Defaults to 0.
max_offset: the maximum range of starting position to be selected randomly.
Defaults to image size modulo patch size.
num_patches: number of patches (or maximum number of patches) to return.
If the requested number of patches is greater than the number of available patches,
padding will be applied to provide exactly `num_patches` patches unless `threshold` is set.
When `threshold` is set, this value is treated as the maximum number of patches.
Defaults to None, which does not limit number of the patches.
overlap: the amount of overlap of neighboring patches in each dimension (a value between 0.0 and 1.0).
If only one float number is given, it will be applied to all dimensions. Defaults to 0.0.
sort_fn: when `num_patches` is provided, it determines if keep patches with highest values (`"max"`),
lowest values (`"min"`), in random ("random"), or in their default order (`None`). Default to None.
threshold: a value to keep only the patches whose sum of intensities are less than the threshold.
Defaults to no filtering.
pad_mode: the mode for padding the input image by `patch_size` to include patches that cross boundaries.
Available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``,
``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``}
(PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}.
One of the listed string values or a user supplied function.
Defaults to `None`, which means no padding will be applied.
See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
requires pytorch >= 1.10 for best compatibility.
allow_missing_keys: don't raise exception if key is missing.
pad_kwargs: other arguments for the `np.pad` or `torch.pad` function.
note that `np.pad` treats channel dimension as the first dimension.
Returns:
dictionary, contains the all the original key/value with the values for `keys`
replaced by the patches, a MetaTensor with following metadata:
- `PatchKeys.LOCATION`: the starting location of the patch in the image,
- `PatchKeys.COUNT`: total number of patches in the image,
- "spatial_shape": spatial size of the extracted patch, and
- "offset": the amount of offset for the patches in the image (starting position of the first patch)
"""
backend = RandGridPatch.backend
def __init__(
self,
keys: KeysCollection,
patch_size: Sequence[int],
min_offset: Sequence[int] | int | None = None,
max_offset: Sequence[int] | int | None = None,
num_patches: int | None = None,
overlap: float = 0.0,
sort_fn: str | None = None,
threshold: float | None = None,
pad_mode: str | None = None,
allow_missing_keys: bool = False,
**pad_kwargs,
):
MapTransform.__init__(self, keys, allow_missing_keys)
self.patcher = RandGridPatch(
patch_size=patch_size,
min_offset=min_offset,
max_offset=max_offset,
num_patches=num_patches,
overlap=overlap,
sort_fn=sort_fn,
threshold=threshold,
pad_mode=pad_mode,
**pad_kwargs,
)
def set_random_state(self, seed: int | None = None, state: np.random.RandomState | None = None) -> RandGridPatchd:
super().set_random_state(seed, state)
self.patcher.set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
Returns:
a dictionary containing the transformed data, as well as any other data present in the dictionary
"""
d = dict(data)
# All the keys share the same random noise
for key in self.key_iterator(d):
self.patcher.randomize(d[key])
break
for key in self.key_iterator(d):
d[key] = self.patcher(d[key], randomize=False)
return d
class RandSimulateLowResolutiond(RandomizableTransform, MapTransform):
"""
Dictionary-based wrapper of :py:class:`monai.transforms.RandSimulateLowResolution`.
Random simulation of low resolution corresponding to nnU-Net's SimulateLowResolutionTransform
(https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/resample_transforms.py#L23)
First, the array/tensor is resampled at lower resolution as determined by the zoom_factor which is uniformly sampled
from the `zoom_range`. Then, the array/tensor is resampled at the original resolution.
"""
backend = RandAffine.backend
def __init__(
self,
keys: KeysCollection,
prob: float = 0.1,
downsample_mode: InterpolateMode | str = InterpolateMode.NEAREST,
upsample_mode: InterpolateMode | str = InterpolateMode.TRILINEAR,
zoom_range=(0.5, 1.0),
align_corners=False,
allow_missing_keys: bool = False,
device: torch.device | None = None,
) -> None:
"""
Args:
keys: keys of the corresponding items to be transformed.
prob: probability of performing this augmentation
downsample_mode: interpolation mode for downsampling operation
upsample_mode: interpolation mode for upsampling operation
zoom_range: range from which the random zoom factor for the downsampling and upsampling operation is
sampled. It determines the shape of the downsampled tensor.
align_corners: This only has an effect when downsample_mode or upsample_mode is 'linear', 'bilinear',
'bicubic' or 'trilinear'. Default: False
See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
allow_missing_keys: don't raise exception if key is missing.
device: device on which the tensor will be allocated.
See also:
- :py:class:`monai.transforms.compose.MapTransform`
"""
MapTransform.__init__(self, keys, allow_missing_keys)
RandomizableTransform.__init__(self, prob)
self.downsample_mode = downsample_mode
self.upsample_mode = upsample_mode
self.zoom_range = zoom_range
self.align_corners = align_corners
self.device = device
self.sim_lowres_tfm = RandSimulateLowResolution(
prob=1.0, # probability is handled by dictionary class
downsample_mode=self.downsample_mode,
upsample_mode=self.upsample_mode,
zoom_range=self.zoom_range,
align_corners=self.align_corners,
device=self.device,
)
def set_random_state(
self, seed: int | None = None, state: np.random.RandomState | None = None
) -> RandSimulateLowResolutiond:
super().set_random_state(seed, state)
return self
def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> dict[Hashable, NdarrayOrTensor]:
"""
Args:
data: a dictionary containing the tensor-like data to be transformed. The ``keys`` specified
in this dictionary must be tensor like arrays that are channel first and have at most
three spatial dimensions
"""
d = dict(data)
first_key: Hashable = self.first_key(d)
if first_key == ():
out: dict[Hashable, NdarrayOrTensor] = convert_to_tensor(d, track_meta=get_track_meta())
return out
self.randomize(None)
for key in self.key_iterator(d):
# do the transform
if self._do_transform:
d[key] = self.sim_lowres_tfm(d[key]) # type: ignore
else:
d[key] = convert_to_tensor(d[key], track_meta=get_track_meta(), dtype=torch.float32)
return d
SpatialResampleD = SpatialResampleDict = SpatialResampled
ResampleToMatchD = ResampleToMatchDict = ResampleToMatchd
SpacingD = SpacingDict = Spacingd
OrientationD = OrientationDict = Orientationd
Rotate90D = Rotate90Dict = Rotate90d
RandRotate90D = RandRotate90Dict = RandRotate90d
ResizeD = ResizeDict = Resized
AffineD = AffineDict = Affined
RandAffineD = RandAffineDict = RandAffined
Rand2DElasticD = Rand2DElasticDict = Rand2DElasticd
Rand3DElasticD = Rand3DElasticDict = Rand3DElasticd
FlipD = FlipDict = Flipd
RandFlipD = RandFlipDict = RandFlipd
GridDistortionD = GridDistortionDict = GridDistortiond
RandGridDistortionD = RandGridDistortionDict = RandGridDistortiond
RandAxisFlipD = RandAxisFlipDict = RandAxisFlipd
RotateD = RotateDict = Rotated
RandRotateD = RandRotateDict = RandRotated
ZoomD = ZoomDict = Zoomd
RandZoomD = RandZoomDict = RandZoomd
GridSplitD = GridSplitDict = GridSplitd
GridPatchD = GridPatchDict = GridPatchd
RandGridPatchD = RandGridPatchDict = RandGridPatchd
RandSimulateLowResolutionD = RandSimulateLowResolutionDict = RandSimulateLowResolutiond
|