File size: 148,240 Bytes
037353a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 | """Transform classes for cropping operations on images and other data types.
This module provides various crop transforms that can be applied to images, masks,
bounding boxes, and keypoints. The transforms include simple cropping, random cropping,
center cropping, cropping near bounding boxes, and other specialized cropping operations
that maintain the integrity of bounding boxes. These transforms are designed to work within
the albumentations pipeline and can be used for data augmentation in computer vision tasks.
"""
from __future__ import annotations
import math
from collections.abc import Sequence
from typing import Annotated, Any, Literal, Union, cast
import cv2
import numpy as np
from pydantic import AfterValidator, Field, model_validator
from typing_extensions import Self
from albumentations.augmentations.geometric import functional as fgeometric
from albumentations.core.bbox_utils import denormalize_bboxes, normalize_bboxes, union_of_bboxes
from albumentations.core.pydantic import (
OnePlusIntRangeType,
ZeroOneRangeType,
check_range_bounds,
nondecreasing,
)
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import (
ALL_TARGETS,
NUM_MULTI_CHANNEL_DIMENSIONS,
PAIR,
PercentType,
PxType,
)
from . import functional as fcrops
__all__ = [
"AtLeastOneBBoxRandomCrop",
"BBoxSafeRandomCrop",
"CenterCrop",
"Crop",
"CropAndPad",
"CropNonEmptyMaskIfExists",
"RandomCrop",
"RandomCropFromBorders",
"RandomCropNearBBox",
"RandomResizedCrop",
"RandomSizedBBoxSafeCrop",
"RandomSizedCrop",
]
class CropSizeError(Exception):
pass
class BaseCrop(DualTransform):
"""Base class for transforms that only perform cropping.
This abstract class provides the foundation for all cropping transformations.
It handles cropping of different data types including images, masks, bounding boxes,
keypoints, and volumes while keeping their spatial relationships intact.
Child classes must implement the `get_params_dependent_on_data` method to determine
crop coordinates based on transform-specific logic. This method should return a dictionary
containing at least a 'crop_coords' key with a tuple value (x_min, y_min, x_max, y_max).
Args:
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
This class is not meant to be used directly. Instead, use or create derived
transforms that implement the specific cropping behavior required.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> from albumentations.augmentations.crops.transforms import BaseCrop
>>>
>>> # Example of a custom crop transform that inherits from BaseCrop
>>> class CustomCenterCrop(BaseCrop):
... '''A simple custom center crop with configurable size'''
... def __init__(self, crop_height, crop_width, p=1.0):
... super().__init__(p=p)
... self.crop_height = crop_height
... self.crop_width = crop_width
...
... def get_params_dependent_on_data(self, params, data):
... '''Calculate crop coordinates based on center of image'''
... image_height, image_width = params["shape"][:2]
...
... # Calculate center crop coordinates
... x_min = max(0, (image_width - self.crop_width) // 2)
... y_min = max(0, (image_height - self.crop_height) // 2)
... x_max = min(image_width, x_min + self.crop_width)
... y_max = min(image_height, y_min + self.crop_height)
...
... return {"crop_coords": (x_min, y_min, x_max, y_max)}
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Use the custom transform in a pipeline
>>> transform = A.Compose(
... [CustomCenterCrop(crop_height=80, crop_width=80)],
... bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels'])
... )
>>>
>>> # Apply the transform to data
>>> result = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = result['image'] # Will be 80x80
>>> transformed_mask = result['mask'] # Will be 80x80
>>> transformed_bboxes = result['bboxes'] # Bounding boxes adjusted to the cropped area
>>> transformed_bbox_labels = result['bbox_labels'] # Labels for bboxes that remain after cropping
>>> transformed_keypoints = result['keypoints'] # Keypoints adjusted to the cropped area
>>> transformed_keypoint_labels = result['keypoint_labels'] # Labels for keypoints that remain after cropping
"""
_targets = ALL_TARGETS
def apply(
self,
img: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop transform to an image.
Args:
img (np.ndarray): The image to apply the crop transform to.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The cropped image.
"""
return fcrops.crop(img, x_min=crop_coords[0], y_min=crop_coords[1], x_max=crop_coords[2], y_max=crop_coords[3])
def apply_to_bboxes(
self,
bboxes: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop transform to bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to apply the crop transform to.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The cropped bounding boxes.
"""
return fcrops.crop_bboxes_by_coords(bboxes, crop_coords, params["shape"][:2])
def apply_to_keypoints(
self,
keypoints: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop transform to keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the crop transform to.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The cropped keypoints.
"""
return fcrops.crop_keypoints_by_coords(keypoints, crop_coords)
def apply_to_images(
self,
images: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return fcrops.volume_crop_yx(images, crop_coords[0], crop_coords[1], crop_coords[2], crop_coords[3])
def apply_to_volume(
self,
volume: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return self.apply_to_images(volume, crop_coords, **params)
def apply_to_volumes(
self,
volumes: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return fcrops.volumes_crop_yx(volumes, crop_coords[0], crop_coords[1], crop_coords[2], crop_coords[3])
def apply_to_mask3d(
self,
mask3d: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return self.apply_to_images(mask3d, crop_coords, **params)
def apply_to_masks3d(
self,
masks3d: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return self.apply_to_volumes(masks3d, crop_coords, **params)
@staticmethod
def _clip_bbox(bbox: tuple[int, int, int, int], image_shape: tuple[int, int]) -> tuple[int, int, int, int]:
height, width = image_shape[:2]
x_min, y_min, x_max, y_max = bbox
x_min = np.clip(x_min, 0, width)
y_min = np.clip(y_min, 0, height)
x_max = np.clip(x_max, x_min, width)
y_max = np.clip(y_max, y_min, height)
return x_min, y_min, x_max, y_max
class BaseCropAndPad(BaseCrop):
"""Base class for transforms that need both cropping and padding.
This abstract class extends BaseCrop by adding padding capabilities. It's the foundation
for transforms that may need to both crop parts of the input and add padding, such as when
converting inputs to a specific target size. The class handles the complexities of applying
these operations to different data types (images, masks, bounding boxes, keypoints) while
maintaining their spatial relationships.
Child classes must implement the `get_params_dependent_on_data` method to determine
crop coordinates and padding parameters based on transform-specific logic.
Args:
pad_if_needed (bool): Whether to pad the input if the crop size exceeds input dimensions.
border_mode (int): OpenCV border mode used for padding.
fill (tuple[float, ...] | float): Value to fill the padded area if border_mode is BORDER_CONSTANT.
For multi-channel images, this can be a tuple with a value for each channel.
fill_mask (tuple[float, ...] | float): Value to fill the padded area in masks.
pad_position (Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"]):
Position of padding when pad_if_needed is True.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
This class is not meant to be used directly. Instead, use or create derived
transforms that implement the specific cropping and padding behavior required.
Examples:
>>> import numpy as np
>>> import cv2
>>> import albumentations as A
>>> from albumentations.augmentations.crops.transforms import BaseCropAndPad
>>>
>>> # Example of a custom transform that inherits from BaseCropAndPad
>>> # This transform crops to a fixed size, padding if needed to maintain dimensions
>>> class CustomFixedSizeCrop(BaseCropAndPad):
... '''A custom fixed-size crop that pads if needed to maintain output size'''
... def __init__(
... self,
... height=224,
... width=224,
... offset_x=0, # Offset for crop position
... offset_y=0, # Offset for crop position
... pad_if_needed=True,
... border_mode=cv2.BORDER_CONSTANT,
... fill=0,
... fill_mask=0,
... pad_position="center",
... p=1.0,
... ):
... super().__init__(
... pad_if_needed=pad_if_needed,
... border_mode=border_mode,
... fill=fill,
... fill_mask=fill_mask,
... pad_position=pad_position,
... p=p,
... )
... self.height = height
... self.width = width
... self.offset_x = offset_x
... self.offset_y = offset_y
...
... def get_params_dependent_on_data(self, params, data):
... '''Calculate crop coordinates and padding if needed'''
... image_shape = params["shape"][:2]
... image_height, image_width = image_shape
...
... # Calculate crop coordinates with offsets
... x_min = self.offset_x
... y_min = self.offset_y
... x_max = min(x_min + self.width, image_width)
... y_max = min(y_min + self.height, image_height)
...
... # Get padding params if needed
... pad_params = self._get_pad_params(
... image_shape,
... (self.height, self.width)
... ) if self.pad_if_needed else None
...
... return {
... "crop_coords": (x_min, y_min, x_max, y_max),
... "pad_params": pad_params,
... }
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Use the custom transform in a pipeline
>>> # This will create a 224x224 crop with padding as needed
>>> transform = A.Compose(
... [CustomFixedSizeCrop(
... height=224,
... width=224,
... offset_x=20,
... offset_y=10,
... fill=127, # Gray color for padding
... fill_mask=0
... )],
... bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform to data
>>> result = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = result['image'] # Will be 224x224 with padding
>>> transformed_mask = result['mask'] # Will be 224x224 with padding
>>> transformed_bboxes = result['bboxes'] # Bounding boxes adjusted to the cropped and padded area
>>> transformed_bbox_labels = result['bbox_labels'] # Bounding box labels after crop
>>> transformed_keypoints = result['keypoints'] # Keypoints adjusted to the cropped and padded area
>>> transformed_keypoint_labels = result['keypoint_labels'] # Keypoint labels after crop
"""
class InitSchema(BaseTransformInitSchema):
pad_if_needed: bool
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
pad_position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"]
def __init__(
self,
pad_if_needed: bool,
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
],
fill: tuple[float, ...] | float,
fill_mask: tuple[float, ...] | float,
pad_position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"],
p: float,
):
super().__init__(p=p)
self.pad_if_needed = pad_if_needed
self.border_mode = border_mode
self.fill = fill
self.fill_mask = fill_mask
self.pad_position = pad_position
def _get_pad_params(self, image_shape: tuple[int, int], target_shape: tuple[int, int]) -> dict[str, Any] | None:
"""Calculate padding parameters if needed."""
if not self.pad_if_needed:
return None
h_pad_top, h_pad_bottom, w_pad_left, w_pad_right = fgeometric.get_padding_params(
image_shape=image_shape,
min_height=target_shape[0],
min_width=target_shape[1],
pad_height_divisor=None,
pad_width_divisor=None,
)
if h_pad_top == h_pad_bottom == w_pad_left == w_pad_right == 0:
return None
h_pad_top, h_pad_bottom, w_pad_left, w_pad_right = fgeometric.adjust_padding_by_position(
h_top=h_pad_top,
h_bottom=h_pad_bottom,
w_left=w_pad_left,
w_right=w_pad_right,
position=self.pad_position,
py_random=self.py_random,
)
return {
"pad_top": h_pad_top,
"pad_bottom": h_pad_bottom,
"pad_left": w_pad_left,
"pad_right": w_pad_right,
}
def apply(
self,
img: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to an image.
Args:
img (np.ndarray): The image to apply the crop and pad transform to.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The cropped and padded image.
"""
pad_params = params.get("pad_params")
if pad_params is not None:
img = fgeometric.pad_with_params(
img,
pad_params["pad_top"],
pad_params["pad_bottom"],
pad_params["pad_left"],
pad_params["pad_right"],
border_mode=self.border_mode,
value=self.fill,
)
return BaseCrop.apply(self, img, crop_coords, **params)
def apply_to_mask(
self,
mask: np.ndarray,
crop_coords: Any,
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to a mask.
Args:
mask (np.ndarray): The mask to apply the crop and pad transform to.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The cropped and padded mask.
"""
pad_params = params.get("pad_params")
if pad_params is not None:
mask = fgeometric.pad_with_params(
mask,
pad_params["pad_top"],
pad_params["pad_bottom"],
pad_params["pad_left"],
pad_params["pad_right"],
border_mode=self.border_mode,
value=self.fill_mask,
)
# Note' that super().apply would apply the padding twice as it is looped to this.apply
return BaseCrop.apply(self, mask, crop_coords=crop_coords, **params)
def apply_to_images(
self,
images: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
pad_params = params.get("pad_params")
if pad_params is not None:
images = fcrops.pad_along_axes(
images,
pad_params["pad_top"],
pad_params["pad_bottom"],
pad_params["pad_left"],
pad_params["pad_right"],
h_axis=2,
w_axis=3,
border_mode=self.border_mode,
pad_value=self.fill,
)
return BaseCrop.apply_to_images(self, images, crop_coords, **params)
def apply_to_volume(
self,
volume: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return self.apply_to_images(volume, crop_coords, **params)
def apply_to_volumes(
self,
volumes: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
pad_params = params.get("pad_params")
if pad_params is not None:
volumes = fcrops.pad_along_axes(
volumes,
pad_params["pad_top"],
pad_params["pad_bottom"],
pad_params["pad_left"],
pad_params["pad_right"],
h_axis=3,
w_axis=4,
border_mode=self.border_mode,
pad_value=self.fill,
)
return BaseCrop.apply_to_volumes(self, volumes, crop_coords, **params)
def apply_to_mask3d(
self,
mask3d: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return self.apply_to_images(mask3d, crop_coords, **params)
def apply_to_masks3d(
self,
masks3d: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
return self.apply_to_volumes(masks3d, crop_coords, **params)
def apply_to_bboxes(
self,
bboxes: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to apply the crop and pad transform to.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The cropped and padded bounding boxes.
"""
pad_params = params.get("pad_params")
image_shape = params["shape"][:2]
if pad_params is not None:
# First denormalize bboxes to absolute coordinates
bboxes_np = denormalize_bboxes(bboxes, image_shape)
# Apply padding to bboxes (already works with absolute coordinates)
bboxes_np = fgeometric.pad_bboxes(
bboxes_np,
pad_params["pad_top"],
pad_params["pad_bottom"],
pad_params["pad_left"],
pad_params["pad_right"],
self.border_mode,
image_shape=image_shape,
)
# Update shape to padded dimensions
padded_height = image_shape[0] + pad_params["pad_top"] + pad_params["pad_bottom"]
padded_width = image_shape[1] + pad_params["pad_left"] + pad_params["pad_right"]
padded_shape = (padded_height, padded_width)
bboxes_np = normalize_bboxes(bboxes_np, padded_shape)
params["shape"] = padded_shape
return BaseCrop.apply_to_bboxes(self, bboxes_np, crop_coords, **params)
# If no padding, use original function behavior
return BaseCrop.apply_to_bboxes(self, bboxes, crop_coords, **params)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the crop and pad transform to.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The cropped and padded keypoints.
"""
pad_params = params.get("pad_params")
image_shape = params["shape"][:2]
if pad_params is not None:
# Calculate padded dimensions
padded_height = image_shape[0] + pad_params["pad_top"] + pad_params["pad_bottom"]
padded_width = image_shape[1] + pad_params["pad_left"] + pad_params["pad_right"]
# First apply padding to keypoints using original image shape
keypoints = fgeometric.pad_keypoints(
keypoints,
pad_params["pad_top"],
pad_params["pad_bottom"],
pad_params["pad_left"],
pad_params["pad_right"],
self.border_mode,
image_shape=image_shape,
)
# Update image shape for subsequent crop operation
params = {**params, "shape": (padded_height, padded_width)}
return BaseCrop.apply_to_keypoints(self, keypoints, crop_coords, **params)
class RandomCrop(BaseCropAndPad):
"""Crop a random part of the input.
Args:
height (int): height of the crop.
width (int): width of the crop.
pad_if_needed (bool): Whether to pad if crop size exceeds image size. Default: False.
border_mode (OpenCV flag): OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.
fill (tuple[float, ...] | float): Padding value for images if border_mode is
cv2.BORDER_CONSTANT. Default: 0.
fill_mask (tuple[float, ...] | float): Padding value for masks if border_mode is
cv2.BORDER_CONSTANT. Default: 0.
pad_position (Literal['center', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'random']):
Position of padding. Default: 'center'.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
If pad_if_needed is True and crop size exceeds image dimensions, the image will be padded
before applying the random crop.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Example 1: Basic random crop
>>> transform = A.Compose([
... A.RandomCrop(height=64, width=64),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Will be 64x64
>>> transformed_mask = transformed['mask'] # Will be 64x64
>>> transformed_bboxes = transformed['bboxes'] # Bounding boxes adjusted to the cropped area
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for boxes that remain after cropping
>>> transformed_keypoints = transformed['keypoints'] # Keypoints adjusted to the cropped area
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for keypoints that remain
>>>
>>> # Example 2: Random crop with padding when needed
>>> # This is useful when you want to crop to a size larger than some images
>>> transform_padded = A.Compose([
... A.RandomCrop(
... height=120, # Larger than original image height
... width=120, # Larger than original image width
... pad_if_needed=True,
... border_mode=cv2.BORDER_CONSTANT,
... fill=0, # Black padding for image
... fill_mask=0 # Zero padding for mask
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the padded transform
>>> padded_transformed = transform_padded(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # The result will be 120x120 with padding
>>> padded_image = padded_transformed['image']
>>> padded_mask = padded_transformed['mask']
>>> padded_bboxes = padded_transformed['bboxes'] # Coordinates adjusted to the new dimensions
"""
class InitSchema(BaseCropAndPad.InitSchema):
height: Annotated[int, Field(ge=1)]
width: Annotated[int, Field(ge=1)]
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
def __init__(
self,
height: int,
width: int,
pad_if_needed: bool = False,
pad_position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"] = "center",
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
fill: tuple[float, ...] | float = 0.0,
fill_mask: tuple[float, ...] | float = 0.0,
p: float = 1.0,
):
super().__init__(
pad_if_needed=pad_if_needed,
border_mode=border_mode,
fill=fill,
fill_mask=fill_mask,
pad_position=pad_position,
p=p,
)
self.height = height
self.width = width
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]: # Changed return type to be more flexible
"""Get parameters that depend on input data.
Args:
params (dict[str, Any]): Parameters.
data (dict[str, Any]): Input data.
Returns:
dict[str, Any]: Dictionary with parameters.
"""
image_shape = params["shape"][:2]
image_height, image_width = image_shape
if not self.pad_if_needed and (self.height > image_height or self.width > image_width):
raise CropSizeError(
f"Crop size (height, width) exceeds image dimensions (height, width):"
f" {(self.height, self.width)} vs {image_shape[:2]}",
)
# Get padding params first if needed
pad_params = self._get_pad_params(image_shape, (self.height, self.width))
# If padding is needed, adjust the image shape for crop calculation
if pad_params is not None:
pad_top = pad_params["pad_top"]
pad_bottom = pad_params["pad_bottom"]
pad_left = pad_params["pad_left"]
pad_right = pad_params["pad_right"]
padded_height = image_height + pad_top + pad_bottom
padded_width = image_width + pad_left + pad_right
padded_shape = (padded_height, padded_width)
# Get random crop coordinates based on padded dimensions
h_start = self.py_random.random()
w_start = self.py_random.random()
crop_coords = fcrops.get_crop_coords(padded_shape, (self.height, self.width), h_start, w_start)
else:
# Get random crop coordinates based on original dimensions
h_start = self.py_random.random()
w_start = self.py_random.random()
crop_coords = fcrops.get_crop_coords(image_shape, (self.height, self.width), h_start, w_start)
return {
"crop_coords": crop_coords,
"pad_params": pad_params,
}
class CenterCrop(BaseCropAndPad):
"""Crop the central part of the input.
This transform crops the center of the input image, mask, bounding boxes, and keypoints to the specified dimensions.
It's useful when you want to focus on the central region of the input, discarding peripheral information.
Args:
height (int): The height of the crop. Must be greater than 0.
width (int): The width of the crop. Must be greater than 0.
pad_if_needed (bool): Whether to pad if crop size exceeds image size. Default: False.
border_mode (OpenCV flag): OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.
fill (tuple[float, ...] | float): Padding value for images if border_mode is
cv2.BORDER_CONSTANT. Default: 0.
fill_mask (tuple[float, ...] | float): Padding value for masks if border_mode is
cv2.BORDER_CONSTANT. Default: 0.
pad_position (Literal['center', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'random']):
Position of padding. Default: 'center'.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- If pad_if_needed is False and crop size exceeds image dimensions, it will raise a CropSizeError.
- If pad_if_needed is True and crop size exceeds image dimensions, the image will be padded.
- For bounding boxes and keypoints, coordinates are adjusted appropriately for both padding and cropping.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Example 1: Basic center crop without padding
>>> transform = A.Compose([
... A.CenterCrop(height=64, width=64),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Will be 64x64
>>> transformed_mask = transformed['mask'] # Will be 64x64
>>> transformed_bboxes = transformed['bboxes'] # Bounding boxes adjusted to the cropped area
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for boxes that remain after cropping
>>> transformed_keypoints = transformed['keypoints'] # Keypoints adjusted to the cropped area
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for keypoints that remain
>>>
>>> # Example 2: Center crop with padding when needed
>>> transform_padded = A.Compose([
... A.CenterCrop(
... height=120, # Larger than original image height
... width=120, # Larger than original image width
... pad_if_needed=True,
... border_mode=cv2.BORDER_CONSTANT,
... fill=0, # Black padding for image
... fill_mask=0 # Zero padding for mask
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the padded transform
>>> padded_transformed = transform_padded(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # The result will be 120x120 with padding
>>> padded_image = padded_transformed['image']
>>> padded_mask = padded_transformed['mask']
>>> padded_bboxes = padded_transformed['bboxes'] # Coordinates adjusted to the new dimensions
>>> padded_keypoints = padded_transformed['keypoints'] # Coordinates adjusted to the new dimensions
"""
class InitSchema(BaseCropAndPad.InitSchema):
height: Annotated[int, Field(ge=1)]
width: Annotated[int, Field(ge=1)]
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
def __init__(
self,
height: int,
width: int,
pad_if_needed: bool = False,
pad_position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"] = "center",
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
fill: tuple[float, ...] | float = 0.0,
fill_mask: tuple[float, ...] | float = 0.0,
p: float = 1.0,
):
super().__init__(
pad_if_needed=pad_if_needed,
border_mode=border_mode,
fill=fill,
fill_mask=fill_mask,
pad_position=pad_position,
p=p,
)
self.height = height
self.width = width
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Get the parameters dependent on the data.
Args:
params (dict[str, Any]): The parameters of the transform.
data (dict[str, Any]): The data of the transform.
"""
image_shape = params["shape"][:2]
image_height, image_width = image_shape
if not self.pad_if_needed and (self.height > image_height or self.width > image_width):
raise CropSizeError(
f"Crop size (height, width) exceeds image dimensions (height, width):"
f" {(self.height, self.width)} vs {image_shape[:2]}",
)
# Get padding params first if needed
pad_params = self._get_pad_params(image_shape, (self.height, self.width))
# If padding is needed, adjust the image shape for crop calculation
if pad_params is not None:
pad_top = pad_params["pad_top"]
pad_bottom = pad_params["pad_bottom"]
pad_left = pad_params["pad_left"]
pad_right = pad_params["pad_right"]
padded_height = image_height + pad_top + pad_bottom
padded_width = image_width + pad_left + pad_right
padded_shape = (padded_height, padded_width)
# Get crop coordinates based on padded dimensions
crop_coords = fcrops.get_center_crop_coords(padded_shape, (self.height, self.width))
else:
# Get crop coordinates based on original dimensions
crop_coords = fcrops.get_center_crop_coords(image_shape, (self.height, self.width))
return {
"crop_coords": crop_coords,
"pad_params": pad_params,
}
class Crop(BaseCropAndPad):
"""Crop a specific region from the input image.
This transform crops a rectangular region from the input image, mask, bounding boxes, and keypoints
based on specified coordinates. It's useful when you want to extract a specific area of interest
from your inputs.
Args:
x_min (int): Minimum x-coordinate of the crop region (left edge). Must be >= 0. Default: 0.
y_min (int): Minimum y-coordinate of the crop region (top edge). Must be >= 0. Default: 0.
x_max (int): Maximum x-coordinate of the crop region (right edge). Must be > x_min. Default: 1024.
y_max (int): Maximum y-coordinate of the crop region (bottom edge). Must be > y_min. Default: 1024.
pad_if_needed (bool): Whether to pad if crop coordinates exceed image dimensions. Default: False.
border_mode (OpenCV flag): OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.
fill (tuple[float, ...] | float): Padding value if border_mode is cv2.BORDER_CONSTANT. Default: 0.
fill_mask (tuple[float, ...] | float): Padding value for masks. Default: 0.
pad_position (Literal['center', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'random']):
Position of padding. Default: 'center'.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The crop coordinates are applied as follows: x_min <= x < x_max and y_min <= y < y_max.
- If pad_if_needed is False and crop region extends beyond image boundaries, it will be clipped.
- If pad_if_needed is True, image will be padded to accommodate the full crop region.
- For bounding boxes and keypoints, coordinates are adjusted appropriately for both padding and cropping.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Example 1: Basic crop with fixed coordinates
>>> transform = A.Compose([
... A.Crop(x_min=20, y_min=20, x_max=80, y_max=80),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Will be 60x60 - cropped from (20,20) to (80,80)
>>> transformed_mask = transformed['mask'] # Will be 60x60
>>> transformed_bboxes = transformed['bboxes'] # Bounding boxes adjusted to the cropped area
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for boxes that remain after cropping
>>>
>>> # Example 2: Crop with padding when the crop region extends beyond image dimensions
>>> transform_padded = A.Compose([
... A.Crop(
... x_min=50, y_min=50, x_max=150, y_max=150, # Extends beyond the 100x100 image
... pad_if_needed=True,
... border_mode=cv2.BORDER_CONSTANT,
... fill=0, # Black padding for image
... fill_mask=0 # Zero padding for mask
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the padded transform
>>> padded_transformed = transform_padded(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # The result will be 100x100 (50:150, 50:150) with padding on right and bottom
>>> padded_image = padded_transformed['image'] # 100x100 with 50 pixels of original + 50 pixels of padding
>>> padded_mask = padded_transformed['mask']
>>> padded_bboxes = padded_transformed['bboxes'] # Coordinates adjusted to the cropped and padded area
>>>
>>> # Example 3: Crop with reflection padding and custom position
>>> transform_reflect = A.Compose([
... A.Crop(
... x_min=-20, y_min=-20, x_max=80, y_max=80, # Negative coordinates (outside image)
... pad_if_needed=True,
... border_mode=cv2.BORDER_REFLECT_101, # Reflect image for padding
... pad_position="top_left" # Apply padding at top-left
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
>>>
>>> # The resulting crop will use reflection padding for the negative coordinates
>>> reflect_result = transform_reflect(
... image=image,
... bboxes=bboxes,
... bbox_labels=bbox_labels
... )
"""
class InitSchema(BaseCropAndPad.InitSchema):
x_min: Annotated[int, Field(ge=0)]
y_min: Annotated[int, Field(ge=0)]
x_max: Annotated[int, Field(gt=0)]
y_max: Annotated[int, Field(gt=0)]
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
@model_validator(mode="after")
def _validate_coordinates(self) -> Self:
if not self.x_min < self.x_max:
msg = "x_max must be greater than x_min"
raise ValueError(msg)
if not self.y_min < self.y_max:
msg = "y_max must be greater than y_min"
raise ValueError(msg)
return self
def __init__(
self,
x_min: int = 0,
y_min: int = 0,
x_max: int = 1024,
y_max: int = 1024,
pad_if_needed: bool = False,
pad_position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"] = "center",
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
p: float = 1.0,
):
super().__init__(
pad_if_needed=pad_if_needed,
border_mode=border_mode,
fill=fill,
fill_mask=fill_mask,
pad_position=pad_position,
p=p,
)
self.x_min = x_min
self.y_min = y_min
self.x_max = x_max
self.y_max = y_max
# New helper function for computing minimum padding
def _compute_min_padding(self, image_height: int, image_width: int) -> tuple[int, int, int, int]:
pad_top = 0
pad_bottom = max(0, self.y_max - image_height)
pad_left = 0
pad_right = max(0, self.x_max - image_width)
return pad_top, pad_bottom, pad_left, pad_right
# New helper function for distributing and adjusting padding
def _compute_adjusted_padding(self, pad_top: int, pad_bottom: int, pad_left: int, pad_right: int) -> dict[str, int]:
delta_h = pad_top + pad_bottom
delta_w = pad_left + pad_right
pad_top_dist = delta_h // 2
pad_bottom_dist = delta_h - pad_top_dist
pad_left_dist = delta_w // 2
pad_right_dist = delta_w - pad_left_dist
(pad_top_adj, pad_bottom_adj, pad_left_adj, pad_right_adj) = fgeometric.adjust_padding_by_position(
h_top=pad_top_dist,
h_bottom=pad_bottom_dist,
w_left=pad_left_dist,
w_right=pad_right_dist,
position=self.pad_position,
py_random=self.py_random,
)
final_top = max(pad_top_adj, pad_top)
final_bottom = max(pad_bottom_adj, pad_bottom)
final_left = max(pad_left_adj, pad_left)
final_right = max(pad_right_adj, pad_right)
return {
"pad_top": final_top,
"pad_bottom": final_bottom,
"pad_left": final_left,
"pad_right": final_right,
}
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters for crop.
Args:
params (dict): Dictionary with parameters for crop.
data (dict): Dictionary with data.
Returns:
dict: Dictionary with parameters for crop.
"""
image_shape = params["shape"][:2]
image_height, image_width = image_shape
if not self.pad_if_needed:
return {"crop_coords": (self.x_min, self.y_min, self.x_max, self.y_max), "pad_params": None}
pad_top, pad_bottom, pad_left, pad_right = self._compute_min_padding(image_height, image_width)
pad_params = None
if any([pad_top, pad_bottom, pad_left, pad_right]):
pad_params = self._compute_adjusted_padding(pad_top, pad_bottom, pad_left, pad_right)
return {"crop_coords": (self.x_min, self.y_min, self.x_max, self.y_max), "pad_params": pad_params}
class CropNonEmptyMaskIfExists(BaseCrop):
"""Crop area with mask if mask is non-empty, else make random crop.
This transform attempts to crop a region containing a mask (non-zero pixels). If the mask is empty or not provided,
it falls back to a random crop. This is particularly useful for segmentation tasks where you want to focus on
regions of interest defined by the mask.
Args:
height (int): Vertical size of crop in pixels. Must be > 0.
width (int): Horizontal size of crop in pixels. Must be > 0.
ignore_values (list of int, optional): Values to ignore in mask, `0` values are always ignored.
For example, if background value is 5, set `ignore_values=[5]` to ignore it. Default: None.
ignore_channels (list of int, optional): Channels to ignore in mask.
For example, if background is the first channel, set `ignore_channels=[0]` to ignore it. Default: None.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- If a mask is provided, the transform will try to crop an area containing non-zero (or non-ignored) pixels.
- If no suitable area is found in the mask or no mask is provided, it will perform a random crop.
- The crop size (height, width) must not exceed the original image dimensions.
- Bounding boxes and keypoints are also cropped along with the image and mask.
Raises:
ValueError: If the specified crop size is larger than the input image dimensions.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.zeros((100, 100), dtype=np.uint8)
>>> mask[25:75, 25:75] = 1 # Create a non-empty region in the mask
>>> transform = A.Compose([
... A.CropNonEmptyMaskIfExists(height=50, width=50, p=1.0),
... ])
>>> transformed = transform(image=image, mask=mask)
>>> transformed_image = transformed['image']
>>> transformed_mask = transformed['mask']
# The resulting crop will likely include part of the non-zero region in the mask
Raises:
ValueError: If the specified crop size is larger than the input image dimensions.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> # Create a mask with non-empty region in the center
>>> mask = np.zeros((100, 100), dtype=np.uint8)
>>> mask[25:75, 25:75] = 1 # Create a non-empty region in the mask
>>>
>>> # Create bounding boxes and keypoints in the mask region
>>> bboxes = np.array([
... [20, 20, 60, 60], # Box overlapping with non-empty region
... [30, 30, 70, 70], # Box mostly inside non-empty region
... ], dtype=np.float32)
>>> bbox_labels = ['cat', 'dog']
>>>
>>> # Add some keypoints inside mask region
>>> keypoints = np.array([
... [40, 40], # Inside non-empty region
... [60, 60], # At edge of non-empty region
... [90, 90] # Outside non-empty region
... ], dtype=np.float32)
>>> keypoint_labels = ['eye', 'nose', 'ear']
>>>
>>> # Define transform that will crop around the non-empty mask region
>>> transform = A.Compose([
... A.CropNonEmptyMaskIfExists(
... height=50,
... width=50,
... ignore_values=None,
... ignore_channels=None,
... p=1.0
... ),
... ], bbox_params=A.BboxParams(
... format='pascal_voc',
... label_fields=['bbox_labels']
... ), keypoint_params=A.KeypointParams(
... format='xy',
... label_fields=['keypoint_labels']
... ))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # 50x50 image centered on mask region
>>> transformed_mask = transformed['mask'] # 50x50 mask showing part of non-empty region
>>> transformed_bboxes = transformed['bboxes'] # Bounding boxes adjusted to new coordinates
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels preserved for visible boxes
>>> transformed_keypoints = transformed['keypoints'] # Keypoints adjusted to new coordinates
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for visible keypoints
"""
class InitSchema(BaseCrop.InitSchema):
ignore_values: list[int] | None
ignore_channels: list[int] | None
height: Annotated[int, Field(ge=1)]
width: Annotated[int, Field(ge=1)]
def __init__(
self,
height: int,
width: int,
ignore_values: list[int] | None = None,
ignore_channels: list[int] | None = None,
p: float = 1.0,
):
super().__init__(p=p)
self.height = height
self.width = width
self.ignore_values = ignore_values
self.ignore_channels = ignore_channels
def _preprocess_mask(self, mask: np.ndarray) -> np.ndarray:
mask_height, mask_width = mask.shape[:2]
if self.ignore_values is not None:
ignore_values_np = np.array(self.ignore_values)
mask = np.where(np.isin(mask, ignore_values_np), 0, mask)
if mask.ndim == NUM_MULTI_CHANNEL_DIMENSIONS and self.ignore_channels is not None:
target_channels = np.array([ch for ch in range(mask.shape[-1]) if ch not in self.ignore_channels])
mask = np.take(mask, target_channels, axis=-1)
if self.height > mask_height or self.width > mask_width:
raise ValueError(
f"Crop size ({self.height},{self.width}) is larger than image ({mask_height},{mask_width})",
)
return mask
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Get crop coordinates based on mask content.
Args:
params (dict[str, Any]): The parameters of the transform.
data (dict[str, Any]): The data of the transform.
"""
if "mask" in data:
mask = self._preprocess_mask(data["mask"])
elif "masks" in data and len(data["masks"]):
masks = data["masks"]
mask = self._preprocess_mask(np.copy(masks[0]))
for m in masks[1:]:
mask |= self._preprocess_mask(m)
else:
msg = "Can not find mask for CropNonEmptyMaskIfExists"
raise RuntimeError(msg)
mask_height, mask_width = mask.shape[:2]
if mask.any():
# Find non-zero regions in mask
mask_sum = mask.sum(axis=-1) if mask.ndim == NUM_MULTI_CHANNEL_DIMENSIONS else mask
non_zero_yx = np.argwhere(mask_sum)
y, x = self.py_random.choice(non_zero_yx)
# Calculate crop coordinates centered around chosen point
x_min = x - self.py_random.randint(0, self.width - 1)
y_min = y - self.py_random.randint(0, self.height - 1)
x_min = np.clip(x_min, 0, mask_width - self.width)
y_min = np.clip(y_min, 0, mask_height - self.height)
else:
# Random crop if no non-zero regions
x_min = self.py_random.randint(0, mask_width - self.width)
y_min = self.py_random.randint(0, mask_height - self.height)
x_max = x_min + self.width
y_max = y_min + self.height
return {"crop_coords": (x_min, y_min, x_max, y_max)}
class BaseRandomSizedCropInitSchema(BaseTransformInitSchema):
size: Annotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))]
class _BaseRandomSizedCrop(DualTransform):
"""Base class for transforms that crop an image randomly and resize it to a specific size.
This abstract class provides the foundation for RandomSizedCrop and RandomResizedCrop transforms.
It handles cropping and resizing for different data types (image, mask, bboxes, keypoints) while
maintaining their spatial relationships.
Child classes must implement the `get_params_dependent_on_data` method to determine how the
crop coordinates are selected according to transform-specific parameters and logic.
Args:
size (tuple[int, int]): Target size (height, width) after cropping and resizing.
interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm
for image resizing. Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation
algorithm for mask resizing. Default: cv2.INTER_NEAREST.
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
This class is not meant to be used directly. Instead, use derived transforms
like RandomSizedCrop or RandomResizedCrop that implement specific crop selection
strategies.
When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
downscaling (when the crop is larger than the target size), which provides better quality for size reduction.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Example of a custom transform that inherits from _BaseRandomSizedCrop
>>> class CustomRandomCrop(_BaseRandomSizedCrop):
... def __init__(
... self,
... size=(224, 224),
... custom_parameter=0.5,
... interpolation=cv2.INTER_LINEAR,
... mask_interpolation=cv2.INTER_NEAREST,
... area_for_downscale="image",
... p=1.0
... ):
... super().__init__(
... size=size,
... interpolation=interpolation,
... mask_interpolation=mask_interpolation,
... area_for_downscale=area_for_downscale,
... p=p,
... )
... self.custom_parameter = custom_parameter
...
... def get_params_dependent_on_data(self, params, data):
... # Custom logic to select crop coordinates
... image_height, image_width = params["shape"][:2]
...
... # Simple example: calculate crop size based on custom_parameter
... crop_height = int(image_height * self.custom_parameter)
... crop_width = int(image_width * self.custom_parameter)
...
... # Random position
... y1 = self.py_random.randint(0, image_height - crop_height + 1)
... x1 = self.py_random.randint(0, image_width - crop_width + 1)
... y2 = y1 + crop_height
... x2 = x1 + crop_width
...
... return {"crop_coords": (x1, y1, x2, y2)}
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Create a pipeline with our custom transform
>>> transform = A.Compose(
... [CustomRandomCrop(size=(64, 64), custom_parameter=0.6, area_for_downscale="image")],
... bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels'])
... )
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Will be 64x64
>>> transformed_mask = transformed['mask'] # Will be 64x64
>>> transformed_bboxes = transformed['bboxes'] # Bounding boxes adjusted to new dimensions
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for bboxes that remain after cropping
>>> transformed_keypoints = transformed['keypoints'] # Keypoints adjusted to new dimensions
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for keypoints that remain
"""
class InitSchema(BaseRandomSizedCropInitSchema):
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
area_for_downscale: Literal[None, "image", "image_mask"]
def __init__(
self,
size: tuple[int, int],
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
area_for_downscale: Literal[None, "image", "image_mask"] = None,
p: float = 1.0,
):
super().__init__(p=p)
self.size = size
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
self.area_for_downscale = area_for_downscale
def _get_interpolation_for_resize(self, crop_shape: tuple[int, int], target_type: str) -> int:
"""Get the appropriate interpolation method for resizing.
Args:
crop_shape: Shape of the crop (height, width)
target_type: Either "image" or "mask" to determine base interpolation
Returns:
OpenCV interpolation flag
"""
crop_height, crop_width = crop_shape
target_height, target_width = self.size
# Determine if this is downscaling
is_downscale = (crop_height > target_height) or (crop_width > target_width)
# Use INTER_AREA for downscaling if configured
if (is_downscale and (target_type == "image" and self.area_for_downscale in ["image", "image_mask"])) or (
target_type == "mask" and self.area_for_downscale == "image_mask"
):
return cv2.INTER_AREA
# Get base interpolation
return self.interpolation if target_type == "image" else self.mask_interpolation
def apply(
self,
img: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop to the image.
Args:
img (np.ndarray): The image to crop.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
**params (Any): Additional parameters.
"""
crop = fcrops.crop(img, *crop_coords)
interpolation = self._get_interpolation_for_resize(crop.shape[:2], "image")
return fgeometric.resize(crop, self.size, interpolation)
def apply_to_mask(
self,
mask: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop to the mask.
Args:
mask (np.ndarray): The mask to crop.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
**params (Any): Additional parameters.
"""
crop = fcrops.crop(mask, *crop_coords)
interpolation = self._get_interpolation_for_resize(crop.shape[:2], "mask")
return fgeometric.resize(crop, self.size, interpolation)
def apply_to_bboxes(
self,
bboxes: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop to the bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to crop.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
**params (Any): Additional parameters.
"""
return fcrops.crop_bboxes_by_coords(bboxes, crop_coords, params["shape"])
def apply_to_keypoints(
self,
keypoints: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop to the keypoints.
Args:
keypoints (np.ndarray): The keypoints to crop.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
**params (Any): Additional parameters.
"""
# First, crop the keypoints
cropped_keypoints = fcrops.crop_keypoints_by_coords(keypoints, crop_coords)
# Calculate the dimensions of the crop
crop_height = crop_coords[3] - crop_coords[1]
crop_width = crop_coords[2] - crop_coords[0]
# Calculate scaling factors
scale_x = self.size[1] / crop_width
scale_y = self.size[0] / crop_height
# Scale the cropped keypoints
return fgeometric.keypoints_scale(cropped_keypoints, scale_x, scale_y)
def apply_to_images(
self,
images: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and resize to a volume/images.
This method crops the volume first (reducing data size), then resizes using
a helper method with batch transform decorator.
Args:
images (np.ndarray): The volume/images to crop and resize with shape (D, H, W) or (D, H, W, C).
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
**params (Any): Additional parameters.
"""
# First crop the volume using volume_crop_yx (reduces data size)
crop = fcrops.volume_crop_yx(images, *crop_coords)
# Get interpolation method based on crop dimensions
interpolation = self._get_interpolation_for_resize(crop.shape[1:3], "image")
# Then resize the smaller cropped volume using the selected interpolation
return np.stack([fgeometric.resize(crop[i], self.size, interpolation) for i in range(images.shape[0])])
def apply_to_volume(
self,
volume: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and resize to a volume.
Args:
volume (np.ndarray): The volume to crop.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
**params (Any): Additional parameters.
"""
return self.apply_to_images(volume, crop_coords, **params)
def apply_to_mask3d(
self,
mask3d: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and resize to a mask3d.
Args:
mask3d (np.ndarray): The mask3d to crop.
crop_coords (tuple[int, int, int, int]): The coordinates of the crop.
**params (Any): Additional parameters.
"""
return self.apply_to_images(mask3d, crop_coords, **params)
class RandomSizedCrop(_BaseRandomSizedCrop):
"""Crop a random part of the input and rescale it to a specific size.
This transform first crops a random portion of the input and then resizes it to a specified size.
The size of the random crop is controlled by the 'min_max_height' parameter.
Args:
min_max_height (tuple[int, int]): Minimum and maximum height of the crop in pixels.
size (tuple[int, int]): Target size for the output image, i.e. (height, width) after crop and resize.
w2h_ratio (float): Aspect ratio (width/height) of crop. Default: 1.0
interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): Probability of applying the transform. Default: 1.0
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The crop size is randomly selected for each execution within the range specified by 'min_max_height'.
- The aspect ratio of the crop is determined by the 'w2h_ratio' parameter.
- After cropping, the result is resized to the specified 'size'.
- Bounding boxes that end up fully outside the cropped area will be removed.
- Keypoints that end up outside the cropped area will be removed.
- This transform differs from RandomResizedCrop in that it allows more control over the crop size
through the 'min_max_height' parameter, rather than using a scale parameter.
- When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
downscaling (when the crop is larger than the target size), which provides better quality for size reduction.
Mathematical Details:
1. A random crop height h is sampled from the range [min_max_height[0], min_max_height[1]].
2. The crop width w is calculated as: w = h * w2h_ratio
3. A random location for the crop is selected within the input image.
4. The image is cropped to the size (h, w).
5. The crop is then resized to the specified 'size'.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Define transform with parameters as tuples
>>> transform = A.Compose([
... A.RandomSizedCrop(
... min_max_height=(50, 80),
... size=(64, 64),
... w2h_ratio=1.0,
... interpolation=cv2.INTER_LINEAR,
... mask_interpolation=cv2.INTER_NEAREST,
... area_for_downscale="image", # Use INTER_AREA for image downscaling
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Shape: (64, 64, 3)
>>> transformed_mask = transformed['mask'] # Shape: (64, 64)
>>> transformed_bboxes = transformed['bboxes'] # Bounding boxes adjusted to new crop and size
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for the preserved bboxes
>>> transformed_keypoints = transformed['keypoints'] # Keypoints adjusted to new crop and size
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for the preserved keypoints
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
min_max_height: OnePlusIntRangeType
w2h_ratio: Annotated[float, Field(gt=0)]
size: Annotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))]
area_for_downscale: Literal[None, "image", "image_mask"]
def __init__(
self,
min_max_height: tuple[int, int],
size: tuple[int, int],
w2h_ratio: float = 1.0,
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
area_for_downscale: Literal[None, "image", "image_mask"] = None,
p: float = 1.0,
):
super().__init__(
size=size,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
area_for_downscale=area_for_downscale,
p=p,
)
self.min_max_height = min_max_height
self.w2h_ratio = w2h_ratio
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
"""Get the parameters dependent on the data.
Args:
params (dict[str, Any]): The parameters of the transform.
data (dict[str, Any]): The data of the transform.
"""
image_shape = params["shape"][:2]
crop_height = self.py_random.randint(*self.min_max_height)
crop_width = int(crop_height * self.w2h_ratio)
crop_shape = (crop_height, crop_width)
h_start = self.py_random.random()
w_start = self.py_random.random()
crop_coords = fcrops.get_crop_coords(image_shape, crop_shape, h_start, w_start)
return {"crop_coords": crop_coords}
class RandomResizedCrop(_BaseRandomSizedCrop):
"""Crop a random part of the input and rescale it to a specified size.
This transform first crops a random portion of the input image (or mask, bounding boxes, keypoints)
and then resizes the crop to a specified size. It's particularly useful for training neural networks
on images of varying sizes and aspect ratios.
Args:
size (tuple[int, int]): Target size for the output image, i.e. (height, width) after crop and resize.
scale (tuple[float, float]): Range of the random size of the crop relative to the input size.
For example, (0.08, 1.0) means the crop size will be between 8% and 100% of the input size.
Default: (0.08, 1.0)
ratio (tuple[float, float]): Range of aspect ratios of the random crop.
For example, (0.75, 1.3333) allows crop aspect ratios from 3:4 to 4:3.
Default: (0.75, 1.3333333333333333)
interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR
mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): Probability of applying the transform. Default: 1.0
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- This transform attempts to crop a random area with an aspect ratio and relative size
specified by 'ratio' and 'scale' parameters. If it fails to find a suitable crop after
10 attempts, it will return a crop from the center of the image.
- The crop's aspect ratio is defined as width / height.
- Bounding boxes that end up fully outside the cropped area will be removed.
- Keypoints that end up outside the cropped area will be removed.
- After cropping, the result is resized to the specified size.
- When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
downscaling (when the crop is larger than the target size), which provides better quality for size reduction.
Mathematical Details:
1. A target area A is sampled from the range [scale[0] * input_area, scale[1] * input_area].
2. A target aspect ratio r is sampled from the range [ratio[0], ratio[1]].
3. The crop width and height are computed as:
w = sqrt(A * r)
h = sqrt(A / r)
4. If w and h are within the input image dimensions, the crop is accepted.
Otherwise, steps 1-3 are repeated (up to 10 times).
5. If no valid crop is found after 10 attempts, a centered crop is taken.
6. The crop is then resized to the specified size.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Define transform with parameters as tuples
>>> transform = A.Compose([
... A.RandomResizedCrop(
... size=(64, 64),
... scale=(0.5, 0.9), # Crop size will be 50-90% of original image
... ratio=(0.75, 1.33), # Aspect ratio will vary from 3:4 to 4:3
... interpolation=cv2.INTER_LINEAR,
... mask_interpolation=cv2.INTER_NEAREST,
... area_for_downscale="image", # Use INTER_AREA for image downscaling
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Shape: (64, 64, 3)
>>> transformed_mask = transformed['mask'] # Shape: (64, 64)
>>> transformed_bboxes = transformed['bboxes'] # Bounding boxes adjusted to new crop and size
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for the preserved bboxes
>>> transformed_keypoints = transformed['keypoints'] # Keypoints adjusted to new crop and size
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for the preserved keypoints
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
scale: Annotated[tuple[float, float], AfterValidator(check_range_bounds(0, 1)), AfterValidator(nondecreasing)]
ratio: Annotated[
tuple[float, float],
AfterValidator(check_range_bounds(0, None)),
AfterValidator(nondecreasing),
]
size: Annotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))]
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
area_for_downscale: Literal[None, "image", "image_mask"]
def __init__(
self,
size: tuple[int, int],
scale: tuple[float, float] = (0.08, 1.0),
ratio: tuple[float, float] = (0.75, 1.3333333333333333),
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
area_for_downscale: Literal[None, "image", "image_mask"] = None,
p: float = 1.0,
):
super().__init__(
size=size,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
area_for_downscale=area_for_downscale,
p=p,
)
self.scale = scale
self.ratio = ratio
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
"""Get the parameters dependent on the data.
Args:
params (dict[str, Any]): The parameters of the transform.
data (dict[str, Any]): The data of the transform.
"""
image_shape = params["shape"][:2]
image_height, image_width = image_shape
area = image_height * image_width
# Pre-compute constants to avoid repeated calculations
scale_min_area = self.scale[0] * area
scale_max_area = self.scale[1] * area
log_ratio_min = math.log(self.ratio[0])
log_ratio_max = math.log(self.ratio[1])
for _ in range(10):
target_area = self.py_random.uniform(scale_min_area, scale_max_area)
aspect_ratio = math.exp(self.py_random.uniform(log_ratio_min, log_ratio_max))
width = round(math.sqrt(target_area * aspect_ratio))
height = round(math.sqrt(target_area / aspect_ratio))
if 0 < width <= image_width and 0 < height <= image_height:
h_start = self.py_random.random()
w_start = self.py_random.random()
crop_coords = fcrops.get_crop_coords(image_shape, (height, width), h_start, w_start)
return {"crop_coords": crop_coords}
# Fallback to central crop - use proper function
in_ratio = image_width / image_height
if in_ratio < self.ratio[0]:
width = image_width
height = round(image_width / self.ratio[0])
elif in_ratio > self.ratio[1]:
height = image_height
width = round(height * self.ratio[1])
else: # whole image
width = image_width
height = image_height
crop_coords = fcrops.get_center_crop_coords(image_shape, (height, width))
return {"crop_coords": crop_coords}
class RandomCropNearBBox(BaseCrop):
"""Crop bbox from image with random shift by x,y coordinates
Args:
max_part_shift (float, (float, float)): Max shift in `height` and `width` dimensions relative
to `cropping_bbox` dimension.
If max_part_shift is a single float, the range will be (0, max_part_shift).
Default (0, 0.3).
cropping_bbox_key (str): Additional target key for cropping box. Default `cropping_bbox`.
p (float): probability of applying the transform. Default: 1.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Examples:
>>> aug = Compose([RandomCropNearBBox(max_part_shift=(0.1, 0.5), cropping_bbox_key='test_bbox')],
>>> bbox_params=BboxParams("pascal_voc"))
>>> result = aug(image=image, bboxes=bboxes, test_bbox=[0, 5, 10, 20])
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
max_part_shift: ZeroOneRangeType
cropping_bbox_key: str
def __init__(
self,
max_part_shift: tuple[float, float] | float = (0, 0.3),
cropping_bbox_key: str = "cropping_bbox",
p: float = 1.0,
):
super().__init__(p=p)
self.max_part_shift = cast("tuple[float, float]", max_part_shift)
self.cropping_bbox_key = cropping_bbox_key
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[float, ...]]:
"""Get the parameters dependent on the data.
Args:
params (dict[str, Any]): The parameters of the transform.
data (dict[str, Any]): The data of the transform.
"""
bbox = data[self.cropping_bbox_key]
image_shape = params["shape"][:2]
bbox = self._clip_bbox(bbox, image_shape)
h_max_shift = round((bbox[3] - bbox[1]) * self.max_part_shift[0])
w_max_shift = round((bbox[2] - bbox[0]) * self.max_part_shift[1])
x_min = bbox[0] - self.py_random.randint(-w_max_shift, w_max_shift)
x_max = bbox[2] + self.py_random.randint(-w_max_shift, w_max_shift)
y_min = bbox[1] - self.py_random.randint(-h_max_shift, h_max_shift)
y_max = bbox[3] + self.py_random.randint(-h_max_shift, h_max_shift)
crop_coords = self._clip_bbox((x_min, y_min, x_max, y_max), image_shape)
if crop_coords[0] == crop_coords[2] or crop_coords[1] == crop_coords[3]:
crop_shape = (bbox[3] - bbox[1], bbox[2] - bbox[0])
crop_coords = fcrops.get_center_crop_coords(image_shape, crop_shape)
return {"crop_coords": crop_coords}
@property
def targets_as_params(self) -> list[str]:
"""Get the targets as parameters.
Returns:
list[str]: The targets as parameters.
"""
return [self.cropping_bbox_key]
class BBoxSafeRandomCrop(BaseCrop):
"""Crop an area from image while ensuring all bounding boxes are preserved in the crop.
Similar to AtLeastOneBboxRandomCrop, but with a key difference:
- BBoxSafeRandomCrop ensures ALL bounding boxes are preserved in the crop when erosion_rate=0.0
- AtLeastOneBboxRandomCrop ensures AT LEAST ONE bounding box is present in the crop
This makes BBoxSafeRandomCrop more suitable for scenarios where:
- You need to preserve all objects in the scene
- Losing any bounding box would be problematic (e.g., rare object classes)
- You're training a model that needs to detect multiple objects simultaneously
The algorithm:
1. If bounding boxes exist:
- Computes the union of all bounding boxes
- Applies erosion based on erosion_rate to this union
- Clips the eroded union to valid image coordinates [0,1]
- Randomly samples crop coordinates within the clipped union area
2. If no bounding boxes exist:
- Computes crop height based on erosion_rate
- Sets crop width to maintain original aspect ratio
- Randomly places the crop within the image
Args:
erosion_rate (float): Controls how much the valid crop region can deviate from the bbox union.
Must be in range [0.0, 1.0].
- 0.0: crop must contain the exact bbox union (safest option that guarantees all boxes are preserved)
- 1.0: crop can deviate maximally from the bbox union (increases likelihood of cutting off some boxes)
Defaults to 0.0.
p (float, optional): Probability of applying the transform. Defaults to 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Raises:
CropSizeError: If requested crop size exceeds image dimensions
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Define transform with erosion_rate parameter
>>> transform = A.Compose([
... A.BBoxSafeRandomCrop(erosion_rate=0.2),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> result = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = result['image'] # Cropped image containing all bboxes
>>> transformed_mask = result['mask'] # Cropped mask
>>> transformed_bboxes = result['bboxes'] # All bounding boxes preserved with adjusted coordinates
>>> transformed_bbox_labels = result['bbox_labels'] # Original labels preserved
>>> transformed_keypoints = result['keypoints'] # Keypoints with adjusted coordinates
>>> transformed_keypoint_labels = result['keypoint_labels'] # Original keypoint labels preserved
>>>
>>> # Example with a different erosion_rate
>>> transform_more_flexible = A.Compose([
... A.BBoxSafeRandomCrop(erosion_rate=0.5), # More flexibility in crop placement
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
>>>
>>> # Apply transform with only image and bboxes
>>> result_bboxes_only = transform_more_flexible(
... image=image,
... bboxes=bboxes,
... bbox_labels=bbox_labels
... )
>>> transformed_image = result_bboxes_only['image']
>>> transformed_bboxes = result_bboxes_only['bboxes'] # All bboxes still preserved
Note:
- IMPORTANT: Using erosion_rate > 0.0 may result in some bounding boxes being cut off,
particularly narrow boxes at the boundary of the union area. For guaranteed preservation
of all bounding boxes, use erosion_rate=0.0.
- Aspect ratio is preserved only when no bounding boxes are present
- May be more restrictive in crop placement compared to AtLeastOneBboxRandomCrop
- The crop size is determined by the bounding boxes when present
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
erosion_rate: float = Field(
ge=0.0,
le=1.0,
)
def __init__(self, erosion_rate: float = 0.0, p: float = 1.0):
super().__init__(p=p)
self.erosion_rate = erosion_rate
def _get_coords_no_bbox(self, image_shape: tuple[int, int]) -> tuple[int, int, int, int]:
image_height, image_width = image_shape
erosive_h = int(image_height * (1.0 - self.erosion_rate))
crop_height = image_height if erosive_h >= image_height else self.py_random.randint(erosive_h, image_height)
crop_width = int(crop_height * image_width / image_height)
h_start = self.py_random.random()
w_start = self.py_random.random()
crop_shape = (crop_height, crop_width)
return fcrops.get_crop_coords(image_shape, crop_shape, h_start, w_start)
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
"""Get the parameters dependent on the data.
Args:
params (dict[str, Any]): The parameters of the transform.
data (dict[str, Any]): The data of the transform.
"""
image_shape = params["shape"][:2]
if len(data["bboxes"]) == 0: # less likely, this class is for use with bboxes.
crop_coords = self._get_coords_no_bbox(image_shape)
return {"crop_coords": crop_coords}
bbox_union = union_of_bboxes(bboxes=data["bboxes"], erosion_rate=self.erosion_rate)
if bbox_union is None:
crop_coords = self._get_coords_no_bbox(image_shape)
return {"crop_coords": crop_coords}
x_min, y_min, x_max, y_max = bbox_union
x_min = np.clip(x_min, 0, 1)
y_min = np.clip(y_min, 0, 1)
x_max = np.clip(x_max, x_min, 1)
y_max = np.clip(y_max, y_min, 1)
image_height, image_width = image_shape
crop_x_min = int(x_min * self.py_random.random() * image_width)
crop_y_min = int(y_min * self.py_random.random() * image_height)
bbox_xmax = x_max + (1 - x_max) * self.py_random.random()
bbox_ymax = y_max + (1 - y_max) * self.py_random.random()
crop_x_max = int(bbox_xmax * image_width)
crop_y_max = int(bbox_ymax * image_height)
return {"crop_coords": (crop_x_min, crop_y_min, crop_x_max, crop_y_max)}
class RandomSizedBBoxSafeCrop(BBoxSafeRandomCrop):
"""Crop a random part of the input and rescale it to a specific size without loss of bounding boxes.
This transform first attempts to crop a random portion of the input image while ensuring that all bounding boxes
remain within the cropped area. It then resizes the crop to the specified size. This is particularly useful for
object detection tasks where preserving all objects in the image is crucial while also standardizing the image size.
Args:
height (int): Height of the output image after resizing.
width (int): Width of the output image after resizing.
erosion_rate (float): A value between 0.0 and 1.0 that determines the minimum allowable size of the crop
as a fraction of the original image size. For example, an erosion_rate of 0.2 means the crop will be
at least 80% of the original image height and width. Default: 0.0 (no minimum size).
interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- This transform ensures that all bounding boxes in the original image are fully contained within the
cropped area. If it's not possible to find such a crop (e.g., when bounding boxes are too spread out),
it will default to cropping the entire image.
- After cropping, the result is resized to the specified (height, width) size.
- Bounding box coordinates are adjusted to match the new image size.
- Keypoints are moved along with the crop and scaled to the new image size.
- If there are no bounding boxes in the image, it will fall back to a random crop.
Mathematical Details:
1. A crop region is selected that includes all bounding boxes.
2. The crop size is determined by the erosion_rate:
min_crop_size = (1 - erosion_rate) * original_size
3. If the selected crop is smaller than min_crop_size, it's expanded to meet this requirement.
4. The crop is then resized to the specified (height, width) size.
5. Bounding box coordinates are transformed to match the new image size:
new_coord = (old_coord - crop_start) * (new_size / crop_size)
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (300, 300, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (300, 300), dtype=np.uint8)
>>>
>>> # Create bounding boxes with some overlap and separation
>>> bboxes = np.array([
... [10, 10, 80, 80], # top-left box
... [100, 100, 200, 200], # center box
... [210, 210, 290, 290] # bottom-right box
... ], dtype=np.float32)
>>> bbox_labels = ['cat', 'dog', 'bird']
>>>
>>> # Create keypoints inside the bounding boxes
>>> keypoints = np.array([
... [45, 45], # inside first box
... [150, 150], # inside second box
... [250, 250] # inside third box
... ], dtype=np.float32)
>>> keypoint_labels = ['nose', 'eye', 'tail']
>>>
>>> # Example 1: Basic usage with default parameters
>>> transform_basic = A.Compose([
... A.RandomSizedBBoxSafeCrop(height=224, width=224, p=1.0),
... ], bbox_params=A.BboxParams(
... format='pascal_voc',
... label_fields=['bbox_labels']
... ), keypoint_params=A.KeypointParams(
... format='xy',
... label_fields=['keypoint_labels']
... ))
>>>
>>> # Apply the transform
>>> result_basic = transform_basic(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Access the transformed data
>>> transformed_image = result_basic['image'] # Shape will be (224, 224, 3)
>>> transformed_mask = result_basic['mask'] # Shape will be (224, 224)
>>> transformed_bboxes = result_basic['bboxes'] # All original bounding boxes preserved
>>> transformed_bbox_labels = result_basic['bbox_labels'] # Original labels preserved
>>> transformed_keypoints = result_basic['keypoints'] # Keypoints adjusted to new coordinates
>>> transformed_keypoint_labels = result_basic['keypoint_labels'] # Original labels preserved
>>>
>>> # Example 2: With erosion_rate for more flexibility in crop placement
>>> transform_erosion = A.Compose([
... A.RandomSizedBBoxSafeCrop(
... height=256,
... width=256,
... erosion_rate=0.2, # Allows 20% flexibility in crop placement
... interpolation=cv2.INTER_CUBIC, # Higher quality interpolation
... mask_interpolation=cv2.INTER_NEAREST, # Preserve mask edges
... p=1.0
... ),
... ], bbox_params=A.BboxParams(
... format='pascal_voc',
... label_fields=['bbox_labels'],
... min_visibility=0.3 # Only keep bboxes with at least 30% visibility
... ), keypoint_params=A.KeypointParams(
... format='xy',
... label_fields=['keypoint_labels'],
... remove_invisible=True # Remove keypoints outside the crop
... ))
>>>
>>> # Apply the transform with erosion
>>> result_erosion = transform_erosion(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # With erosion_rate=0.2, the crop has more flexibility in placement
>>> # while still ensuring all bounding boxes are included
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
height: Annotated[int, Field(ge=1)]
width: Annotated[int, Field(ge=1)]
erosion_rate: float = Field(
ge=0.0,
le=1.0,
)
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
def __init__(
self,
height: int,
width: int,
erosion_rate: float = 0.0,
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
p: float = 1.0,
):
super().__init__(erosion_rate=erosion_rate, p=p)
self.height = height
self.width = width
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
def apply(
self,
img: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to an image.
Args:
img (np.ndarray): The image to apply the crop and pad transform to.
crop_coords (tuple[int, int, int, int]): The parameters for the crop.
params (dict[str, Any]): Additional parameters for the transform.
"""
crop = fcrops.crop(img, *crop_coords)
return fgeometric.resize(crop, (self.height, self.width), self.interpolation)
def apply_to_mask(
self,
mask: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to a mask.
Args:
mask (np.ndarray): The mask to apply the crop and pad transform to.
crop_coords (tuple[int, int, int, int]): The parameters for the crop.
params (dict[str, Any]): Additional parameters for the transform.
"""
crop = fcrops.crop(mask, *crop_coords)
return fgeometric.resize(crop, (self.height, self.width), self.mask_interpolation)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
crop_coords: tuple[int, int, int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the crop and pad transform to.
crop_coords (tuple[int, int, int, int]): The parameters for the crop.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The keypoints after the crop and pad transform.
"""
keypoints = fcrops.crop_keypoints_by_coords(keypoints, crop_coords)
crop_height = crop_coords[3] - crop_coords[1]
crop_width = crop_coords[2] - crop_coords[0]
scale_y = self.height / crop_height
scale_x = self.width / crop_width
return fgeometric.keypoints_scale(keypoints, scale_x=scale_x, scale_y=scale_y)
class CropAndPad(DualTransform):
"""Crop and pad images by pixel amounts or fractions of image sizes.
This transform allows for simultaneous cropping and padding of images. Cropping removes pixels from the sides
(i.e., extracts a subimage), while padding adds pixels to the sides (e.g., black pixels). The amount of
cropping/padding can be specified either in absolute pixels or as a fraction of the image size.
Args:
px (int, tuple of int, tuple of tuples of int, or None):
The number of pixels to crop (negative values) or pad (positive values) on each side of the image.
Either this or the parameter `percent` may be set, not both at the same time.
- If int: crop/pad all sides by this value.
- If tuple of 2 ints: crop/pad by (top/bottom, left/right).
- If tuple of 4 ints: crop/pad by (top, right, bottom, left).
- Each int can also be a tuple of 2 ints for a range, or a list of ints for discrete choices.
Default: None.
percent (float, tuple of float, tuple of tuples of float, or None):
The fraction of the image size to crop (negative values) or pad (positive values) on each side.
Either this or the parameter `px` may be set, not both at the same time.
- If float: crop/pad all sides by this fraction.
- If tuple of 2 floats: crop/pad by (top/bottom, left/right) fractions.
- If tuple of 4 floats: crop/pad by (top, right, bottom, left) fractions.
- Each float can also be a tuple of 2 floats for a range, or a list of floats for discrete choices.
Default: None.
border_mode (int):
OpenCV border mode used for padding. Default: cv2.BORDER_CONSTANT.
fill (tuple[float, ...] | float):
The constant value to use for padding if border_mode is cv2.BORDER_CONSTANT.
Default: 0.
fill_mask (tuple[float, ...] | float):
Same as fill but used for mask padding. Default: 0.
keep_size (bool):
If True, the output image will be resized to the input image size after cropping/padding.
Default: True.
sample_independently (bool):
If True and ranges are used for px/percent, sample a value for each side independently.
If False, sample one value and use it for all sides. Default: True.
interpolation (int):
OpenCV interpolation flag used for resizing if keep_size is True.
Default: cv2.INTER_LINEAR.
mask_interpolation (int):
OpenCV interpolation flag used for resizing if keep_size is True.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
p (float):
Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- This transform will never crop images below a height or width of 1.
- When using pixel values (px), the image will be cropped/padded by exactly that many pixels.
- When using percentages (percent), the amount of crop/pad will be calculated based on the image size.
- Bounding boxes that end up fully outside the image after cropping will be removed.
- Keypoints that end up outside the image after cropping will be removed.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Example 1: Using px parameter with specific values for each side
>>> # Crop 10px from top, pad 20px on right, pad 30px on bottom, crop 40px from left
>>> transform_px = A.Compose([
... A.CropAndPad(
... px=(-10, 20, 30, -40), # (top, right, bottom, left)
... border_mode=cv2.BORDER_CONSTANT,
... fill=128, # Gray padding color
... fill_mask=0,
... keep_size=False, # Don't resize back to original dimensions
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> result_px = transform_px(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data with px parameters
>>> transformed_image_px = result_px['image'] # Shape will be different from original
>>> transformed_mask_px = result_px['mask']
>>> transformed_bboxes_px = result_px['bboxes'] # Adjusted to new dimensions
>>> transformed_bbox_labels_px = result_px['bbox_labels'] # Bounding box labels after crop
>>> transformed_keypoints_px = result_px['keypoints'] # Adjusted to new dimensions
>>> transformed_keypoint_labels_px = result_px['keypoint_labels'] # Keypoint labels after crop
>>>
>>> # Example 2: Using percent parameter as a single value
>>> # This will pad all sides by 10% of image dimensions
>>> transform_percent = A.Compose([
... A.CropAndPad(
... percent=0.1, # Pad all sides by 10%
... border_mode=cv2.BORDER_REFLECT, # Use reflection padding
... keep_size=True, # Resize back to original dimensions
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> result_percent = transform_percent(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data with percent parameters
>>> # Since keep_size=True, image dimensions remain the same (100x100)
>>> transformed_image_pct = result_percent['image']
>>> transformed_mask_pct = result_percent['mask']
>>> transformed_bboxes_pct = result_percent['bboxes']
>>> transformed_bbox_labels_pct = result_percent['bbox_labels']
>>> transformed_keypoints_pct = result_percent['keypoints']
>>> transformed_keypoint_labels_pct = result_percent['keypoint_labels']
>>>
>>> # Example 3: Random padding within a range
>>> # Pad top and bottom by 5-15%, left and right by 10-20%
>>> transform_random = A.Compose([
... A.CropAndPad(
... percent=[(0.05, 0.15), (0.1, 0.2), (0.05, 0.15), (0.1, 0.2)], # (top, right, bottom, left)
... sample_independently=True, # Sample each side independently
... border_mode=cv2.BORDER_CONSTANT,
... fill=0, # Black padding
... keep_size=False,
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Result dimensions will vary based on the random padding values chosen
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
px: PxType | None
percent: PercentType | None
keep_size: bool
sample_independently: bool
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
@model_validator(mode="after")
def _check_px_percent(self) -> Self:
if self.px is None and self.percent is None:
msg = "Both px and percent parameters cannot be None simultaneously."
raise ValueError(msg)
if self.px is not None and self.percent is not None:
msg = "Only px or percent may be set!"
raise ValueError(msg)
return self
def __init__(
self,
px: int | list[int] | None = None,
percent: float | list[float] | None = None,
keep_size: bool = True,
sample_independently: bool = True,
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
p: float = 1.0,
):
super().__init__(p=p)
self.px = px
self.percent = percent
self.border_mode = border_mode
self.fill = fill
self.fill_mask = fill_mask
self.keep_size = keep_size
self.sample_independently = sample_independently
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
def apply(
self,
img: np.ndarray,
crop_params: Sequence[int],
pad_params: Sequence[int],
fill: tuple[float, ...] | float,
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to an image.
Args:
img (np.ndarray): The image to apply the crop and pad transform to.
crop_params (Sequence[int]): The parameters for the crop.
pad_params (Sequence[int]): The parameters for the pad.
fill (tuple[float, ...] | float): The value to fill the image with.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The image after the crop and pad transform.
"""
return fcrops.crop_and_pad(
img,
crop_params,
pad_params,
fill,
params["shape"][:2],
self.interpolation,
self.border_mode,
self.keep_size,
)
def apply_to_mask(
self,
mask: np.ndarray,
crop_params: Sequence[int],
pad_params: Sequence[int],
fill_mask: tuple[float, ...] | float,
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to a mask.
Args:
mask (np.ndarray): The mask to apply the crop and pad transform to.
crop_params (Sequence[int]): The parameters for the crop.
pad_params (Sequence[int]): The parameters for the pad.
fill_mask (tuple[float, ...] | float): The value to fill the mask with.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The mask after the crop and pad transform.
"""
return fcrops.crop_and_pad(
mask,
crop_params,
pad_params,
fill_mask,
params["shape"][:2],
self.mask_interpolation,
self.border_mode,
self.keep_size,
)
def apply_to_bboxes(
self,
bboxes: np.ndarray,
crop_params: tuple[int, int, int, int],
pad_params: tuple[int, int, int, int],
result_shape: tuple[int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to apply the crop and pad transform to.
crop_params (tuple[int, int, int, int]): The parameters for the crop.
pad_params (tuple[int, int, int, int]): The parameters for the pad.
result_shape (tuple[int, int]): The shape of the result.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The bounding boxes after the crop and pad transform.
"""
return fcrops.crop_and_pad_bboxes(bboxes, crop_params, pad_params, params["shape"][:2], result_shape)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
crop_params: tuple[int, int, int, int],
pad_params: tuple[int, int, int, int],
result_shape: tuple[int, int],
**params: Any,
) -> np.ndarray:
"""Apply the crop and pad transform to keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the crop and pad transform to.
crop_params (tuple[int, int, int, int]): The parameters for the crop.
pad_params (tuple[int, int, int, int]): The parameters for the pad.
result_shape (tuple[int, int]): The shape of the result.
params (dict[str, Any]): Additional parameters for the transform.
Returns:
np.ndarray: The keypoints after the crop and pad transform.
"""
return fcrops.crop_and_pad_keypoints(
keypoints,
crop_params,
pad_params,
params["shape"][:2],
result_shape,
self.keep_size,
)
@staticmethod
def __prevent_zero(val1: int, val2: int, max_val: int) -> tuple[int, int]:
regain = abs(max_val) + 1
regain1 = regain // 2
regain2 = regain // 2
if regain1 + regain2 < regain:
regain1 += 1
if regain1 > val1:
diff = regain1 - val1
regain1 = val1
regain2 += diff
elif regain2 > val2:
diff = regain2 - val2
regain2 = val2
regain1 += diff
return val1 - regain1, val2 - regain2
@staticmethod
def _prevent_zero(crop_params: list[int], height: int, width: int) -> list[int]:
top, right, bottom, left = crop_params
remaining_height = height - (top + bottom)
remaining_width = width - (left + right)
if remaining_height < 1:
top, bottom = CropAndPad.__prevent_zero(top, bottom, height)
if remaining_width < 1:
left, right = CropAndPad.__prevent_zero(left, right, width)
return [max(top, 0), max(right, 0), max(bottom, 0), max(left, 0)]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get the parameters for the crop.
Args:
params (dict[str, Any]): The parameters for the transform.
data (dict[str, Any]): The data for the transform.
Returns:
dict[str, Any]: The parameters for the crop.
"""
height, width = params["shape"][:2]
if self.px is not None:
new_params = self._get_px_params()
else:
percent_params = self._get_percent_params()
new_params = [
int(percent_params[0] * height),
int(percent_params[1] * width),
int(percent_params[2] * height),
int(percent_params[3] * width),
]
pad_params = [max(i, 0) for i in new_params]
crop_params = self._prevent_zero([-min(i, 0) for i in new_params], height, width)
top, right, bottom, left = crop_params
crop_params = [left, top, width - right, height - bottom]
result_rows = crop_params[3] - crop_params[1]
result_cols = crop_params[2] - crop_params[0]
if result_cols == width and result_rows == height:
crop_params = []
top, right, bottom, left = pad_params
pad_params = [top, bottom, left, right]
if any(pad_params):
result_rows += top + bottom
result_cols += left + right
else:
pad_params = []
return {
"crop_params": crop_params or None,
"pad_params": pad_params or None,
"fill": None if pad_params is None else self._get_pad_value(self.fill),
"fill_mask": None
if pad_params is None
else self._get_pad_value(cast("Union[tuple[float, ...], float]", self.fill_mask)),
"result_shape": (result_rows, result_cols),
}
def _get_px_params(self) -> list[int]:
if self.px is None:
msg = "px is not set"
raise ValueError(msg)
if isinstance(self.px, int):
return [self.px] * 4
if len(self.px) == PAIR:
if self.sample_independently:
return [self.py_random.randrange(*self.px) for _ in range(4)]
px = self.py_random.randrange(*self.px)
return [px] * 4
if isinstance(self.px[0], int):
return self.px
if len(self.px[0]) == PAIR:
return [self.py_random.randrange(*i) for i in self.px]
return [self.py_random.choice(i) for i in self.px]
def _get_percent_params(self) -> list[float]:
if self.percent is None:
msg = "percent is not set"
raise ValueError(msg)
if isinstance(self.percent, float):
params = [self.percent] * 4
elif len(self.percent) == PAIR:
if self.sample_independently:
params = [self.py_random.uniform(*self.percent) for _ in range(4)]
else:
px = self.py_random.uniform(*self.percent)
params = [px] * 4
elif isinstance(self.percent[0], (int, float)):
params = self.percent
elif len(self.percent[0]) == PAIR:
params = [self.py_random.uniform(*i) for i in self.percent]
else:
params = [self.py_random.choice(i) for i in self.percent]
return params # params = [top, right, bottom, left]
def _get_pad_value(
self,
fill: Sequence[float] | float,
) -> int | float:
if isinstance(fill, (list, tuple)):
if len(fill) == PAIR:
a, b = fill
if isinstance(a, int) and isinstance(b, int):
return self.py_random.randint(a, b)
return self.py_random.uniform(a, b)
return self.py_random.choice(fill)
if isinstance(fill, (int, float)):
return fill
msg = "fill should be a number or list, or tuple of two numbers."
raise ValueError(msg)
class RandomCropFromBorders(BaseCrop):
"""Randomly crops the input from its borders without resizing.
This transform randomly crops parts of the input (image, mask, bounding boxes, or keypoints)
from each of its borders. The amount of cropping is specified as a fraction of the input's
dimensions for each side independently.
Args:
crop_left (float): The maximum fraction of width to crop from the left side.
Must be in the range [0.0, 1.0]. Default: 0.1
crop_right (float): The maximum fraction of width to crop from the right side.
Must be in the range [0.0, 1.0]. Default: 0.1
crop_top (float): The maximum fraction of height to crop from the top.
Must be in the range [0.0, 1.0]. Default: 0.1
crop_bottom (float): The maximum fraction of height to crop from the bottom.
Must be in the range [0.0, 1.0]. Default: 0.1
p (float): Probability of applying the transform. Default: 1.0
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The actual amount of cropping for each side is randomly chosen between 0 and
the specified maximum for each application of the transform.
- The sum of crop_left and crop_right must not exceed 1.0, and the sum of
crop_top and crop_bottom must not exceed 1.0. Otherwise, a ValueError will be raised.
- This transform does not resize the input after cropping, so the output dimensions
will be smaller than the input dimensions.
- Bounding boxes that end up fully outside the cropped area will be removed.
- Keypoints that end up outside the cropped area will be removed.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Define transform with crop fractions for each border
>>> transform = A.Compose([
... A.RandomCropFromBorders(
... crop_left=0.1, # Max 10% crop from left
... crop_right=0.2, # Max 20% crop from right
... crop_top=0.15, # Max 15% crop from top
... crop_bottom=0.05, # Max 5% crop from bottom
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply transform
>>> result = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Access transformed data
>>> transformed_image = result['image'] # Reduced size image with borders cropped
>>> transformed_mask = result['mask'] # Reduced size mask with borders cropped
>>> transformed_bboxes = result['bboxes'] # Bounding boxes adjusted to new dimensions
>>> transformed_bbox_labels = result['bbox_labels'] # Bounding box labels after crop
>>> transformed_keypoints = result['keypoints'] # Keypoints adjusted to new dimensions
>>> transformed_keypoint_labels = result['keypoint_labels'] # Keypoint labels after crop
>>>
>>> # The resulting output shapes will be smaller, with dimensions reduced by
>>> # the random crop amounts from each side (within the specified maximums)
>>> print(f"Original image shape: (100, 100, 3)")
>>> print(f"Transformed image shape: {transformed_image.shape}") # e.g., (85, 75, 3)
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
crop_left: float = Field(
ge=0.0,
le=1.0,
)
crop_right: float = Field(
ge=0.0,
le=1.0,
)
crop_top: float = Field(
ge=0.0,
le=1.0,
)
crop_bottom: float = Field(
ge=0.0,
le=1.0,
)
@model_validator(mode="after")
def _validate_crop_values(self) -> Self:
if self.crop_left + self.crop_right > 1.0:
msg = "The sum of crop_left and crop_right must be <= 1."
raise ValueError(msg)
if self.crop_top + self.crop_bottom > 1.0:
msg = "The sum of crop_top and crop_bottom must be <= 1."
raise ValueError(msg)
return self
def __init__(
self,
crop_left: float = 0.1,
crop_right: float = 0.1,
crop_top: float = 0.1,
crop_bottom: float = 0.1,
p: float = 1.0,
):
super().__init__(p=p)
self.crop_left = crop_left
self.crop_right = crop_right
self.crop_top = crop_top
self.crop_bottom = crop_bottom
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
"""Get the parameters for the crop.
Args:
params (dict[str, Any]): The parameters for the transform.
data (dict[str, Any]): The data for the transform.
Returns:
dict[str, tuple[int, int, int, int]]: The parameters for the crop.
"""
height, width = params["shape"][:2]
x_min = self.py_random.randint(0, int(self.crop_left * width))
x_max = self.py_random.randint(max(x_min + 1, int((1 - self.crop_right) * width)), width)
y_min = self.py_random.randint(0, int(self.crop_top * height))
y_max = self.py_random.randint(max(y_min + 1, int((1 - self.crop_bottom) * height)), height)
crop_coords = x_min, y_min, x_max, y_max
return {"crop_coords": crop_coords}
class AtLeastOneBBoxRandomCrop(BaseCrop):
"""Crop an area from image while ensuring at least one bounding box is present in the crop.
Similar to BBoxSafeRandomCrop, but with a key difference:
- BBoxSafeRandomCrop ensures ALL bounding boxes are preserved in the crop
- AtLeastOneBBoxRandomCrop ensures AT LEAST ONE bounding box is present in the crop
This makes AtLeastOneBBoxRandomCrop more flexible for scenarios where:
- You want to focus on individual objects rather than all objects
- You're willing to lose some bounding boxes to get more varied crops
- The image has many bounding boxes and keeping all of them would be too restrictive
The algorithm:
1. If bounding boxes exist:
- Randomly selects a reference bounding box from available boxes
- Computes an eroded version of this box (shrunk by erosion_factor)
- Calculates valid crop bounds that ensure overlap with the eroded box
- Randomly samples crop coordinates within these bounds
2. If no bounding boxes exist:
- Uses full image dimensions as valid bounds
- Randomly samples crop coordinates within these bounds
Args:
height (int): Fixed height of the crop
width (int): Fixed width of the crop
erosion_factor (float, optional): Factor by which to erode (shrink) the reference
bounding box when computing valid crop regions. Must be in range [0.0, 1.0].
- 0.0 means no erosion (crop must fully contain the reference box)
- 1.0 means maximum erosion (crop can be anywhere that intersects the reference box)
Defaults to 0.0.
p (float, optional): Probability of applying the transform. Defaults to 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Raises:
CropSizeError: If requested crop size exceeds image dimensions
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (300, 300, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (300, 300), dtype=np.uint8)
>>> # Create multiple bounding boxes - the transform will ensure at least one is in the crop
>>> bboxes = np.array([
... [30, 50, 100, 140], # first box
... [150, 120, 270, 250], # second box
... [200, 30, 280, 90] # third box
... ], dtype=np.float32)
>>> bbox_labels = [1, 2, 3]
>>> keypoints = np.array([
... [50, 70], # keypoint inside first box
... [190, 170], # keypoint inside second box
... [240, 60] # keypoint inside third box
... ], dtype=np.float32)
>>> keypoint_labels = [0, 1, 2]
>>>
>>> # Define transform with different erosion_factor values
>>> transform = A.Compose([
... A.AtLeastOneBBoxRandomCrop(
... height=200,
... width=200,
... erosion_factor=0.2, # Allows moderate flexibility in crop placement
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Shape: (200, 200, 3)
>>> transformed_mask = transformed['mask'] # Shape: (200, 200)
>>> transformed_bboxes = transformed['bboxes'] # At least one bbox is guaranteed
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for the preserved bboxes
>>> transformed_keypoints = transformed['keypoints'] # Only keypoints in crop are kept
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Their labels
>>>
>>> # Verify that at least one bounding box was preserved
>>> assert len(transformed_bboxes) > 0, "Should have at least one bbox in the crop"
>>>
>>> # With erosion_factor=0.0, the crop must fully contain the selected reference bbox
>>> conservative_transform = A.Compose([
... A.AtLeastOneBBoxRandomCrop(
... height=200,
... width=200,
... erosion_factor=0.0, # No erosion - crop must fully contain a bbox
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
>>>
>>> # With erosion_factor=1.0, the crop must only intersect with the selected reference bbox
>>> flexible_transform = A.Compose([
... A.AtLeastOneBBoxRandomCrop(
... height=200,
... width=200,
... erosion_factor=1.0, # Maximum erosion - crop only needs to intersect a bbox
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
Note:
- Uses fixed crop dimensions (height and width)
- Bounding boxes that end up partially outside the crop will be adjusted
- Bounding boxes that end up completely outside the crop will be removed
- If no bounding boxes are provided, acts as a regular random crop
"""
_targets = ALL_TARGETS
class InitSchema(BaseCrop.InitSchema):
height: Annotated[int, Field(ge=1)]
width: Annotated[int, Field(ge=1)]
erosion_factor: Annotated[float, Field(ge=0.0, le=1.0)]
def __init__(
self,
height: int,
width: int,
erosion_factor: float = 0.0,
p: float = 1.0,
):
super().__init__(p=p)
self.height = height
self.width = width
self.erosion_factor = erosion_factor
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
"""Get the parameters for the crop.
Args:
params (dict[str, Any]): The parameters for the transform.
data (dict[str, Any]): The data for the transform.
"""
image_height, image_width = params["shape"][:2]
bboxes = data.get("bboxes", [])
if self.height > image_height or self.width > image_width:
raise CropSizeError(
f"Crop size (height, width) exceeds image dimensions (height, width):"
f" {(self.height, self.width)} vs {image_height, image_width}",
)
if len(bboxes) > 0:
bboxes = denormalize_bboxes(bboxes, shape=(image_height, image_width))
# Pick a bbox amongst all possible as our reference bbox.
reference_bbox = self.py_random.choice(bboxes)
bbox_x1, bbox_y1, bbox_x2, bbox_y2 = reference_bbox[:4]
# Compute valid crop bounds:
# erosion_factor = 0.0: crop must fully contain the bbox
# erosion_factor = 1.0: crop can be anywhere that intersects the bbox
if self.erosion_factor < 1.0:
# Regular case: compute eroded box dimensions
bbox_width = bbox_x2 - bbox_x1
bbox_height = bbox_y2 - bbox_y1
eroded_width = bbox_width * (1.0 - self.erosion_factor)
eroded_height = bbox_height * (1.0 - self.erosion_factor)
min_crop_x = np.clip(
a=bbox_x1 + eroded_width - self.width,
a_min=0.0,
a_max=image_width - self.width,
)
max_crop_x = np.clip(
a=bbox_x2 - eroded_width,
a_min=0.0,
a_max=image_width - self.width,
)
min_crop_y = np.clip(
a=bbox_y1 + eroded_height - self.height,
a_min=0.0,
a_max=image_height - self.height,
)
max_crop_y = np.clip(
a=bbox_y2 - eroded_height,
a_min=0.0,
a_max=image_height - self.height,
)
else:
# Maximum erosion case: crop can be anywhere that intersects the bbox
min_crop_x = np.clip(
a=bbox_x1 - self.width, # leftmost position that still intersects
a_min=0.0,
a_max=image_width - self.width,
)
max_crop_x = np.clip(
a=bbox_x2, # rightmost position that still intersects
a_min=0.0,
a_max=image_width - self.width,
)
min_crop_y = np.clip(
a=bbox_y1 - self.height, # topmost position that still intersects
a_min=0.0,
a_max=image_height - self.height,
)
max_crop_y = np.clip(
a=bbox_y2, # bottommost position that still intersects
a_min=0.0,
a_max=image_height - self.height,
)
else:
# If there are no bboxes, just crop anywhere in the image.
min_crop_x = 0.0
max_crop_x = image_width - self.width
min_crop_y = 0.0
max_crop_y = image_height - self.height
# Randomly draw the upper-left corner of the crop.
crop_x1 = int(self.py_random.uniform(a=min_crop_x, b=max_crop_x))
crop_y1 = int(self.py_random.uniform(a=min_crop_y, b=max_crop_y))
crop_x2 = crop_x1 + self.width
crop_y2 = crop_y1 + self.height
return {"crop_coords": (crop_x1, crop_y1, crop_x2, crop_y2)}
|