Skip to content

NII — NIfTI Image Wrapper

The NII class is the central image abstraction in TPTBox. It wraps a nibabel Nifti1Image and exposes reorientation, resampling, masking, arithmetic, and I/O operations through a consistent interface.

NII

TPTBox.core.nii_wrapper.NII

Bases: NII_Math

The NII class represents a NIfTI image and provides various methods for manipulating and analyzing NIfTI images. It supports loading and saving NIfTI images, rescaling and reorienting images, applying operations on segmentation masks, and more.

Example Usage:

# Create an instance of NII class
nii = NII(nib.load('image.nii.gz'),seg=False)

# Get the shape of the image
shape = nii.shape

# Rescale the image to a new voxel spacing
rescaled = nii.rescale(voxel_spacing=(1, 1, 1))

# Reorient the image to a new orientation
reoriented = nii.reorient(axcodes_to=("P", "I", "R"))

# Apply a segmentation mask to the image
masked = nii.apply_mask(mask)

# Save the image to a new file
nii.save('output.nii.gz')

Main functionalities: - Loading and saving NIfTI images - Rescaling and reorienting images - Applying operations on segmentation masks

Methods: - load: Loads a NIfTI image from a file - load_bids: Loads a NIfTI image from a BIDS file - shape: Returns the shape of the image - dtype: Returns the data type of the image - header: Returns the header of the image - affine: Returns the affine transformation matrix of the image - orientation: Returns the orientation of the image - zoom: Returns the voxel sizes of the image - origin: Returns the origin of the image - rotation: Returns the rotation matrix of the image - reorient: Reorients the image to a new orientation - rescale: Rescales the image to a new voxel spacing - apply_mask: Applies a segmentation mask to the image - save: Saves the image to a file

Fields: - nii: The NIfTI image object - seg: A flag indicating whether the image is a segmentation mask - c_val: The default value for the segmentation mask

Note: This class assumes that the input NIfTI images are in the NIfTI-1 format.

Source code in TPTBox/core/nii_wrapper.py
 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
class NII(NII_Math):
    """The `NII` class represents a NIfTI image and provides various methods for manipulating and analyzing NIfTI images. It supports loading and saving NIfTI images, rescaling and reorienting images, applying operations on segmentation masks, and more.

    Example Usage:
    ```python
    # Create an instance of NII class
    nii = NII(nib.load('image.nii.gz'),seg=False)

    # Get the shape of the image
    shape = nii.shape

    # Rescale the image to a new voxel spacing
    rescaled = nii.rescale(voxel_spacing=(1, 1, 1))

    # Reorient the image to a new orientation
    reoriented = nii.reorient(axcodes_to=("P", "I", "R"))

    # Apply a segmentation mask to the image
    masked = nii.apply_mask(mask)

    # Save the image to a new file
    nii.save('output.nii.gz')
    ```

    Main functionalities:
    - Loading and saving NIfTI images
    - Rescaling and reorienting images
    - Applying operations on segmentation masks

    Methods:
    - `load`: Loads a NIfTI image from a file
    - `load_bids`: Loads a NIfTI image from a BIDS file
    - `shape`: Returns the shape of the image
    - `dtype`: Returns the data type of the image
    - `header`: Returns the header of the image
    - `affine`: Returns the affine transformation matrix of the image
    - `orientation`: Returns the orientation of the image
    - `zoom`: Returns the voxel sizes of the image
    - `origin`: Returns the origin of the image
    - `rotation`: Returns the rotation matrix of the image
    - `reorient`: Reorients the image to a new orientation
    - `rescale`: Rescales the image to a new voxel spacing
    - `apply_mask`: Applies a segmentation mask to the image
    - `save`: Saves the image to a file

    Fields:
    - `nii`: The NIfTI image object
    - `seg`: A flag indicating whether the image is a segmentation mask
    - `c_val`: The default value for the segmentation mask

    Note: This class assumes that the input NIfTI images are in the NIfTI-1 format.
    """
    def __init__(self, nii: Nifti1Image|_unpacked_nii, seg=False,c_val=None, desc:str|None=None, info=None) -> None:
        assert nii is not None
        self.__divergent = False
        self._checked_dtype = False
        self.nii = nii
        self.seg:bool = seg
        self.c_val:float|None=c_val # default c_vale if seg is None
        self.__min = None
        self.info = info if info is not None else {}
        self.set_description(desc)
        if seg:
            self._unpack()
            if isinstance(self.dtype,np.floating):
                self.set_dtype_("smallest_uint")


    @classmethod
    def from_numpy(cls, arr: np.ndarray, affine: np.ndarray, seg=False, c_val=None, desc:str|None=None, info=None) -> Self:
        """Creates an NII instance from a numpy array and an affine matrix.

        Args:
            arr: The voxel data array (shape must match the spatial dimensions implied by affine).
            affine: A (4, 4) affine transformation matrix mapping voxel indices to world coordinates.
            seg: Whether the image is a segmentation mask (integer-labelled). Defaults to False.
            c_val: Background / fill value used during resampling. Defaults to None (inferred
                from data for images; 0 for segmentations).
            desc: Optional description string stored in the NIfTI header ``descrip`` field.
            info: Optional dict of arbitrary metadata attached to this instance.

        Returns:
            A new NII wrapping the given array and affine.
        """
        nii = nib.nifti1.Nifti1Image(arr,affine)
        return NII(nii=nii, seg=seg, c_val=c_val, desc=desc, info=info)

    @classmethod
    def load(cls, path: Image_Reference, seg: bool, c_val: float | None = None) -> Self:
        """Loads a NIfTI image from a file path or image reference.

        Args:
            path: File path (str or Path), an existing NII, a Nifti1Image, or a BIDS_FILE
                pointing to the image to load.
            seg: Whether the image is a segmentation mask. When True the array dtype is
                coerced to the smallest unsigned integer type that can hold all values.
            c_val: Background / fill value. Defaults to None.

        Returns:
            A new NII loaded from the given path.
        """
        nii= to_nii(path,seg)
        if seg:
            nii = nii.set_dtype("smallest_uint")
        nii.c_val = c_val
        return nii

    @classmethod
    def load_nrrd(cls, path: str | Path, seg: bool,verbos=False):
        """Load an NRRD file and convert it into a Nifti1Image object.

        Args:
            path (str | Path): The file path to the NRRD file to be loaded.
            seg (bool): A flag indicating if the data represents segmentation data.

        Returns:
            NII: An NII object containing the loaded Nifti1Image and the segmentation flag.

        Raises:
            ImportError: If the `pynrrd` package is not installed.
            FileNotFoundError: If the specified NRRD file cannot be found.

        Example:
            >>> nii = cls.load_nrrd("example.nrrd", seg=True)
            >>> print(nii)
        """
        try:
            import nrrd  # pip install pynrrd, if pynrrd is not already installed
        except ModuleNotFoundError:
            raise ImportError("The `pynrrd` package is required but not installed. Install it with `pip install pynrrd`.") from None
        from TPTBox.core.internal.slicer_nrrd import load_slicer_nrrd
        return load_slicer_nrrd(path,seg,verbos=verbos)
    @classmethod
    def load_bids(cls, nii_bids: bids_files.BIDS_FILE) -> NII:
        """Loads an NII from a BIDS_FILE object, inferring seg and c_val from the format.

        Supports ``.nii``, ``.nii.gz``, ``.nrrd``, and any format readable by SimpleITK.
        The ``seg`` flag is set to True when the BIDS file's interpolation order is 0
        (i.e., it is a label map). CT images default to ``c_val=-1024``; others to 0.

        Args:
            nii_bids: A BIDS_FILE whose ``file`` dict contains at least one of the
                supported image format keys.

        Returns:
            A new NII loaded from the BIDS file.

        Raises:
            AssertionError: If no readable image format is found in ``nii_bids``.
        """
        nifty = None
        if "nii" in nii_bids.file:
            path = nii_bids.file['nii']
            nifty = nib.load(path)
        elif "nii.gz" in nii_bids.file:
            path = nii_bids.file['nii.gz']
            nifty = nib.load(path)
        elif "nrrd" in nii_bids.file:
            path = nii_bids.file['nrrd']
            nifty = NII.load_nrrd(path,seg=False)
        else:
            import SimpleITK as sitk  # noqa: N813

            from TPTBox.core.sitk_utils import sitk_to_nib
            for f in nii_bids.file:
                try:
                    img = sitk.ReadImage(nii_bids.file[f])
                    nifty =  sitk_to_nib(img)
                except Exception:
                    pass
                break
        if nii_bids.get_interpolation_order() == 0:
            seg = True
            c_val=0
        else:
            seg = False
            c_val = -1024 if "ct" in nii_bids.format.lower() else 0
        assert nifty is not None, f"could not find {nii_bids}"
        return NII(nifty,seg,c_val) # type: ignore
    def _unpack(self) -> None:
        """Materialises the lazy nibabel dataobj into an in-memory numpy array."""
        try:
            if self.__unpacked:
                return
            try:
                #if arr.dtype.fields is not None:  # structured dtype (RGB)
                #    arr = np.stack([arr[name] for name in arr.dtype.names], axis=-1)
                if not self._checked_dtype or self.seg:
                    dtype = _check_if_nifty_is_lying_about_its_dtype(self)
                    #print("unpack-nii",f"{self.seg=}",dtype)
                    self._checked_dtype = True
                    self._arr = np.asanyarray(self.nii.dataobj, dtype=dtype).copy()
                else:
                    self._arr = np.asanyarray(self.nii.dataobj, dtype=self.nii.dataobj.dtype).copy() #type: ignore
            except np.exceptions.DTypePromotionError:
                arr = np.asarray(self.nii.dataobj)
                if arr.dtype.fields is not None:  # structured dtype (RGB)
                    self._arr = np.stack([arr[name] for name in arr.dtype.names], axis=-1)
                else:
                    raise np.exceptions.DTypePromotionError(f"The DTypes <class '{self.nii.dataobj.dtype}'> do not have a common numerical DType. {np.asarray(self.nii.dataobj)}") from None

            self._aff = self.nii.affine
            self._header:Nifti1Header = self.nii.header # type: ignore
            self.__unpacked = True
        except EOFError as e:
            raise EOFError(f"{self.nii.get_filename()}: {e!s}\nThe file is probably brocken beyond repair, due killing a software during nifty saving.") from None
        except zlib.error as e:
            raise EOFError(f"{self.nii.get_filename()}: {e!s}\nThe file is probably brocken beyond repair, due killing a software during nifty saving.") from None
        except OSError as e:
            raise EOFError(f"{self.nii.get_filename()}: {e!s}\nThe file is probably brocken beyond repair, due killing a software during nifty saving.") from None
    @property
    def nii_abstract(self) -> Nifti1Image|_unpacked_nii:
        """Returns the internal representation without forcing reconstruction of the Nifti1Image.

        If the data has been unpacked (loaded into memory), returns the ``(array, affine, header)``
        tuple. Otherwise returns the raw ``Nifti1Image``.
        """
        if self.__unpacked:
            return self._arr,self.affine,self.header
        return self._nii

    @property
    def nii(self) -> Nifti1Image:
        """Returns the underlying Nifti1Image, reconstructing it if the in-memory array has diverged.

        The reconstruction synchronises the header dtype and slope/intercept values with the
        current array. Use ``nii_abstract`` if you want to avoid this reconstruction overhead.
        """
        if self.__divergent:
            self._nii = Nifti1Image(self._arr,self.affine,self.header)
            if self.dtype == self._arr.dtype: #type: ignore
                nii = Nifti1Image(self._arr,self.affine,self.header)
            else:
                if not suppress_dtype_change_printout_in_set_array:
                    log.print(f"'set_array' with different dtype: from {self.dtype} to {self._arr.dtype}",verbose=True) #type: ignore
                nii2 = Nifti1Image(self._arr,self.affine,self.header)
                nii2.set_data_dtype(self._arr.dtype)
                nii = Nifti1Image(self._arr,nii2.affine,nii2.header) # type: ignore
            if all(a is None for a in self.header.get_slope_inter()):
                nii.header.set_slope_inter(1,self.get_c_val()) # type: ignore
            #if self.header is not None:
            #    self.header.set_sform(self.affine, code=1)

            self._nii = nii
            self.__divergent = False
        return self._nii
    @nii.setter
    def nii(self,nii:Nifti1Image|_unpacked_nii):
        if isinstance(nii,tuple):
            assert len(nii) == 3, nii
            self.__divergent = True
            self.__unpacked = True
            arr, aff, header = nii
            n = aff.shape[0]-1
            if header is None or n != header['dim'][0]:
                header = None
            if len(arr.shape) != n:
                # is there a dimesion with size 1?
                arr = arr.squeeze()
                # TODO try to get back to a saveabel state, if this did not work
            if arr.dtype == np.uint64:#throws error
                arr = arr.astype(np.uint32)
            if arr.dtype == np.int64:#throws error
                arr = arr.astype(np.int32)
            self._arr = arr
            self._aff = aff
            self._checked_dtype = True
            if header is not None:
                header = header.copy()
                header.set_sform(aff, code='aligned')
                header.set_qform(aff, code='unknown')
                header.set_data_dtype(arr.dtype)
                rotation_zoom = aff[:n, :n]
                zoom = np.sqrt(np.sum(rotation_zoom * rotation_zoom, axis=0))
                #print(aff.shape,arr.shape,zoom)
                header.set_zooms(zoom)
                self._header = header
                return
            else:
                nii = Nifti1Image(arr,aff)
        self.__unpacked = False
        self.__divergent = False
        self._nii = nii

    @property
    def shape(self) -> tuple[int, int, int]:
        """Spatial shape of the image array (x, y, z), or more dims for 4-D images."""
        if self.__unpacked:
            return tuple(self._arr.shape) # type: ignore
        return self.nii.shape # type: ignore
    @property
    def dtype(self) -> type:
        """NumPy dtype of the voxel data array."""
        if self.__unpacked:
            return self._arr.dtype # type: ignore
        return self.nii.dataobj.dtype #type: ignore
    @dtype.setter
    def dtype(self, dtype:type):
        self.set_dtype_(dtype)
    @property
    def header(self) -> Nifti1Header:
        """NIfTI-1 header associated with this image."""
        if self.__unpacked:
            return self._header
        return self.nii.header  # type: ignore
    @property
    def affine(self) -> AFFINE:
        """(4, 4) affine matrix mapping voxel indices to world (mm) coordinates."""
        if self.__unpacked:
            return self._aff # type: ignore
        return self.nii.affine # type: ignore

    @affine.setter
    def affine(self,affine:np.ndarray):
        self._unpack()
        self.__divergent = True
        self._aff = affine
    @property
    def orientation(self) -> AX_CODES:
        """Axis codes describing the image orientation, e.g. ``('R', 'A', 'S')``."""
        ort = nio.io_orientation(self.affine)
        return nio.ornt2axcodes(ort) # type: ignore
    @orientation.setter
    def orientation(self, value: AX_CODES):
        self.reorient_(value, verbose=False)
    @property
    def dims(self) -> int:
        """Number of spatial dimensions (typically 3 for a standard NIfTI volume)."""
        self._unpack()
        return self.affine.shape[0]-1
    @property
    def zoom(self) -> ZOOMS:
        """Voxel sizes in mm along each spatial axis, e.g. ``(1.0, 1.0, 1.5)``."""
        n = self.dims
        rotation_zoom = self.affine[:n, :n]
        zoom = np.sqrt(np.sum(rotation_zoom * rotation_zoom, axis=0)) if self.__divergent else self.header.get_zooms()

        z = tuple(np.round(zoom,7))
        if len(z) >= n:
            z = z[:n]
        #assert len(z) == 3,z
        return z # type: ignore
    @zoom.setter
    def zoom(self, value: tuple[float, float, float]):
        self.rescale_(value, verbose=False)

    @property
    def origin(self) -> tuple[float, float, float]:
        """World-space coordinates (in mm) of voxel index (0, 0, 0)."""
        n = self.dims
        z = tuple(np.round(self.affine[:n,n],7))
        assert len(z) == 3
        return z # type: ignore
    @origin.setter
    def origin(self,x:tuple[float, float, float]):
        n = self.dims
        self._unpack()
        self.__divergent = True
        affine = self._aff
        affine[:n,n] = np.array(x) # type: ignore
        self._aff = affine
    @property
    def rotation(self) -> np.ndarray:
        """Pure rotation matrix extracted from the affine (affine upper-left block divided by zoom)."""
        n = self.dims
        rotation_zoom = self.affine[:n, :n]
        zoom = np.array(self.zoom)
        rotation = rotation_zoom / zoom
        return rotation

    @property
    def direction(self) -> list:
        """Flattened rotation matrix as a list (row-major), compatible with ITK/SimpleITK conventions."""
        direction_matrix = self.rotation
        direction_flat = direction_matrix.flatten().tolist()
        return direction_flat
    @property
    def direction_itk(self) -> list:
        """Flattened rotation matrix with ITK LPS sign convention (first two rows negated)."""
        a = np.array(self.direction)
        a[:len(a)//3*2]*=-1
        return a.tolist()


    def split_4D_image_to_3D(self) -> list[NII]:
        """Splits a 4-D NIfTI image into a list of 3-D NII objects, one per volume.

        Returns:
            A list of NII objects, each containing one 3-D volume from the 4-D image.
            The affine, header, seg flag, and c_val are copied from the original.

        Raises:
            AssertionError: If the image is not 4-D.
        """
        assert self.get_num_dims() == 4,self.get_num_dims()
        arr_4d = self.get_array()
        out:list[NII] = []
        for i in range(self.shape[-1]):
            arr = arr_4d[...,i]
            out.append(NII(Nifti1Image(arr, self.affine, self.header.copy()),self.seg,self.c_val,self.header['descrip']))
        return out


    @property
    def orientation_ornt(self) -> np.ndarray:
        """Nibabel orientation array (shape ``(ndim, 2)``) encoding axis permutation and flip."""
        return nio.io_orientation(self.affine)

    def set_description(self, v: str | None) -> None:
        """Writes a description string into the NIfTI header ``descrip`` field.

        Args:
            v: Description string. When None, defaults to ``"seg"`` for segmentations
                and ``"img"`` for regular images.
        """
        if v is None:
            self.header['descrip'] = "seg" if self.seg else "img"
        else:
            self.header['descrip'] = v

    def get_c_val(self, default: float | None = None) -> float:
        """Returns the background / fill value for this image.

        For segmentations the fill value is always 0. For images it is resolved from
        ``self.c_val``, the ``default`` argument, or the minimum value of the array
        (computed lazily and cached), in that order.

        Args:
            default: Fallback value if ``self.c_val`` is None. Defaults to None.

        Returns:
            The background fill value as a float.
        """
        if self.seg:
            return 0
        if self.c_val is not None:
            return self.c_val
        if default is not None:
            return default
        if self.__min is None:
            self.__min = self.min()
        return self.__min

    def get_seg_array(self) -> np.ndarray:
        """Returns a copy of the voxel array, emitting a warning if ``seg`` is False.

        Returns:
            A copy of the underlying numpy array interpreted as a segmentation mask.
        """
        if not self.seg:
            warnings.warn(
                "requested a segmentation array, but NII is not set as a segmentation", UserWarning, stacklevel=5
            )
        self._unpack()
        return self._arr.copy() #type: ignore
    def get_array(self) -> np.ndarray:
        """Returns a copy of the voxel data array.

        Delegates to ``get_seg_array`` when ``seg=True`` (which adds a warning if
        the flag is inconsistent), otherwise returns a plain copy.

        Returns:
            A copy of the underlying numpy array.
        """
        if self.seg:
            return self.get_seg_array()
        self._unpack()
        return self._arr.copy()
    def numpy(self, *_args) -> np.ndarray:
        """Returns a copy of the voxel data as a numpy array (alias for ``get_array``)."""
        return self.get_array()
    def set_array(self, arr: np.ndarray | Self, inplace=False, verbose: logging = False, seg=None) -> Self:  # noqa: ARG002
        """Returns an NII whose voxel data is replaced by ``arr``, preserving affine and header.

        Note: This function works out-of-place by default, like all other methods.

        Args:
            arr: New voxel data. May be a numpy array or another NII (in which case
                ``get_array()`` is called automatically). Boolean arrays are cast to
                ``uint8``; float16 to float32; floating arrays are cast to int32 when
                ``self.seg`` is True.
            inplace: If True, modifies this NII in place and returns ``self``.
                Defaults to False.
            verbose: Controls verbosity of dtype-change log messages. Defaults to False.
            seg: Override the ``seg`` flag on the returned/modified NII. Defaults to None
                (keep the current value).

        Returns:
            The modified NII (``self`` when ``inplace=True``, a new NII otherwise).
        """
        if hasattr(arr,"get_array"):
            arr = arr.get_array() # type: ignore
        if arr.dtype == bool:
            arr = arr.astype(np.uint8)
        if arr.dtype == np.float16:
            arr = arr.astype(np.float32)
        if self.seg and isinstance(arr, (np.floating, float)):
            arr = arr.astype(np.int32)
        #if self.dtype == arr.dtype: #type: ignore
        nii:_unpacked_nii = (arr,self.affine,self.header.copy())
        self.header.set_data_dtype(arr.dtype)
        #else:
        #    if not suppress_dtype_change_printout_in_set_array:
        #        log.print(f"'set_array' with different dtype: from {self.nii.dataobj.dtype} to {arr.dtype}",verbose=verbose) #type: ignore
        #    nii2 = Nifti1Image(self.get_array(),self.affine,self.header)
        #    nii2.set_data_dtype(arr.dtype)
        #    nii = (arr,nii2.affine,nii2.header) # type: ignore
        #if all(a is None for a in self.header.get_slope_inter()):
        #    nii.header.set_slope_inter(1,self.get_c_val()) # type: ignore
        if inplace:
            if seg is not None:
                self.seg = seg
            self.nii = nii
            return self
        else:
            return self.copy(nii,seg=seg) # type: ignore

    def set_array_(self, arr: np.ndarray, verbose: logging = True) -> Self:
        """In-place variant of `set_array`."""
        return self.set_array(arr,inplace=True,verbose=verbose)
    def set_dtype(self, dtype: type | Literal['smallest_int', 'smallest_uint'] = np.float32, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe", inplace=False) -> Self:
        """Returns an NII with the voxel array cast to a different dtype.

        Args:
            dtype: Target dtype. The special strings ``"smallest_uint"`` and
                ``"smallest_int"`` select the smallest unsigned or signed integer
                type that can hold all values in the current array.
                Defaults to ``np.float32``.
            order: Memory layout order passed to ``ndarray.astype``. Defaults to ``"K"``.
            casting: Casting rule passed to ``ndarray.astype``. Defaults to ``"unsafe"``.
            inplace: If True, converts in place and returns ``self``. Defaults to False.

        Returns:
            The NII with the new dtype (``self`` when ``inplace=True``, a new NII otherwise).
        """
        sel = self if inplace else self.copy()
        if dtype == "smallest_uint":
            arr = self.get_array()
            if arr.max()<256:
                dtype = np.uint8
            elif arr.max()<65536:
                dtype = np.uint16
            else:
                dtype = np.int32
        elif dtype == "smallest_int":
            arr = self.get_array()
            if arr.max()<128:
                dtype = np.int8
            elif arr.max()<32768:
                dtype = np.int16
            else:
                dtype = np.int32
        if self.__unpacked:
            self._unpack()
            sel._arr = sel._arr.astype(dtype)
            sel.header.set_data_dtype(dtype)
        else:
            sel.nii.set_data_dtype(dtype)
            if sel.nii.get_data_dtype() != self.dtype: #type: ignore
                sel.nii = Nifti1Image(self.get_array().astype(dtype,casting=casting,order=order),self.affine,self.header)

        return sel
    def set_dtype_(self, dtype: type | Literal['smallest_uint', 'smallest_int'] = np.float32, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe") -> Self:
        """In-place variant of `set_dtype`."""
        return self.set_dtype(dtype=dtype,order=order,casting=casting, inplace=True)

    def astype(self, dtype, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe", subok=True, copy=True) -> Self:
        """NumPy-compatible dtype conversion wrapper.

        When ``subok=True`` (default), delegates to ``set_dtype`` and returns an NII.
        When ``subok=False``, returns a plain numpy array.

        Args:
            dtype: Target dtype, forwarded to ``set_dtype`` or ``ndarray.astype``.
            order: Memory layout order. Defaults to ``"K"``.
            casting: Casting rule. Defaults to ``"unsafe"``.
            subok: If True, returns an NII; if False, returns a numpy array.
                Defaults to True.
            copy: When ``subok=True`` this maps to ``inplace`` (copy=True → inplace=True).
                Defaults to True.

        Returns:
            An NII or numpy array with the requested dtype.
        """
        if subok:
            c = self.set_dtype(dtype,order=order,casting=casting, inplace=copy)
            return c
        else:
            return self.get_array().astype(dtype,order=order,casting=casting, subok=subok,copy=copy)
    def reorient(self:Self, axcodes_to: AX_CODES|str|None = ("P", "I", "R"), verbose:logging=False, inplace=False)-> Self:
        """Reorients the input Nifti image to the desired orientation, specified by the axis codes.

        Args:
            axcodes_to (tuple): A tuple of three strings representing the desired axis codes. Default value is ("P", "I", "R").
            verbose (bool): If True, prints a message indicating the orientation change. Default value is False.
            inplace (bool): If True, modifies the input image in place. Default value is False.

        Returns:
            If inplace is True, returns None. Otherwise, returns a new instance of the NII class representing the reoriented image.

        Note:
        The nibabel axes codes describe the direction, not the origin, of axes. The direction "PIR+" corresponds to the origin "ASL".
        """
        # Note: nibabel axes codes describe the direction not origin of axes
        # direction PIR+ = origin ASL
        if isinstance(axcodes_to,str):
            axcodes_to = tuple(axcodes_to)
        if axcodes_to is not None:
            aff = self.affine
            ornt_fr = self.orientation_ornt
            arr = self.get_array()
            ornt_to = nio.axcodes2ornt(axcodes_to)
            ornt_trans = nio.ornt_transform(ornt_fr, ornt_to)
            if (ornt_fr == ornt_to).all():
                log.print("Image is already rotated to", axcodes_to,verbose=verbose)
                if inplace:
                    return self
                return self.copy() # type: ignore
            arr = nio.apply_orientation(arr, ornt_trans)
            aff_trans = nio.inv_ornt_aff(ornt_trans, arr.shape)
            new_aff = np.matmul(aff, aff_trans)
            ### Reset origin ###
            flip = ornt_trans[:, 1]
            change = ((-flip) + 1) / 2  # 1 if flip else 0
            change = tuple(a * (s-1) for a, s in zip(change, self.shape))
            new_aff[:3, 3] = nib.affines.apply_affine(aff,change) # type: ignore
            ######
            #if self.header is not None:
            #    self.header.set_sform(new_aff, code=1)
            new_img = arr, new_aff,self.header
            log.print("Image reoriented from", nio.ornt2axcodes(ornt_fr), "to", axcodes_to,verbose=verbose)
        else:
            return self if not inplace else self.copy()
        if inplace:
            self.nii = new_img
            return self

        return self.copy(new_img) # type: ignore
    def reorient_(self: Self, axcodes_to: AX_CODES | None = ("P", "I", "R"), verbose: logging = False) -> Self:
        """In-place variant of `reorient`."""
        if axcodes_to is None:
            return self
        return self.reorient(axcodes_to=axcodes_to, verbose=verbose,inplace=True)


    def compute_crop(self,minimum: float=0, dist: float = 0, use_mm=False, other_crop:tuple[slice,...]|None=None, maximum_size:tuple[slice,...]|int|tuple[int,...]|None=None, raise_error=True)->tuple[slice,slice,slice]:
        """Computes the minimum slice that removes unused space from the image and returns the corresponding slice tuple along with the origin shift required for centroids.

        Args:
            minimum (int): The minimum value of the array (0 for MRI, -1024 for CT). Default value is 0.
            dist (int): The amount of padding to be added to the cropped image. Default value is 0.
            use_mm: dist will be mm instead of number of voxels
            other_crop (tuple[slice,...], optional): A tuple of slice objects representing the slice of an other image to be combined with the current slice. Default value is None.
            raise_error: if crop is empty a "ValueError: bbox_nd: img is empty, cannot calculate a bbox" is produced. When False return None instead.

        Returns:
            ex_slice: A tuple of slice objects that need to be applied to crop the image.
            origin_shift: A tuple of integers representing the shift required to obtain the centroids of the cropped image.

        Note:
            - The computed slice removes the unused space from the image based on the minimum value.
            - The padding is added to the computed slice.
            - If the computed slice reduces the array size to zero, a ValueError is raised.
            - If other_crop is not None, the computed slice is combined with the slice of another image to obtain a common region of interest.
            - Only None slice is supported for combining slices.
        """
        d = np.around(dist / np.asarray(self.zoom)).astype(int) if use_mm else (int(dist),int(dist),int(dist))
        array = self.get_array() #+ minimum

        ex_slice = list(np_bbox_binary(array > minimum, px_dist=d,raise_error=raise_error))

        if other_crop is not None:
            assert all((a.step is None) for a in other_crop), 'Only None slice is supported for combining x'
            ex_slice = [slice(max(a.start, b.start), min(a.stop, b.stop)) for a, b in zip(ex_slice, other_crop)]

        if maximum_size is not None:
            if isinstance(maximum_size,int):
                maximum_size = (maximum_size,maximum_size,maximum_size)
            for i, min_w in enumerate(maximum_size):
                if isinstance(min_w,slice):
                    min_w = min_w.stop - min_w.start  # noqa: PLW2901
                curr_w =  ex_slice[i].stop - ex_slice[i].start
                dif = min_w - curr_w
                if min_w > 0 and dif > 0:
                    new_start = ex_slice[i].start - floor(dif/2)
                    new_goal = ex_slice[i].stop + ceil(dif/2)
                    if new_goal > self.shape[i]:
                        new_start -= new_goal - self.shape[i]
                        new_goal = self.shape[i]
                    if new_start < 0:
                        new_goal -= new_start
                        new_start = 0
                    ex_slice[i] = slice(new_start,new_goal)


        #origin_shift = tuple([int(ex_slice[i].start) for i in range(len(ex_slice))])
        return tuple(ex_slice)# type: ignore

    def apply_center_crop(self, center_shape: tuple[int, int, int], inplace=False, verbose: bool = False) -> Self:
        """Crops (and pads if necessary) the image to the given shape, centred on the image.

        Args:
            center_shape: Desired output shape ``(x, y, z)``. Axes smaller than the
                current image are cropped; axes larger are zero-padded first.
            inplace: If True, modifies this NII in place. Defaults to False.
            verbose: If True, prints the crop/pad operations. Defaults to False.

        Returns:
            The NII cropped/padded to ``center_shape``.
        """
        shp_x, shp_y, shp_z = self.shape
        crop_x, crop_y, crop_z = center_shape
        arr = self.get_array()

        if crop_x > shp_x or crop_y > shp_y or crop_z > shp_z:
            padding_ltrb = [
                ((crop_x - shp_x +1) // 2 if crop_x > shp_x else 0,(crop_x - shp_x) // 2 if crop_x > shp_x else 0),
                ((crop_y - shp_y +1) // 2 if crop_y > shp_y else 0,(crop_y - shp_y) // 2 if crop_y > shp_y else 0),
                ((crop_z - shp_z +1) // 2 if crop_z > shp_z else 0,(crop_z - shp_z) // 2 if crop_z > shp_z else 0),
            ]
            arr_padded = np.pad(arr, padding_ltrb, "constant", constant_values=0)  # PIL uses fill value 0
            log.print(f"Pad from {self.shape} to {arr_padded.shape}", verbose=verbose)
            shp_x, shp_y, shp_z = arr_padded.shape
            if crop_x == shp_x and crop_y == shp_y and crop_z == shp_z:
                return self.set_array(arr_padded)
        else:
            arr_padded = arr

        crop_rel_x = round((shp_x - crop_x) / 2.0)
        crop_rel_y = round((shp_y - crop_y) / 2.0)
        crop_rel_z = round((shp_z - crop_z) / 2.0)

        crop_slices = (slice(crop_rel_x, crop_rel_x + crop_x),slice(crop_rel_y, crop_rel_y + crop_y),slice(crop_rel_z, crop_rel_z + crop_z))
        arr_cropped = arr_padded[crop_slices]
        log.print(f"Center cropped from {arr_padded.shape} to {arr_cropped.shape}", verbose=verbose)
        shp_x, shp_y, shp_z = arr_cropped.shape
        assert crop_x == shp_x and crop_y == shp_y and crop_z == shp_z
        return self.set_array(arr_cropped, inplace=inplace)
        #return self.apply_crop(crop_slices, inplace=inplace)

    def apply_crop_slice(self, *args, **qargs) -> Self:
        """Deprecated alias for `apply_crop`."""
        import warnings
        warnings.warn("apply_crop_slice id deprecated use apply_crop instead",stacklevel=5) #TODO remove in version 1.0
        return self.apply_crop(*args,**qargs)

    def apply_crop_slice_(self, *args, **qargs) -> Self:
        """Deprecated alias for `apply_crop_`."""
        import warnings
        warnings.warn("apply_crop_slice_ id deprecated use apply_crop_ instead",stacklevel=5) #TODO remove in version 1.0
        return self.apply_crop_(*args,**qargs)

    def apply_crop(self,ex_slice:tuple[slice,slice,slice]|Sequence[slice]|None , inplace=False) -> Self:
        """The apply_crop_slice function applies a given slice to reduce the Nifti image volume. If a list of slices is provided, it computes the minimum volume of all slices and applies it.

        Args:
            ex_slice (tuple[slice,slice,slice] | list[tuple[slice,slice,slice]]): A tuple or a list of tuples, where each tuple represents a slice for each axis (x, y, z).
            inplace (bool, optional): If True, it applies the slice to the original image and returns it. If False, it returns a new NII object with the sliced image.

        Returns:
            NII: A new NII object containing the sliced image if inplace=False. Otherwise, it returns the original NII object after applying the slice.
        """
        nii = self.nii.slicer[tuple(ex_slice)] if ex_slice is not None else self.nii_abstract
        if inplace:
            self.nii = nii
            return self
        x= self.copy(nii)
        return x

    def apply_crop_(self, ex_slice: tuple[slice, slice, slice] | Sequence[slice]) -> Self:
        """In-place variant of `apply_crop`."""
        return self.apply_crop(ex_slice=ex_slice,inplace=True)

    def pad_to(self, target_shape: list[int] | tuple[int, int, int] | Self, mode: MODES = "constant", crop=False, inplace=False) -> Self:
        """Pads (and optionally crops) the image to match a target shape.

        Args:
            target_shape: Desired output shape ``(x, y, z)`` or another NII whose
                shape is used as the target.
            mode: Padding mode (``"constant"``, ``"nearest"``, ``"reflect"``,
                or ``"wrap"``). Defaults to ``"constant"``.
            crop: If True and the image is larger than ``target_shape`` along any
                axis, that axis is cropped first. Defaults to False.
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            The NII padded (and optionally cropped) to ``target_shape``.
        """
        if isinstance(target_shape, NII):
            target_shape = target_shape.shape
        padding, crop, requires_crop = _pad_to_parameters(self.shape, target_shape)
        s = self
        if crop and requires_crop:
            s = s.apply_crop(tuple(crop),inplace=inplace)
        return s.apply_pad(padding,inplace=inplace,mode=mode)

    def apply_pad(self, padd: Sequence[tuple[int | None, int | None]] | int | None, mode: MODES = "constant", inplace=False, verbose: logging = True,) -> Self:
        """Pads the image with explicit per-axis ``(before, after)`` amounts.

        The affine is updated so that the world-space origin is preserved (i.e. the
        new voxel (0, 0, 0) corresponds to the same world coordinate as before).

        Args:
            padd: A sequence of ``(before, after)`` integer tuples, one per spatial
                dimension. ``None`` as the ``before`` value means no padding on that
                side. Pass ``None`` for the whole argument to skip padding entirely.
            mode: Padding mode forwarded to ``numpy.pad``. Defaults to ``"constant"``.
                In ``"constant"`` mode the fill value is ``self.get_c_val()``.
            inplace: If True, modifies this NII in place. Defaults to False.
            verbose: If True, logs the padding parameters. Defaults to True.

        Returns:
            The padded NII.
        """
        #TODO add other modes
        #TODO add testcases and options for modes
        if padd is None:
            return self if inplace else self.copy()

        if isinstance(padd, (int, float)):
            padd = int(padd)
            padd = ((padd, padd),) * self.dims

        assert len(padd) == self.dims

        # Replace None with 0
        padd = tuple((b or 0, a or 0) for b, a in padd)

        # Extend for non-spatial dims
        padd = padd + ((0, 0),) * (len(self.shape) - len(padd))

        # Build affine transform
        transform = np.eye(self.dims + 1, dtype=float)
        for i, (before, _) in enumerate(padd[:self.dims]):
            transform[i, -1] = -before

        affine = self.affine @ transform

        arr = self.get_array()

        # ---- 1. CROPPING (negative padding) ----
        slices = []

        for i, (before, after) in enumerate(padd[:self.dims]):
            start = max(0, -before)
            end = arr.shape[i] - max(0, -after)
            slices.append(slice(start, end))

        # keep non-spatial dims unchanged
        slices += [slice(None)] * (arr.ndim - self.dims)

        arr = arr[tuple(slices)]

        # ---- 2. PADDING (positive only) ----
        padd_positive = tuple(
            (max(0, b), max(0, a)) for b, a in padd
        )

        args = {}
        if mode == "constant":
            args["constant_values"] = self.get_c_val()

        if mode == "nearest":
            mode = "edge"

        log.print(f"Padd {padd}; {mode=}, {args}", verbose=verbose)

        arr = np.pad(arr, padd_positive, mode=mode, **args)

        nii = (arr, affine, self.header)

        if inplace:
            self.nii = nii
            return self

        return self.copy(nii)

    def rescale_and_reorient(self, axcodes_to=None, voxel_spacing=(-1, -1, -1), verbose: logging = True, inplace=False, c_val: float | None = None, mode: MODES = 'nearest') -> Self:
        """Reorients and then rescales the image in a single step.

        Args:
            axcodes_to: Target orientation axis codes, e.g. ``("P", "I", "R")``.
                If None, keeps the current orientation. Defaults to None.
            voxel_spacing: Target voxel spacing in mm. ``-1`` keeps the current spacing
                for that axis. Defaults to ``(-1, -1, -1)``.
            verbose: Verbosity flag. Defaults to True.
            inplace: If True, modifies this NII in place. Defaults to False.
            c_val: Background fill value for resampling. Defaults to None.
            mode: Interpolation / boundary mode. Defaults to ``"nearest"``.

        Returns:
            The reoriented and rescaled NII.
        """
        ## Resample and rotate and Save Tempfiles
        if axcodes_to is None:
            curr = self
            ornt_img = self.orientation
            axcodes_to = nio.ornt2axcodes(ornt_img)
        else:
            curr = self.reorient(axcodes_to=axcodes_to, verbose=verbose, inplace=inplace)
        return curr.rescale(voxel_spacing=voxel_spacing, verbose=verbose, inplace=inplace,c_val=c_val,mode=mode)

    def rescale_and_reorient_(self, axcodes_to=None, voxel_spacing=(-1, -1, -1), c_val: float | None = None, mode: MODES = 'nearest', verbose: logging = True) -> Self:
        """In-place variant of `rescale_and_reorient`."""
        return self.rescale_and_reorient(axcodes_to=axcodes_to,voxel_spacing=voxel_spacing,c_val=c_val,mode=mode,verbose=verbose,inplace=True)

    def reorient_same_as(self, img_as: Nifti1Image | Self, verbose: logging = False, inplace=False) -> Self:
        """Reorients this image to match the orientation of another image.

        Args:
            img_as: Reference image whose orientation is used as the target.
            verbose: If True, logs the orientation change. Defaults to False.
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            The reoriented NII.
        """
        axcodes_to: AX_CODES = nio.ornt2axcodes(nio.io_orientation(img_as.affine)) # type: ignore
        return self.reorient(axcodes_to=axcodes_to, verbose=verbose, inplace=inplace)

    def reorient_same_as_(self, img_as: Nifti1Image | Self, verbose: logging = False) -> Self:
        """In-place variant of `reorient_same_as`."""
        return self.reorient_same_as(img_as=img_as,verbose=verbose,inplace=True)
    def rescale(self, voxel_spacing:float|tuple[float,...]=(1, 1, 1), c_val:float|None=None, verbose:logging=False, inplace=False,mode:MODES='nearest',order: int |None = None,align_corners:bool=False,atol=0.001) -> Self:
        """Rescales the NIfTI image to a new voxel spacing.

        Args:
            voxel_spacing (tuple[float, float, float] | float): The desired voxel spacing in millimeters (x, y, z). -1 is keep the voxel spacing.
                Defaults to (1, 1, 1).
            c_val (float | None, optional): The padding value. Defaults to None, meaning that the padding value will be
                inferred from the image data.
            verbose (bool, optional): Whether to print a message indicating that the image has been resampled. Defaults to
                False.
            inplace (bool, optional): Whether to modify the current object or return a new one. Defaults to False.
            mode (str, optional): One of the supported modes by scipy.ndimage.interpolation (e.g., "constant", "nearest",
                "reflect", "wrap"). See the documentation for more details. Defaults to "constant".
            align_corners (bool|default): If True or not set and seg==True. Aline corners for scaling. This prevents segmentation mask to shift in a direction.
            atol: absolute tolerance for skipping if already close in voxel_spacing
        Returns:
            NII: A new NII object with the resampled image data.
        """
        if isinstance(voxel_spacing, (int,float)):
            voxel_spacing =(voxel_spacing for _ in range(min(3,self.affine.shape[0]-1)))
        n = self.dims
        while  n> len(voxel_spacing):
            voxel_spacing = (*voxel_spacing, -1)
        if all(a in (-1, b) for a,b in zip(voxel_spacing, self.zoom)):
            log.print(f"Image already resampled to voxel size {self.zoom}",verbose=verbose)
            return self.copy() if inplace else self

        c_val = self.get_c_val(c_val)
        # resample to new voxel spacing based on the current x-y-z-orientation
        aff = self.affine
        shp = self.shape
        zms = self.zoom
        if order is None:
            order = 0 if self.seg else 3
        #print(aff.shape,shp,zms,voxel_spacing)
        voxel_spacing = tuple([v if v != -1 else z for v,z in zip_strict(voxel_spacing,zms)])
        if np.isclose(voxel_spacing, self.zoom,atol=atol).all():
            log.print(f"Image already resampled to voxel size {self.zoom}",verbose=verbose)
            return self.copy() if inplace else self

        # Calculate new shape
        new_shp = tuple(np.rint([shp[i] * zms[i] / voxel_spacing[i] for i in range(len(voxel_spacing))]).astype(int))
        if len(new_shp) < len(shp):
            new_shp = new_shp + shp[len(new_shp):]
        new_aff = _rescale_affine(aff, shp, voxel_spacing, new_shp)  # type: ignore
        new_aff[:n, n] = nib.affines.apply_affine(aff, [0 for _ in range(n)])# type: ignore
        new_img = _resample_from_to(self, (new_shp, new_aff,voxel_spacing), order=order, mode=mode,align_corners=align_corners)
        log.print(f"Image resampled from {zms} to voxel size {voxel_spacing}",verbose=verbose)
        if inplace:
            self.nii = new_img
            return self
        return self.copy(new_img)

    def rescale_(self, voxel_spacing=(1, 1, 1), c_val: float | None = None, verbose: logging = False, mode: MODES = 'nearest') -> Self:
        """In-place variant of `rescale`."""
        return self.rescale( voxel_spacing=voxel_spacing, c_val=c_val, verbose=verbose,mode=mode, inplace=True)

    def resample_from_to(self, to_vox_map:Image_Reference|Has_Grid|tuple[SHAPE,AFFINE,ZOOMS], mode:MODES='nearest', order: int |None=None, c_val=None, inplace = False,verbose:logging=True,align_corners:bool=False) -> Self:
        r"""Self will be resampled in coordinate of given other image. Adheres to global space not to local pixel space.

        Args:
            to_vox_map (Image_Reference|Proxy): If object, has attributes shape giving input voxel shape, and affine giving mapping of input voxels to output space. If length 2 sequence, elements are (shape, affine) with same meaning as above. The affine is a (4, 4) array-like.\n
            mode (str, optional): Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap').Defaults to 'constant'.\n
            cval (float, optional): Value used for points outside the boundaries of the input if mode='nearest'. Defaults to 0.0.\n
            aline_corners (bool|default): If True or not set and seg==True. Aline corners for scaling. This prevents segmentation mask to shift in a direction.
            inplace (bool, optional): Defaults to False.

        Returns:
            NII:
        """        ''''''
        if to_vox_map is None:
            return self if inplace else self.copy()
        c_val = self.get_c_val(c_val)
        if isinstance(to_vox_map,Has_Grid):
            mapping = to_vox_map.to_gird()
        else:
            mapping = to_vox_map if isinstance(to_vox_map, tuple) else to_nii_optional(to_vox_map, seg=self.seg, default=to_vox_map)
        if isinstance(mapping,Has_Grid):
            if mapping.assert_affine(self,raise_error=False,origin_tolerance=0.000001,error_tolerance=0.000001,shape_tolerance=0):
                log.print(f"resample_from_to skipped; already in space: {self}",verbose=verbose)
                return self if inplace else self.copy()

            m1 = mapping if mapping.orientation == self.orientation else mapping.make_empty_POI().reorient(self.orientation)
            if m1.assert_affine(self,raise_error=False,origin_tolerance=0.00001,error_tolerance=0.00001,shape_tolerance=0):
                log.print(f"resample_from_to only need reorientation; {self.orientation}",verbose=verbose)
                ret = self.reorient(mapping.orientation,inplace=inplace)
                ret.affine = mapping.affine #remove floating point error
                return ret
            if self.orientation == mapping.orientation and np.allclose(self.zoom , mapping.zoom, atol=1e-6):
                shift = (np.array(self.origin) - np.array(m1.origin)) / np.array(m1.zoom)
                if np.allclose(shift, np.round(shift), atol=1e-6):
                    s = self.reorient(mapping.orientation,inplace=inplace)  # noqa: PLW0642
                    shift = (np.array(self.origin) - np.array(mapping.origin)) / np.array(mapping.zoom)
                    shift = np.round(shift).astype(int)
                    dst_shape = np.array(mapping.shape)
                    src_shape = np.array(s.shape)
                    # padding before = how much dst starts before src
                    pad_before = shift
                    # padding after = remaining dst size after src
                    pad_after = dst_shape-shift-src_shape
                    pad = tuple((int(b), int(a)) for b, a in zip(pad_before, pad_after))
                    ret = s.apply_pad(pad, mode=mode,inplace=inplace,verbose=verbose)

                    valid = ret.assert_affine(mapping,raise_error=False,origin_tolerance=0.0001,error_tolerance=0.0001,shape_tolerance=0)
                    if valid:
                        log.print(f"resample_from_to only needs padding/cropping {pad}",verbose=verbose)
                        ret.affine = mapping.affine #remove floating point error
                        return ret


        assert mapping is not None
        log.print(f"resample_from_to: {self} to {mapping}",verbose=verbose)
        if order is None:
            order = 0 if self.seg else 3
        nii = _resample_from_to(self, mapping,order=order, mode=mode,align_corners=align_corners)


        if inplace:
            self.nii = nii
            return self
        else:
            return self.copy(nii)
    def resample_from_to_(self, to_vox_map: Image_Reference | Has_Grid | tuple[SHAPE, AFFINE, ZOOMS], mode: MODES = 'nearest', c_val: float | None = None, verbose: logging = True, aline_corners=False) -> Self:
        """In-place variant of `resample_from_to`."""
        return self.resample_from_to(to_vox_map,mode=mode,c_val=c_val,inplace=True,verbose=verbose,align_corners=aline_corners)

    @property
    def is_empty(self) -> bool:
        """Checks if the array in the nifti is empty.

        Returns:
            bool: Whether the nifti is empty or not
        """
        return np_is_empty(self.get_array())

    def n4_bias_field_correction(
        self,
        threshold = 60,
        mask=None, # type: ignore
        shrink_factor=4,
        convergence=None,
        spline_param=200,
        verbose=False,
        weight_mask=None,
        crop=False,
        inplace=False
    ) -> Self:
        """Runs a n4 bias field correction over the nifty.

        Args:
            threshold (int, optional): If != 0, will mask the input based on the threshold. Defaults to 60.
            mask (_type_, optional): If threshold==0, this can be set to input a individual mask. If none, lets the algorithm automatically determine the mask. Defaults to None.
            shrink_factor (int, optional): _description_. Defaults to 4.
            convergence (dict, optional): _description_. Defaults to {"iters": [50, 50, 50, 50], "tol": 1e-07}.
            spline_param (int, optional): _description_. Defaults to 200.
            verbose (bool, optional): _description_. Defaults to False.
            weight_mask (_type_, optional): _description_. Defaults to None.
            crop (bool, optional): _description_. Defaults to False.
            inplace (bool, optional): _description_. Defaults to False.

        Returns:
            NII: The NII with bias field corrected image
        """
        if convergence is None:
            convergence = {"iters": [50, 50, 50, 50], "tol": 1e-07}
        assert self.seg is False, "n4 bias field correction on a segmentation does not make any sense"
        # install antspyx not ants!
        import ants
        try:
            import ants.ops.bias_correction as bc  # install antspyx not ants!
        except ModuleNotFoundError:
            import ants.utils.bias_correction as bc  # install antspyx not ants!
        from ants.utils.convert_nibabel import from_nibabel
        from scipy.ndimage import binary_dilation, generate_binary_structure
        dtype = self.dtype
        input_ants:ants.ANTsImage = from_nibabel(nib.nifti1.Nifti1Image(self.get_array(),self.affine))
        if threshold != 0:
            mask_arr = self.get_array()
            mask_arr[mask_arr < threshold] = 0
            mask_arr[mask_arr != 0] = 1
            mask_arr = mask_arr.astype(np.uint8)
            struct = generate_binary_structure(3, 3)
            mask_arr = binary_dilation(mask_arr.copy(), structure=struct, iterations=3)
            mask_arr = mask_arr.astype(np.uint8)
            mask:ants.ANTsImage = from_nibabel(nib.nifti1.Nifti1Image(mask_arr,self.affine))#self.set_array(mask,verbose=False).nii
            mask = mask.set_spacing(input_ants.spacing) # type: ignore
        out = bc.n4_bias_field_correction(
            input_ants,
            mask=mask,
            shrink_factor=shrink_factor,
            convergence=convergence,
            spline_param=spline_param,
            verbose=verbose,
            weight_mask=weight_mask,

        )


        out_nib:Nifti1Image = out.to_nibabel()
        if crop:
            # Crop to regions that had a normalization applied. Removes a lot of dead space
            dif = NII((input_ants - out).to_nibabel())
            dif_arr = dif.get_array()
            dif_arr[dif_arr != 0] = 1
            dif.set_array_(dif_arr,verbose=verbose)
            ex_slice = dif.compute_crop()
            out_nib:Nifti1Image = out_nib.slicer[ex_slice]

        if inplace:
            self.nii = out_nib
            self.set_dtype_(dtype)
            return self
        return self.copy(out_nib).set_dtype_(dtype)

    def n4_bias_field_correction_(self, threshold=60, mask=None, shrink_factor=4, convergence=None, spline_param=200, verbose=False, weight_mask=None, crop=False) -> Self:
        """In-place variant of `n4_bias_field_correction`."""
        if convergence is None:
            convergence = {"iters": [50, 50, 50, 50], "tol": 1e-07}
        return self.n4_bias_field_correction(mask=mask,shrink_factor=shrink_factor,convergence=convergence,spline_param=spline_param,verbose=verbose,weight_mask=weight_mask,crop=crop,inplace=True,threshold = threshold)

    def normalize_to_range_(self, min_value: int = 0, max_value: int = 1500, verbose: logging = True) -> None:
        """In-place normalization that clips and scales intensity values to ``[min_value, max_value]``.

        Args:
            min_value: Desired minimum output value. Defaults to 0.
            max_value: Desired maximum output value. Defaults to 1500.
            verbose: If True, logs the before/after intensity range. Defaults to True.

        Raises:
            AssertionError: If this NII is a segmentation (``seg=True``).
        """
        assert not self.seg
        mi, ma = self.min(), self.max()
        self += -mi + min_value  # min = 0
        self_dtype = self.dtype
        max_value2 = self.max() # this is a new value if min got shifted
        if max_value2 > max_value:
            self *= max_value / max_value2
            self.set_dtype_(self_dtype)
        log.print(f"Shifted from range {mi, ma} to range {self.min(), self.max()}", verbose=verbose)

    def get_histogram(self, bins=256, hrange=None, density=False, c_val:float|None=None) -> tuple[np.ndarray, np.ndarray]:
        """Returns the histogram of the image array.

        Args:
            bins (int, optional): Number of bins for the histogram. Defaults to 256.
            range (tuple, optional): Range of values to consider for the histogram. Defaults to None.
            density (bool, optional): If True, the result is the probability density function at the bin, normalized such that the integral over the range is 1. Defaults to False.
            c_val (float|None, optional): The value below which all values are set to c_val. Defaults to None.

        Returns:
            tuple: A tuple containing the histogram values and the bin edges.
        """
        arr = self.get_array()
        if c_val is not None:
            arr[arr <= c_val] = c_val
        return np.histogram(arr, bins=bins, range=hrange, density=density)

    def match_histograms(self, reference: Image_Reference, c_val: float = 0, inplace=False) -> Self:
        """Adjusts the intensity histogram of this image to match a reference image.

        Args:
            reference: Reference image whose histogram is used as the target.
            c_val: Background value; voxels at or below this threshold are clamped
                to ``c_val`` after matching. Defaults to 0.
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            The histogram-matched NII.

        Raises:
            AssertionError: If either image has ``seg=True``.
            ValueError: If ``c_val <= -999`` (CT-range backgrounds are not supported).
        """
        assert not self.seg
        ref_nii = to_nii(reference)
        assert ref_nii.seg is False
        assert self.seg is False
        c_val = self.get_c_val(c_val)
        if c_val <= -999:
            raise ValueError('match_histograms only functions on MRI, which have a minimum 0.')

        from skimage.exposure import match_histograms as ski_match_histograms
        img_arr = self.get_array()
        matched = ski_match_histograms(img_arr, ref_nii.get_array())
        matched[matched <= c_val] = c_val
        return self.set_array(matched, inplace=inplace,verbose=False)

    def match_histograms_(self, reference: Image_Reference, c_val: float = 0) -> Self:
        """In-place variant of `match_histograms`."""
        return self.match_histograms(reference,c_val = c_val,inplace=True)

    def smooth_gaussian(self, sigma: float | list[float] | tuple[float], truncate: float = 4.0, nth_derivative: int = 0, inplace=False) -> Self:
        """Applies a Gaussian smoothing filter to the image.

        Args:
            sigma: Standard deviation of the Gaussian kernel. A scalar applies the
                same sigma to all axes; a sequence sets per-axis values.
            truncate: Truncate the filter at this many standard deviations.
                Defaults to 4.0.
            nth_derivative: Order of the derivative (0 = smoothing, 1 = gradient, …).
                Defaults to 0.
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            The smoothed NII.

        Raises:
            AssertionError: If ``seg=True`` (use ``smooth_gaussian_labelwise`` instead).
        """
        assert self.seg is False, "You really want to smooth a segmentation? If yes, use smooth_gaussian_channelwise() instead"
        from scipy.ndimage import gaussian_filter
        arr = gaussian_filter(self.get_array(), sigma, order=nth_derivative,cval=self.get_c_val(), truncate=truncate)# radius=None, axes=None
        return self.set_array(arr,inplace,verbose=False)

    def smooth_gaussian_(self, sigma: float | list[float] | tuple[float], truncate: float = 4.0, nth_derivative: int = 0) -> Self:
        """In-place variant of `smooth_gaussian`."""
        return self.smooth_gaussian(sigma=sigma,truncate=truncate,nth_derivative=nth_derivative,inplace=True)


    def smooth_gaussian_labelwise(
        self,
        label_to_smooth: list[int] | int,
        sigma: float = 3.0,
        radius: int = 6,
        truncate: int = 4,
        boundary_mode: str = "nearest",
        dilate_prior: int = 0,
        dilate_connectivity: int = 1,
        dilate_channelwise: bool = False,
        smooth_background: bool = True,
        background_threshold: float | None = None,
        inplace: bool = False,
        verbose:logging=False,
    ) -> Self:
        """Smoothes the segmentation mask by applying a gaussian filter label-wise and then using argmax to derive the smoothed segmentation labels again.

        Args:
            label_to_smooth (list[int] | int): Which labels to smooth in the mask. Every other label will be untouched
            sigma (float, optional): Sigma of the gaussian blur. Defaults to 3.0.
            radius (int, optional): Radius of the gaussian blur. Defaults to 6.
            truncate (int, optional): Truncate of the gaussian blur. Defaults to 4.
            boundary_mode (str, optional): Boundary Mode of the gaussian blur. Defaults to "nearest".
            dilate_prior (int, optional): Dilate this many voxels before starting the gaussian blur algorithm. Defaults to 0.
            dilate_connectivity (int, optional): Connectivity of the dilation process, if applied. Defaults to 3.
            smooth_background (bool, optional): If true, will also smooth the background. If False, the background voxels stay the same and the segmentation cannot add voxels. Defaults to True.
            inplace (bool, optional): If true, will overwrite the input NII instead of making a copy. Defaults to False.

        Returns:
            NII: The smoothed NII object.
        """
        assert self.seg, "You cannot use this on a non-segmentation NII"
        log.print("smooth_gaussian_labelwise",verbose=verbose)
        smoothed = np_smooth_gaussian_labelwise(
            self.get_seg_array(),
            label_to_smooth=label_to_smooth,
            sigma=sigma,
            radius=radius,
            truncate=truncate,
            boundary_mode=boundary_mode,
            dilate_prior=dilate_prior,
            dilate_connectivity=dilate_connectivity,
            smooth_background=smooth_background,
            background_threshold=background_threshold,
            dilate_channelwise=dilate_channelwise,
        )
        return self.set_array(smoothed, inplace, verbose=False)

    def smooth_gaussian_labelwise_(
        self,
        label_to_smooth: list[int] | int,
        sigma: float = 3.0,
        radius: int = 6,
        truncate: int = 4,
        boundary_mode: str = "nearest",
        dilate_prior: int = 1,
        dilate_connectivity: int = 1,
        dilate_channelwise: bool = False,
        smooth_background: bool = True,
        background_threshold: float | None = None,
    ) -> Self:
        """In-place variant of `smooth_gaussian_labelwise`."""
        return self.smooth_gaussian_labelwise(
            label_to_smooth=label_to_smooth,
            sigma=sigma,
            radius=radius,
            truncate=truncate,
            boundary_mode=boundary_mode,
            dilate_prior=dilate_prior,
            dilate_connectivity=dilate_connectivity,
            smooth_background=smooth_background,
            inplace=True,
            background_threshold=background_threshold,
            dilate_channelwise=dilate_channelwise,
        )

    def to_ants(self) -> Any:
        """Converts this NII to an ANTs image (requires the ``antspyx`` package).

        Returns:
            An ``ants.ANTsImage`` corresponding to this NII.

        Raises:
            ImportError: If ``antspyx`` is not installed.
        """
        try:
            import ants
        except Exception:
            log.print_error()
            log.on_fail("run 'pip install antspyx' to install hf-deepali")
            raise
        return ants.from_nibabel(self.nii)

    def to_simpleITK(self) -> Any:
        """Converts this NII to a SimpleITK image.

        Returns:
            A ``SimpleITK.Image`` corresponding to this NII.
        """
        from TPTBox.core.sitk_utils import nii_to_sitk
        return nii_to_sitk(self)

    @classmethod
    def from_deepali(cls, img, seg=False) -> NII:
        """Construct a NII from a DeepALI ``Image`` object.

        Args:
            img: A ``deepali.data.Image`` instance.
            seg: Mark the resulting NII as a segmentation mask.
        """
        try:
            from deepali.data import Image as deepaliImage
        except Exception:
            log.print_error()
            log.on_fail("run 'pip install hf-deepali' to install deepali")
            raise
        img_ : deepaliImage =img
        grid = cls.from_deepali_grid(img_.grid())

        arr = img_.data.squeeze().cpu().detach().numpy()
        arr = np.transpose(arr, axes=tuple(reversed(range(arr.ndim))))
        return  NII((nib.Nifti1Image(arr,grid.affine)),seg=seg)

    def to_deepali(self, align_corners: bool = True, dtype=None, device: device | str = "cpu") -> Any:
        """Converts this NII to a DeepALI ``Image`` tensor (requires the ``hf-deepali`` package).

        Args:
            align_corners: If True, aligns grid corners during conversion. Defaults to True.
            dtype: Optional target torch dtype. Defaults to None (inferred).
            device: Target torch device. Defaults to ``"cpu"``.

        Returns:
            A ``deepali.data.Image`` corresponding to this NII.

        Raises:
            ImportError: If ``hf-deepali`` is not installed.
        """
        import torch
        try:
            from deepali.data import Image as deepaliImage  # type: ignore
        except Exception:
            log.print_error()
            log.on_fail("run 'pip install hf-deepali' to install deepali")
            raise
        dim = np.asarray(self.header["dim"])
        ndim = int(dim[0])
        # Image data array
        data = self.get_array()
        # Squeeze unused dimensions
        # https://github.com/InsightSoftwareConsortium/ITK/blob/3454d857dc46e4333ad1178be8c186547fba87ef/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx#L1112-L1156
        intent_code = int(self.header["intent_code"]) # type: ignore
        if intent_code in (1005, 1006, 1007):
            # Vector or matrix valued image
            for realdim in range(4, 1, -1):
                if dim[realdim] > 1:
                    break
            else:
                realdim = 1
        elif intent_code == 1004:
            raise NotImplementedError("NII has an intent code of NIFTI_INTENT_GENMATRIX which is not yet implemented")
        else:
            # Scalar image
            realdim = ndim
            while realdim > 3 and dim[realdim] == 1:
                realdim -= 1
        data = np.reshape(data, data.shape[:realdim] + data.shape[5:])
        # Reverse order of axes
        data = np.transpose(data, axes=tuple(reversed(range(data.ndim))))
        grid = self.to_deepali_grid(align_corners=align_corners)
        # Add leading channel dimension
        if data.ndim == grid.ndim:
            data = np.expand_dims(data, 0)
        if data.dtype == np.uint16:
            data = data.astype(np.int32)
        elif data.dtype == np.uint32:
            data = data.astype(np.int64)
        grid = grid.align_corners_(align_corners)
        data = torch.Tensor(data)
        #if len(torch.Tensor(data)) == 3:
        #   data = data.unsqueeze(0)
        return deepaliImage(data, grid, dtype=dtype, device=device)  # type: ignore

    def erode_msk(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, inplace=False,verbose:logging=True,border_value=0, use_crop=True,ignore_direction:DIRECTIONS|int|None=None) -> Self:
        """Erodes the binary segmentation mask by the specified number of voxels.

        Args:
            mm (int, optional): The number of voxels to erode the mask by. Defaults to 5.
            labels (LABEL_REFERENCE, optional): Labels that should be dilated. If None, will erode all labels (not including zero!)
            connectivity (int, optional): Elements up to a squared distance of connectivity from the center are considered neighbors. connectivity may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors).
            inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
            verbose (bool, optional): Whether to print a message indicating that the mask was eroded. Defaults to True.
            use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
        Returns:
            NII: The eroded mask.

        Notes:
            The method uses binary erosion with a 3D structuring element to erode the mask by the specified number of voxels.

        """
        assert self.seg
        log.print("erode mask",end='\r',verbose=verbose)
        msk_i_data = self.get_seg_array()
        labels = self.unique() if labels is None else labels
        if isinstance(ignore_direction,str):
            ignore_direction = self.get_axis(ignore_direction)
        out = np_erode_msk(msk_i_data, label_ref=labels, n_pixel=n_pixel, connectivity=connectivity,border_value=border_value,ignore_axis=ignore_direction, use_crop=use_crop)
        out = out.astype(self.dtype)
        log.print("Mask eroded by", n_pixel, "voxels",verbose=verbose)
        return self.set_array(out,inplace=inplace)

    def erode_msk_(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, verbose: logging = True, border_value=0, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self:
        """In-place variant of `erode_msk`."""
        return self.erode_msk(n_pixel=n_pixel, labels=labels, connectivity=connectivity, inplace=True, verbose=verbose,border_value=border_value,use_crop=use_crop,ignore_direction=ignore_direction)
    def erode_msk_euclid(
        self,
        n_pixel: int = 5,
        labels: LABEL_REFERENCE = None,
        mask: Self | None = None,
        inplace=False,
        verbose: logging = True,
        use_crop=True,
    ) -> Self:
        """Euclidean erodes (in voxel space) a segmentation mask by the specified number.

        Args:
            n_pixel (int, optional): The number of voxels to erode the mask by. Defaults to 5.
            labels (list[int], optional): Labels that should be eroded. If None, will erode all labels (not including zero!).
            mask (NII, optional): If set, after operation, will zero out everything based on this mask.
            inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
            verbose (bool, optional): Whether to print a message. Defaults to True.
            use_crop: Speed up computation by cropping/un-cropping.

        Returns:
            NII: The eroded mask.

        Notes:
            Uses Euclidean distance transform inside the foreground.
            Runtime is independent of n_pixel and len(labels).
            For n_pixel=1 this is similar to connectivity=1 erosion.
        """
        assert self.seg
        log.print("erode mask", end="\r", verbose=verbose)

        msk_i_data = self.get_seg_array()
        mask_ = mask.get_seg_array() if mask is not None else None

        out = np_erode_msk_euclid(
            arr=msk_i_data,
            n_pixel=n_pixel,
            labels=labels,
            use_crop=use_crop,
            mask=mask_
        )

        out = out.astype(self.dtype)

        log.print("Mask euclidean eroded by", n_pixel, "voxels", verbose=verbose)

        return self.set_array(out, inplace=inplace)
    def dilate_msk_euclid(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, mask: Self | None = None, inplace=False, verbose: logging = True, use_crop=True) -> Self:
        """Euclidean Dilates (in voxel space) a segmentation mask by the specified number.

        Args:
            n_pixel (int, optional): The number of voxels to dilate the mask by. Defaults to 5.
            labels (list[int], optional): Labels that should be dilated. If None, will dilate all labels (not including zero!)
            mask (NII, optional): If set, after each iteration, will zero out everything based on this mask
            inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
            verbose (bool, optional): Whether to print a message indicating that the mask was dilated. Defaults to True.
            use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
        Returns:
            NII: The dilated mask.

        Notes:
            The method uses euclidean dilation to dilate the mask by the specified number of voxels.
            For n_pixel=1 dilate_msk_euclid and dilate_msk/connectivity=1 are equivalent.
            This will algorithm runtime is independent of n_pixel and len(labels) unlike dilate_msk

        """
        assert self.seg
        log.print("dilate mask",end='\r',verbose=verbose)
        msk_i_data = self.get_seg_array()
        mask_ = mask.get_seg_array() if mask is not None else None
        out = np_dilate_msk_euclid(arr=msk_i_data, n_pixel=n_pixel,labels=labels,use_crop=use_crop,mask=mask_)
        out = out.astype(self.dtype)
        log.print("Mask euclidean dilated by", n_pixel, "voxels",verbose=verbose)

        return self.set_array(out,inplace=inplace)

    def dilate_msk(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, mask: Self | None = None, inplace=False, verbose:logging=True,use_crop=True, ignore_direction:DIRECTIONS|int|None=None) -> Self:
        """Dilates the binary segmentation mask by the specified number of voxels.

        Args:
            n_pixel (int, optional): The number of voxels to dilate the mask by. Defaults to 5.
            labels (list[int], optional): Labels that should be dilated. If None, will dilate all labels (not including zero!)
            connectivity (int, optional): Elements up to a squared distance of connectivity from the center are considered neighbors. connectivity may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors).
            mask (NII, optional): If set, after each iteration, will zero out everything based on this mask
            inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
            verbose (bool, optional): Whether to print a message indicating that the mask was dilated. Defaults to True.
            use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
        Returns:
            NII: The dilated mask.

        Notes:
            The method uses binary dilation with a 3D structuring element to dilate the mask by the specified number of voxels.

        """
        assert self.seg
        log.print("dilate mask",end='\r',verbose=verbose)
        if labels is None:
            labels = self.unique()
        msk_i_data = self.get_seg_array()
        mask_ = mask.get_seg_array() if mask is not None else None
        if isinstance(ignore_direction,str):
            ignore_direction = self.get_axis(ignore_direction)
        out = np_dilate_msk(arr=msk_i_data, label_ref=labels, n_pixel=n_pixel, mask=mask_, connectivity=connectivity,ignore_axis=ignore_direction, use_crop=use_crop)
        out = out.astype(self.dtype)
        log.print("Mask dilated by", n_pixel, "voxels",verbose=verbose)
        return self.set_array(out,inplace=inplace)

    def dilate_msk_(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, mask: Self | None = None, verbose: logging = True, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self:
        """In-place variant of `dilate_msk`."""
        return self.dilate_msk(n_pixel=n_pixel, labels=labels, connectivity=connectivity, mask=mask, inplace=True, verbose=verbose,use_crop=use_crop,ignore_direction=ignore_direction)


    def fill_holes(self, labels: LABEL_REFERENCE = None, slice_wise_dim: int|str | None = None, verbose:logging=False, inplace=False,use_crop=True) -> Self:  # noqa: ARG002
        """Fills holes in segmentation.

        Args:
            labels (LABEL_REFERENCE, optional): Labels that the hole-filling should be applied to. If none, applies on all labels found in arr. Defaults to None.
            verbose: whether to print which labels have been filled
            inplace (bool): Whether to modify the current NIfTI image object in place or create a new object with the mapped labels.
                Default is False.
            slice_wise_dim (int | None, optional): If the input is 3D, the specified dimension here cna be used for 2D slice-wise filling. Defaults to None.
            use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
        Returns:
            NII: If inplace is True, returns the current NIfTI image object with filled holes. Otherwise, returns a new NIfTI image object with filled holes.
        """
        assert self.seg
        if labels is None:
            labels = list(self.unique())

        if isinstance(labels, int):
            labels = [labels]

        seg_arr = self.get_seg_array()
        if isinstance(slice_wise_dim,str):
            slice_wise_dim = self.get_axis(slice_wise_dim)
        #seg_arr = self.get_seg_array()
        filled = np_fill_holes(seg_arr, label_ref=labels, slice_wise_dim=slice_wise_dim, use_crop=use_crop)
        return self.set_array(filled,inplace=inplace)

    def fill_holes_(self, labels: LABEL_REFERENCE = None, slice_wise_dim: int | str | None = None, verbose: logging = True, use_crop=True) -> Self:
        """In-place variant of `fill_holes`."""
        return self.fill_holes(labels, slice_wise_dim, verbose, inplace=True,use_crop=use_crop)

    def calc_convex_hull(
        self,
        axis: DIRECTIONS|None = "S",
        inplace: bool = False,
        verbose: bool = False
    ) -> Self:
        """Calculates the convex hull of this segmentation nifty.

        Args:
            axis (int | None, optional): If given axis, will calculate convex hull along that axis (remaining dimension must be at least 2). Defaults to None.
        """
        assert self.seg, "To calculate the convex hull, this must be a segmentation"
        axis_int = self.get_axis(axis) if axis is not None else None
        convex_hull_arr = np_calc_convex_hull(self.get_seg_array(), axis=axis_int, verbose=verbose)
        if inplace:
            return self.set_array_(convex_hull_arr)
        return self.set_array(convex_hull_arr)

    def calc_convex_hull_(self, axis: None | DIRECTIONS = "S", verbose: bool = False) -> Self:
        """In-place variant of `calc_convex_hull`."""
        return self.calc_convex_hull(axis=axis, inplace=True, verbose=verbose)


    def boundary_mask(self, threshold: float,inplace = False) -> Self:
        """Calculate a boundary mask based on the input image.

        Parameters:
        - img (NII): The image used to create the boundary mask.
        - threshold(float): threshold

        Returns:
        NII: A segmentation of the boundary.


        This function takes a NII and generates a boundary mask by marking specific regions.
        The intensity of the image can be adjusted for CT scans by adding 1000. The boundary mask is created by initializing
        corner points and using an "infect" process to mark neighboring points. The boundary mask is initiated with
        zeros, and specific boundary points are set to 1. The "infect" function iteratively marks neighboring points in the mask.
        The process starts from the initial points and corner points of the image. The infection process continues until the
        infect_list is empty. The resulting boundary mask is modified by subtracting 1 from all non-zero values and setting
        the remaining zeros to 2. The sum of the boundary mask values is printed before returning the modified NII object.

        """
        return self.set_array(np_calc_boundary_mask(self.get_array(),threshold),inplace=inplace,verbose=False)

    def get_connected_components(self, labels: int | list[int] | None = None, connectivity: int = 3, include_zero: bool = False, inplace=False) -> Self:
        """Replaces each label with a unique connected-component index.

        Args:
            labels: Labels to process. If None, processes all non-zero labels.
            connectivity: Voxel connectivity (1 = face-adjacent, 3 = corner-adjacent).
                Defaults to 3.
            include_zero: If True, also labels the background (0) as components.
                Defaults to False.
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            An NII where each connected component has a unique integer label.

        Raises:
            AssertionError: If ``seg=False``.
        """
        assert self.seg, "This only works on segmentations"
        out, _ = np_connected_components(self.get_seg_array(), label_ref=labels, connectivity=connectivity, include_zero=include_zero)
        return self.set_array(out,inplace=inplace)

    def get_connected_components_per_label(self, labels: int | list[int], connectivity: int = 3, include_zero: bool = False) -> dict[int, Self]:
        """Returns a dict mapping each label to an NII containing only that label's connected components.

        Args:
            labels: Label(s) to process.
            connectivity: Voxel connectivity (1 to 3). Defaults to 3.
            include_zero: Whether to include the background. Defaults to False.

        Returns:
            A dict ``{label: NII}`` where each NII holds the component-indexed array
            for that label.

        Raises:
            AssertionError: If ``seg=False``.
        """
        assert self.seg, "This only works on segmentations"
        out = np_connected_components_per_label(self.get_seg_array(), label_ref=labels, connectivity=connectivity, include_zero=include_zero)
        cc = {i: self.set_array(k) for i,k in out.items()}
        return cc

    def filter_connected_components(self, labels: int |list[int]|None=None,min_volume:int=0,max_volume:int|None=None, max_count_component = None, connectivity: int = 3,removed_to_label=0,keep_label=False, inplace=False,) -> Self:
        """Filter connected components in a segmentation array based on specified volume constraints.

        Parameters:
        labels (int | list[int]): The labels of the components to filter.
        min_volume (int | None): Minimum volume for a component to be retained. Components smaller than this will be removed.
        max_volume (int | None): Maximum volume for a component to be retained. Components larger than this will be removed.
        max_count_component (int | None): Maximum number of components to retain. Once this limit is reached, remaining components will be removed.
        connectivity (int): Connectivity criterion for defining connected components (default is 3).
        removed_to_label (int): Label to assign to removed components (default is 0).
        TODO : max_count_component currently filters over all labels instead of per label. will be changed.
        TODO : removed_to_label does not work when keep_label=False
        Returns:
        None
        """
        assert self.seg, "This only works on segmentations"
        arr = np_filter_connected_components(self.get_seg_array(), largest_k_components=max_count_component,label_ref=labels,connectivity=connectivity,return_original_labels=keep_label,min_volume=min_volume,max_volume=max_volume,removed_to_label=removed_to_label,)
        assert arr.shape == self.shape, f"Shape mismatch: {arr.shape} != {self.shape}"
        if keep_label and labels is not None:
            if isinstance(labels,int):
                labels = [labels]
            old_labels = [i for i in self.unique() if i not in labels]
            if len(old_labels) != 0:
                s = self.extract_label(old_labels,keep_label=True).get_array()
                arr[s != 0] = s[s!=0]
        #print("filter",nii.unique())
        #assert max_count_component is None or nii.max() <= max_count_component, nii.unique()
        return self.set_array(arr, inplace=inplace)
    def filter_connected_components_(self, labels: int | list[int] | None = None, min_volume: int = 0, max_volume: int | None = None, max_count_component=None, connectivity: int = 3, keep_label=False, removed_to_label=0) -> Self:
        """In-place variant of `filter_connected_components`."""
        return self.filter_connected_components(labels,min_volume=min_volume,max_volume=max_volume, max_count_component = max_count_component, connectivity = connectivity,removed_to_label=removed_to_label,keep_label=keep_label,inplace=True)

    def get_segmentation_connected_components_center_of_mass(self, label: int, connectivity: int = 3, sort_by_axis: int | None = None) -> list[COORDINATE]:
        """Calculates the center of mass of each connected component for a given label.

        Args:
            label: The integer label whose connected components are analysed.
            connectivity: Voxel connectivity (1 to 3). Defaults to 3.
            sort_by_axis: If not None, the returned list is sorted by the voxel
                coordinate along this axis. Defaults to None.

        Returns:
            A list of ``(x, y, z)`` voxel coordinates, one per connected component.

        Raises:
            AssertionError: If ``seg=False``.
        """
        assert self.seg, "This only works on segmentations"
        arr = self.get_seg_array()
        return np_get_connected_components_center_of_mass(arr, label=label, connectivity=connectivity, sort_by_axis=sort_by_axis)


    def get_largest_k_segmentation_connected_components(self, k: int | None, labels: int | list[int] | None = None, connectivity: int = 1, return_original_labels: bool = True,inplace=False,min_volume:int=0,max_volume:int|None=None,removed_to_label=0) -> Self:
        """Finds the largest k connected components in a given array (does NOT work with zero as label!).

        Args:
            arr (np.ndarray): input array
            k (int | None): finds the k-largest components. If k is None, will find all connected components and still sort them by size
            labels (int | list[int] | None, optional): Labels that the algorithm should be applied to. If none, applies on all labels found in this NII. Defaults to None.
            return_original_labels (bool): If set to False, will label the components from 1 to k. Defaults to True
        """
        raise DeprecationWarning("Use filter_connected_components instead")
        msk_i_data = self.get_seg_array()
        out = np_filter_connected_components(msk_i_data, largest_k_components=k, label_ref=labels, connectivity=connectivity, return_original_labels=return_original_labels,min_volume=min_volume,max_volume=max_volume,removed_to_label=removed_to_label)
        return self.set_array(out,inplace=inplace)

    def compute_surface_mask(self, connectivity: int = 3, dilated_surface: bool = False) -> Self:
        """Removes everything but surface voxels.

        Args:
            connectivity (int): Connectivity for surface calculation
            dilated_surface (bool): If False, will return msk - eroded mask. If true, will return dilated msk - msk
        """
        assert self.seg, "This only works on segmentations"
        return self.set_array(np_compute_surface(self.get_seg_array(), connectivity=connectivity, dilated_surface=dilated_surface))


    def compute_surface_points(self, connectivity: int = 3, dilated_surface: bool = False) -> list[tuple[int, int, int]]:
        """Returns voxel coordinates of all surface voxels in the segmentation.

        Args:
            connectivity: Connectivity for surface calculation. Defaults to 3.
            dilated_surface: If False, returns ``mask - eroded_mask``; if True,
                returns ``dilated_mask - mask``. Defaults to False.

        Returns:
            A list of ``(x, y, z)`` voxel coordinate tuples for every surface voxel.

        Raises:
            AssertionError: If ``seg=False``.
        """
        assert self.seg, "This only works on segmentations"
        surface = self.compute_surface_mask(connectivity, dilated_surface)
        return np_point_coordinates(surface.get_seg_array()) # type: ignore


    def fill_holes_global_with_majority_voting(self, connectivity: int = 3, inplace: bool = False, verbose: bool = False) -> Self:
        """Fills 3D holes globally, and resolves inter-label conflicts with majority voting by neighbors.

        Args:
            connectivity (int, optional): Connectivity of fill holes. Defaults to 3.
            inplace (bool, optional): Defaults to False.
            verbose (bool, optional): Defaults to False.

        Returns:
            NII:
        """
        assert self.seg, "This only works on segmentations"
        arr = np_fill_holes_global_with_majority_voting(self.get_seg_array(), connectivity=connectivity, verbose=verbose, inplace=inplace)
        return self.set_array(arr,inplace=inplace)


    def map_labels_based_on_majority_label_mask_overlap(self, label_mask: Self, labels: int | list[int] | None = None, dilate_pixel: int = 1, inplace: bool = False,no_match_label=0) -> Self:
        """Relabels all individual labels from input array to the majority labels of a given label_mask.

        Args:
            label_mask (np.ndarray): the mask from which to pull the target labels.
            labels (int | list[int] | None, optional): Which labels in the input to process. Defaults to None.
            dilate_pixel (int, optional): If true, will dilate the input to calculate the overlap. Defaults to 1.
            inplace (bool, optional): Defaults to False.

        Returns:
            NII: Relabeled nifti
        """
        assert self.seg and label_mask.seg, "This only works on segmentations"
        return self.set_array(np_map_labels_based_on_majority_label_mask_overlap(self.get_seg_array(), label_mask.get_seg_array(), label_ref=labels, dilate_pixel=dilate_pixel, inplace=inplace,no_match_label=no_match_label), inplace=inplace,)


    def get_segmentation_difference_to(self, mask_gt: Self, ignore_background_tp: bool = False) -> Self:
        """Calculates an NII that represents the segmentation difference between self and given groundtruth mask.

        Args:
            mask_groundtruth (Self): The ground truth mask. Must match in orientation, zoom, and shape

        Returns:
            NII: Difference NII (1: FN, 2: TP, 3: FP, 4: Wrong label)
        """
        assert self.seg and mask_gt.seg, "This only works on segmentations"
        if self.orientation != mask_gt.orientation:
            mask_gt = mask_gt.reorient_same_as(self)

        self.assert_affine(zoom=mask_gt.zoom, shape=mask_gt.shape)
        arr = self.get_seg_array()
        gt = mask_gt.get_seg_array()
        diff_arr = arr.copy() * 0
        # TP
        diff_arr[gt == arr] = 2
        # FN
        diff_arr[(gt != 0) & (arr == 0)] = 1
        # FP
        diff_arr[(gt == 0) & (arr != 0)] = 3
        # Wrong label
        diff_arr[(diff_arr == 0) & (gt != arr)] = 4

        if ignore_background_tp:
            diff_arr[(gt == 0) & (arr == 0)] = 0

        return self.set_array(diff_arr)

    def get_overlapping_labels_to(
        self,
        mask_other: Self
    ) -> list[tuple[int, int]]:
        """Calculates the pairs of labels that are overlapping in at least one voxel (fast).

        Args:
            mask_other (NII): The array to be compared with.

        Returns:
            list[tuple[int, int]]: List of tuples of labels that overlap in at least one voxel. First label in the tuple is Self NII, the second is of the mask_other
        """
        assert self.seg and mask_other.seg
        return np_calc_overlapping_labels(self.get_seg_array(), mask_other.get_seg_array())

    def is_segmentation_in_border(self,minimum=0, voxel_tolerance: int = 2,use_mm=False) -> bool:
        """Checks if the segmentation is touching the border of the image volume.

        Parameters:
        - minimum (int, optional): Minimum intensity threshold for segmentation. Defaults to 0.
        - voxel_tolerance (int, optional): Number of voxels allowed as tolerance from the border. Defaults to 2.
        - use_mm (bool, optional): Whether to use millimeter units instead of voxels. Defaults to False.

        Returns:
        - bool: True if the segmentation is within the defined voxel tolerance of the border, False otherwise.
        """
        slices = self.compute_crop(minimum,dist=0,use_mm=use_mm,raise_error=False)
        if slices is None:
            return False
        shp = self.shape
        seg_at_border = False
        for d in range(3):
            if slices[d].start <= voxel_tolerance or slices[d].stop - 1 >= shp[d] - voxel_tolerance:
                seg_at_border = True
                break
        return seg_at_border

    def truncate_labels_beyond_reference_(
        self, idx: int | list[int] = 1, not_beyond: int | list[int] = 1, fill: int = 0,  axis: DIRECTIONS = "S", inclusion: bool = False, inplace: bool = True
    ) -> Self:
        """Remove voxels with label ``idx`` beyond a reference label along a specified axis.

        Replaces those voxels with ``fill`` (default 0).

        Parameters:
            nii (NII): The NIfTI-like object with 3D imaging data.
            idx (int or list[int]): The index/label(s) to process in the array. Default is 1.
            not_beyond (int or list[int]): The label/index used to determine the reference position. Default is 1.
            fill (int): The value to set for voxels beyond the reference point. Default is 0.
            axis (str): The anatomical axis along which truncation is applied. Default is "S" (superior).
                Options:
                - "S" (Superior)
                - "I" (Inferior)
                - "R" (Right)
                - "L" (Left)
                - "A" (Anterior)
                - "P" (Posterior)
            inclusion (bool): Controls whether the reference label `not_beyond` itself is considered a boundary.
                - `False` (default): The truncation occurs strictly beyond the reference label.
                - `True`: The truncation includes the reference label as well.
            inplace (bool): If `True`, modifies the NIfTI object in place. If `False`, returns a modified copy.

        Returns:
            NII: The modified NIfTI object.
        """
        # Identify the axis to work on
        axis_ = self.get_axis(axis)
        flip = self.orientation[axis_] != axis  # Check orientation for flipping
        # Get the array data
        np_array = self.get_array()
        np_array_cond = self.extract_label(idx).get_seg_array()

        # Find the lowest point (smallest index) along the axis where `not_above` exists
        threshold = np.where(self.extract_label(not_beyond).get_seg_array() == 1)
        if len(threshold[axis_]) == 0:
            return self if inplace else self.copy()
        flip_up = flip
        if not inclusion:
            flip_up = not flip_up
        # Determine the lowest index along the axis
        limit = threshold[axis_].min() if flip_up else threshold[axis_].max()

        # Create an array of indices along the specified axis
        index_grid = np.arange(self.shape[axis_])

        # Create a mask to identify the region above or below the threshold
        mask = index_grid < limit if flip else index_grid >= limit

        # Apply the mask along the specified axis
        mask = np.expand_dims(mask, axis=tuple(i for i in range(np_array.ndim) if i != axis_))
        mask = np.broadcast_to(mask, self.shape)

        # Replace values of `idx` with `fill` in the masked region
        np_array = np.where((np_array_cond == 1) & mask, fill, np_array)

        # Update the NIfTI object with the modified array
        return self.set_array(np_array, inplace=inplace)
    def truncate_labels_beyond_reference(
        self,
        idx: int | list[int] = 1,
        not_beyond: int | list[int] = 1,
        fill: int = 0,
        axis: DIRECTIONS = "S",
        inclusion: bool = False,
        inplace=False,
    ) -> Self:
        """Removes label ``idx`` voxels beyond the extent of ``not_beyond`` along ``axis``.

        This is the out-of-place counterpart of ``truncate_labels_beyond_reference_``.
        See that method for full parameter documentation.

        Returns:
            The modified NII (new object by default).
        """
        return self.truncate_labels_beyond_reference_(idx,not_beyond,fill,axis,inclusion,inplace=inplace)

    def infect(self: NII, reference_mask: NII, inplace=False, verbose=True, axis: int | str | None = None, max_depth=None, _do_crop=True) -> Self:
        """Expands labels from this segmentation into a reference mask via breadth-first diffusion.

        Starting from the surface voxels of this NII, the algorithm propagates existing
        labels into neighbouring voxels where ``reference_mask == 1``, until no more
        unlabelled neighbour voxels remain (or ``max_depth`` is reached).

        Args:
            reference_mask: Binary NII that defines the region into which labels may
                spread. Must have the same affine as ``self``.
            inplace: If True, modifies this NII in place. Defaults to False.
            verbose: If True, shows a tqdm progress bar. Defaults to True.
            axis: If given, restricts diffusion to the plane perpendicular to this
                axis (int or anatomical direction string). Defaults to None (3-D).
            max_depth: Maximum number of propagation steps (layers). Defaults to None
                (unlimited).

        Returns:
            The NII with expanded labels.
        """
        self.assert_affine(reference_mask)
        if _do_crop:
            crop = reference_mask.compute_crop(0,5,raise_error=False)
            s = self.apply_crop(crop)
            reference_mask = reference_mask.apply_crop(crop)
        else:
            s = self
        self_mask = s.compute_surface_mask().get_seg_array().copy()
        self_mask_org = s.get_seg_array().copy()
        ref_mask = np.clip(reference_mask.get_seg_array(), 0, 1)
        ref_mask[self_mask_org != 0] = 0
        searched = np.clip(self_mask,0,1).astype(np.uint8)

        # Define neighborhood kernel
        if axis is None:
            kernel = [(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)]
        else:
            if isinstance(axis,str):
                axis = self.get_axis(axis)
            if axis == 0:
                kernel = [(0,1,0),(0,0,1),(0,-1,0),(0,0,-1)]
            elif axis == 1:
                kernel = [(1,0,0),(0,0,1),(-1,0,0),(0,0,-1)]
            elif axis == 2:
                kernel = [(1,0,0),(0,1,0),(-1,0,0),(0,-1,0)]
            else:
                raise NotImplementedError(axis)

        search = deque()
        coords = np.where(self_mask != 0)
        def _add_idx(x,y,z,v,d):
            for x1,y1,z1 in kernel:
                a = x+x1
                b = y+y1
                c = z+z1

                if a < 0 or b < 0 or c < 0:
                    continue
                if a >= self_mask.shape[0] or b >= self_mask.shape[1] or c >= self_mask.shape[2]:
                    continue
                #try:
                if searched[a,b,c] == 0 and ref_mask[a,b,c] == 1:
                    search.append((a,b,c,v,d))
                #except Exception:
                #    pass
        def _infect(a,b,c,v,d):
            if d-1 == max_depth:
                return
            if searched[x,y,z] != 0:
                return
            if ref_mask[x,y,z] == 0:
                return
            #print(a,b,c)
            searched[a,b,c] = 1
            self_mask[a,b,c] = v
            _add_idx(a,b,c,v,d)

        from tqdm import tqdm
        for x,y,z in tqdm(zip(coords[0],coords[1],coords[2]),total=len(coords[0]),disable=not verbose,desc="Collecting Surface"):
            _add_idx(x,y,z,self_mask[x,y,z],0)
        while len(search) != 0:
            search2 = search
            search = deque()
            for _ in tqdm(range(len(search2)),disable=not verbose,desc="infect"):
                x,y,z,v,d = search2.popleft()
                _infect(x,y,z,v,d+1)
        self_mask[self_mask == 0] = self_mask_org[self_mask == 0]
        if _do_crop:
            if inplace:
                self[crop] = self_mask
                return self
            else:
                arr = self.get_array()
                arr[crop] = self_mask
                self_mask = arr
        return self.set_array(self_mask,inplace=inplace)

    def infect_(self: NII, reference_mask: NII, verbose=True, axis: int | str | None = None,_do_crop=True) -> Self:
        """In-place variant of `infect`."""
        return self.infect(reference_mask, inplace=True,verbose=verbose,axis=axis,_do_crop=_do_crop)

    def map_labels(self, label_map:LABEL_MAP , verbose:logging=True, inplace=False) -> Self:
        """Maps labels in the given NIfTI image according to the label_map dictionary.

        Args:
            label_map (dict): A dictionary that maps the original label values (str or int) to the new label values (int).
                For example, `{"T1": 1, 2: 3, 4: 5}` will map the original labels "T1", 2, and 4 to the new labels 1, 3, and 5, respectively.
            verbose (bool): Whether to print the label mapping and the number of labels reassigned. Default is True.
            inplace (bool): Whether to modify the current NIfTI image object in place or create a new object with the mapped labels.
                Default is False.

        Returns:
            If inplace is True, returns the current NIfTI image object with mapped labels. Otherwise, returns a new NIfTI image object with mapped labels.
        """
        data_orig = self.get_seg_array()
        labels_before = [v for v in np_unique(data_orig) if v > 0]
        # enforce keys to be str to support both str and int
        label_map_ = {
            (v_name2idx[k] if k in v_name2idx else int(k)): (
                v_name2idx[v] if v in v_name2idx else (0 if v is None else int(v))
            )
            for k, v in label_map.items()
        }
        log.print("label_map_ =", label_map_, verbose=verbose)
        data = np_map_labels(data_orig, label_map_)
        labels_after = [v for v in np_unique(data) if v > 0]
        log.print(
                "N =",
                len(label_map_),
                "labels reassigned, before labels: ",
                labels_before,
                " after: ",
                labels_after,verbose=verbose
            )
        nii = data.astype(np.uint16), self.affine, self.header
        if inplace:
            self.nii = nii
            return self
        return self.copy(nii)

    def map_labels_(self, label_map: LABEL_MAP, verbose: logging = True) -> Self:
        """In-place variant of `map_labels`."""
        return self.map_labels(label_map,verbose=verbose,inplace=True)

    def copy(self, nib: Nifti1Image | _unpacked_nii | None = None, seg=None) -> NII:
        """Returns a deep copy of this NII, optionally with a replacement image.

        Args:
            nib: If provided, the copy will use this image data instead of copying
                the current array. Accepts a ``Nifti1Image`` or an
                ``(array, affine, header)`` tuple. Defaults to None (copy current data).
            seg: Override the ``seg`` flag in the returned copy. Defaults to None
                (keep the current value).

        Returns:
            A new NII with the same ``c_val`` and ``info`` as this instance.
        """
        if nib is None:
            nib = (self.get_array().copy(), self.affine.copy(), self.header.copy())
        return NII(nib,seg=self.seg if seg is None else seg,c_val = self.c_val,info = self.info)


    def flip(self, axis: int | str, keep_global_coords=True, inplace=False) -> Self:
        """Flips the image along a spatial axis.

        Args:
            axis: The axis to flip, specified as an integer index or an anatomical
                direction string (e.g. ``"S"``, ``"R"``).
            keep_global_coords: If True, the flip is implemented via a reorientation
                so that world-space coordinates are preserved. If False, the array is
                flipped in-place without adjusting the affine. Defaults to True.
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            The flipped NII.
        """
        axis = self.get_axis(axis) if not isinstance(axis,int) else axis
        if keep_global_coords:
            orient = list(self.orientation)
            orient[axis] = _same_direction[orient[axis]]
            return self.reorient(tuple(orient),inplace=inplace)
        else:
            return self.set_array(np.flip(self.get_array(),axis),inplace=inplace)

    def clone(self) -> NII:
        """Returns a deep copy of this NII (alias for ``copy()``)."""
        return self.copy()
    @secure_save
    def save(self, file: str | Path, make_parents=True, verbose: logging = True, dtype=None) -> None:
        """Saves this NII to a NIfTI file on disk.

        Args:
            file: Destination file path (e.g. ``"/path/to/image.nii.gz"``).
            make_parents: If True, parent directories are created automatically.
                Defaults to True.
            verbose: If True (or a non-zero int), logs the save path and dtype.
                Defaults to True.
            dtype: Override the on-disk dtype. Defaults to None (use the array dtype).
        """
        if make_parents:
            Path(file).parent.mkdir(0o777,exist_ok=True,parents=True)
        if str(file).endswith(".nrrd"):
            return self.save_nrrd(file,verbose=verbose)

        arr = self.get_array() if not self.seg else self.get_seg_array()
        if isinstance(arr,np.floating) and self.seg:
            self.set_dtype_("smallest_uint")
            arr = self.get_array() if not self.seg else self.get_seg_array()

        self.header.set_data_dtype(arr.dtype)
        out = Nifti1Image(arr, self.affine,self.header)#,dtype=arr.dtype)
        if dtype is not None:
            out.set_data_dtype(dtype)
        if out.header["qform_code"] == 0: #NIFTI_XFORM_UNKNOWN Will cause an error for some rounding of the affine in ITKSnap ...
            # 1 means Scanner coordinate system
            # 2 means align (to something) coordinate system
            out.header["qform_code"] = 2 if self.seg else 1
        nib.save(out, file) #type: ignore
        log.print(f"Save {file} as {out.get_data_dtype()}",verbose=verbose,ltype=Log_Type.SAVE)

    @secure_save
    def save_nrrd(self:Self, file: str | Path|bids_files.BIDS_FILE,make_parents=True,verbose:logging=True,**args) -> None:
        """Save an NII object to an NRRD file.

        Args:
            nii_obj (NII): The NII object to be saved.
            path (str | Path): The file path where the NRRD file will be saved.

        Raises:
            ImportError: If the `pynrrd` package is not installed.
            ValueError: If the affine matrix is invalid or incompatible.
        """
        try:
            import nrrd
        except ModuleNotFoundError:
            raise ImportError("The `pynrrd` package is required but not installed. Install it with `pip install pynrrd`." ) from None
        if isinstance(file, bids_files.BIDS_FILE):
            file = file.file['nrrd']
        from TPTBox.core.internal.slicer_nrrd import save_slicer_nrrd
        save_slicer_nrrd(self,file,make_parents=make_parents,verbose=verbose,**args)


    def to_stls(
        self: NII,
        out_path: Path | dict[int, Path] | None = None,
        bb: tuple | None = None,
        to_world: bool = True,
        include_normals: bool = False,
        number_path: bool | None = None,
    ) -> dict[int, Mesh]:
        """Convert all labels in a segmentation into STL meshes.

        This function iterates over all unique labels in the segmentation and
        applies `to_stl_single` to each label independently.

        Args:
            seg (NII):
                Segmentation object containing one or more labels.
            out_path (Path | dict[int, Path] | None, optional):
                Output specification:
                    - Path → save all meshes into the same directory or file pattern
                    - dict[label, Path] → per-label output paths
                    - None → do not save meshes
            bb (tuple | None, optional):
                Optional bounding box (e.g., slices). If provided and `to_world=False`,
                vertex coordinates are shifted by the bounding box start indices.
            to_world (bool, optional):
                If True, transform vertices from voxel coordinates into world
                coordinates using `seg.affine`. Defaults to True.
            include_normals (bool, optional):
                If True, compute per-face normals for each mesh using
                `mesh.Mesh.update_normals()`. Defaults to False.
            number_path (bool | None, optional):
                Controls filename numbering when saving:
                    - If None (default):
                        Automatically set to True if `out_path` is not a dict,
                        and False otherwise.
                    - If True:
                        Append the label to the output filename.
                    - If False:
                        Do not modify the filename.

        Returns:
            dict[int, mesh.Mesh]:
                Dictionary mapping each label to its corresponding STL mesh.

        Notes:
            - Each label is processed independently via `to_stl_single`.
            - Padding is applied internally to ensure closed surfaces.
            - STL format stores only triangle geometry and per-face normals;
            it does not support per-vertex attributes such as scalar values.
            - If `to_world=True`, all meshes are returned in physical space
            (e.g., millimeters).
        """
        ret = {}

        # Resolve default numbering behavior
        if number_path is None:
            number_path = not isinstance(out_path, dict)

        for i in self.unique():
            ret[i] = self.to_stl(
                label=i, out_path=out_path, bb=bb, to_world=to_world, include_normals=include_normals, number_path=number_path
            )

        return ret


    def to_stl(
        self: NII,
        label: int|Enum|Sequence[int]|Sequence[Enum],
        out_path: Path | dict[int, Path] | None = None,
        bb: tuple | None = None,
        to_world: bool = True,
        include_normals: bool = False,
        number_path=False,
    ) -> Mesh:
        """Convert a binary segmentation label into an STL surface mesh using marching cubes.

        The function extracts a single label from a segmentation, runs marching cubes
        to generate a triangular surface mesh, and optionally transforms the vertices
        into world (physical) coordinates using the NIfTI affine.

        Args:
            seg (NII):
                Segmentation object containing a 3D mask.
            label (int, optional):
                Label value to extract from the segmentation. Defaults to 1.
            out_path (Path | dict[int, Path] | None, optional):
                Output specification:
                    - Path → save mesh to this file
                    - dict[label, Path] → per-label output path
                    - None → do not save mesh
            bb (tuple | None, optional):
                Optional bounding box (e.g., slices). If provided and `to_world=False`,
                vertex coordinates are shifted by the bounding box start indices.
            to_world (bool, optional):
                If True, transform vertices from voxel coordinates into world
                coordinates using `seg.affine`. Defaults to True.
            include_normals (bool, optional):
                If True, compute and include per-face normals in the returned mesh
                using `mesh.Mesh.update_normals()`. Note that STL supports only
                one normal per face. Defaults to False.
            number_path (bool, optional):
                If True, append the label to the output filename when saving.
                Defaults to False.

        Returns:
            mesh.Mesh:
                The generated STL mesh. If `include_normals=True`, normals are stored
                in `mesh.normals` (per face).

        Notes:
            - Marching cubes is applied to a padded volume to ensure closed surfaces
            at the segmentation boundaries.
            - Vertex coordinates are initially in voxel space and shifted to account
            for padding.
            - If `to_world=True`, vertices are transformed to physical space (e.g. mm)
            using the affine matrix of the input segmentation.
            - STL format stores only triangle geometry and per-face normals; it does
            not support per-vertex attributes such as scalar values from marching cubes.
        """
        from stl import mesh
        seg = self.extract_label(label)
        # Prepare binary mask
        seg_arr = np.pad(seg.clamp(0, 1).get_array(), 1)
        # Marching cubes (voxel coordinates)
        try:
            verts, faces, normals, values = marching_cubes(seg_arr, gradient_direction="ascent", step_size=1)
        except RuntimeError as e:
            raise RuntimeError(str(e),f"{label=}, {self.unique()}, {out_path=}") from None
        # Remove padding offset (since we padded by 1 voxel)
        verts -= 1
        # Apply bounding box offset (still voxel space)
        if bb is not None and not to_world:
            verts += np.array([b.start for b in bb])
        # Convert to world coordinates using affine
        if to_world:
            affine = self.affine  # (4, 4)
            verts_h = np.c_[verts, np.ones(len(verts))]  # homogeneous coords
            verts = (affine @ verts_h.T).T[:, :3]

        # Build STL mesh
        cube: mesh.Mesh = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
        for i, f in enumerate(faces):
            cube.vectors[i] = verts[f]

        # Save if requested
        if out_path is not None:
            out_path = out_path.get(label) if isinstance(out_path, dict) else out_path

            if out_path is not None:
                out_path = Path(out_path)
                if out_path.is_dir():
                    out_path = out_path / f"mask_{label}.stl"
                elif number_path:
                    out_path.with_name(f"{out_path.stem}_{label}.stl")
                log.on_save(f"Saving STL to {out_path}")
                out_path.parent.mkdir(exist_ok=True)
                cube.save(str(out_path))

        if include_normals:
            cube.update_normals()

        return cube

    def __str__(self) -> str:
        return f"{super().__str__()}, seg={self.seg}" # type: ignore
    def __repr__(self)-> str:
        return self.__str__()
    def __array__(self,dtype=None):
            self._unpack()
            if dtype is None:
                return self._arr
            else:
                return self._arr.astype(dtype, copy=False)
    def __array_wrap__(self, array,context=None, return_scalar=False):
        assert not return_scalar,context
        if array.shape != self.shape:
            raise SyntaxError(f"Function call induce a shape change of nii image. Before {self.shape} after {array.shape}. {context}")
        return self.set_array(array)
    def __getitem__(self, key)-> Any:
        if isinstance(key,Sequence):
            ellipsis_type = type(Ellipsis)

            if all(isinstance(k, (slice, ellipsis_type)) for k in key):
                #if all(k.step is not None and k.step == 1 for k in key):
                #    raise NotImplementedError(f"Slicing is not implemented. Attempted {key}")
                if len(key)!= len(self.shape) or Ellipsis in key:
                    raise ValueError(f"Number slices must have exact number of slices like in dimension. Attempted: {key} - Shape {self.shape}")
                return self.apply_crop(key) # type: ignore
            elif  all(isinstance(k, int) for k in key):
                if len(key)!= len(self.shape):
                    raise ValueError(f"Number ints must have exact number of slices like in dimension. Attempted: {key} - Shape {self.shape}")
                self._unpack()
                return self._arr.__getitem__(key)
            else:
                self._unpack()
                return self._arr.__getitem__(key)
                #raise TypeError("Invalid argument type:", (key))
        elif isinstance(key,self.__class__):
            return self.get_array()[key.get_array()==1]
        elif isinstance(key,np.ndarray):
            return self.get_array()[key]
        elif isinstance(key,slice):
            self.__getitem__((key,Ellipsis,Ellipsis))
        else:
            raise TypeError("Invalid argument type:", type(key))
    def __setitem__(self, key,value):
        if isinstance(key,self.__class__):
            key = key.get_array()==1
        self._unpack()
        self.__divergent = True
        self._arr[key] = value


    @classmethod
    def suppress_dtype_change_printout_in_set_array(cls, value=True) -> None:
        """Globally suppresses the log message emitted when ``set_array`` changes the dtype.

        Args:
            value: Set to True to suppress the message, False to re-enable it.
                Defaults to True.
        """
        global suppress_dtype_change_printout_in_set_array  # noqa: PLW0603
        suppress_dtype_change_printout_in_set_array = value
    def is_intersecting_vertical(self, b: Self, min_overlap=40) -> bool:
        """Tests whether this image and ``b`` overlap vertically in global (world) space.

        Uses the z-axis extent of both images' affines. Assumes the same rotation.

        Args:
            b: The other NII to test intersection against.
            min_overlap: Minimum number of mm that must overlap. Defaults to 40.

        Returns:
            True if the two images overlap by at least ``min_overlap`` mm along z.

        Note:
            This method is untested; prefer ``get_intersecting_volume`` for reliable results.
        """
        #warnings.warn('is_intersecting is untested use get_intersecting_volume instead')
        x1 = self.affine.dot([0, 0, 0, 1])[:3] # type: ignore
        x2 = self.affine.dot((*self.shape, 1))[:3]# type: ignore
        y1 = b.affine.dot([0, 0, 0, 1])[:3]# type: ignore
        y2 = b.affine.dot((*b.shape, 1))[:3]# type: ignore
        max_v = max(x1[2],x2[2])- min_overlap
        min_v = min(x1[2],x2[2])+ min_overlap
        if min_v < y1[2] < max_v:
            return True
        if min_v < y2[2] < max_v:
            return True

        max_v = max(y1[2],y2[2])- min_overlap
        min_v = min(y1[2],y2[2])+ min_overlap
        if min_v < x1[2] < max_v:
            return True
        return min_v < x2[2] < max_v

    def get_intersecting_volume(self, b: Self) -> float:
        """Returns the number of voxels in ``self``'s grid that overlap with image ``b``.

        ``b`` is binarised (all non-zero → 1) and resampled into ``self``'s voxel
        grid using constant-mode (zero fill) before summing the overlap.

        Args:
            b: The other image whose spatial extent is tested for overlap.

        Returns:
            The count of overlapping voxels as a float.
        """
        b = to_nii(b).copy() # type: ignore
        b.nii = Nifti1Image(b.get_array()*0+1,affine=b.affine)
        b.seg = True
        b.set_dtype_(np.uint8)
        b.c_val = 0
        b = b.resample_from_to(self,c_val=0,verbose=False,mode="constant") # type: ignore
        return b.get_array().sum()

    def extract_background(self, inplace=False) -> Self:
        """Returns a binary mask where all background (0) voxels are set to 1.

        Args:
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            An NII with 1 where the original segmentation had 0, and 0 elsewhere.

        Raises:
            AssertionError: If ``seg=False``.
        """
        assert self.seg, "extracting the background only makes sense for a segmentation mask"
        arr_bg = self.get_seg_array()
        arr_bg = np_extract_label(arr_bg, label=0, to_label=1)
        return self.set_array(arr_bg, inplace, False)

    def extract_label(self,label:int|Enum|Sequence[int]|Sequence[Enum]|None, keep_label=False,inplace=False) -> Self:
        """If this NII is a segmentation you can single out one label with [0,1]."""
        assert self.seg, "extracting a label only makes sense for a segmentation mask"
        if label is None:
            if keep_label:
                return self.copy() if inplace else self
            else:
                return self.clamp(0,1,inplace=inplace)
        seg_arr = self.get_seg_array()

        if isinstance(label, Sequence):
            label_int:list[int] = [idx.value if isinstance(idx,Enum) else idx for idx in label]
            assert 0 not in label_int, 'Zero label does not make sense. This is the background'
            seg_arr = np_extract_label(seg_arr, label_int, to_label=1, inplace=True)
        else:
            if isinstance(label,Enum):
                label = label.value
            if isinstance(label,str):
                label = int(label)

            assert label != 0, 'Zero label does not make sense. This is the background'
            seg_arr = np_extract_label(seg_arr, label, to_label=1, inplace=True)
        if keep_label:
            seg_arr = seg_arr * self.get_seg_array()
        return self.set_array(seg_arr,inplace=inplace)
    def extract_label_(self, label: int | Enum | Sequence[int] | Sequence[Enum], keep_label=False) -> Self:
        """In-place variant of `extract_label`."""
        return self.extract_label(label,keep_label,inplace=True)
    def remove_labels(self,label:int|Enum|Sequence[int]|Sequence[Enum], inplace=False, verbose:logging=True, removed_to_label=0) -> Self:
        """If this NII is a segmentation you can single out one label."""
        assert label != 0, 'Zero label does not make sens.  This is the background'
        seg_arr = self.get_seg_array()
        if not isinstance(label,Sequence):
            label = [label] # type: ignore
        for l in label:
            if isinstance(l, list):
                for g in l:
                    seg_arr[seg_arr == g] = removed_to_label
            else:
                seg_arr[seg_arr == l] = removed_to_label
        return self.set_array(seg_arr,inplace=inplace, verbose=verbose)
    def remove_labels_(self, label: int | Enum | Sequence[int] | Sequence[Enum], removed_to_label=0, verbose: logging = True) -> Self:
        """In-place variant of `remove_labels`."""
        return self.remove_labels(label,inplace=True,removed_to_label=removed_to_label,verbose=verbose)
    def apply_mask(self, mask: Self, inplace=False) -> Self:
        """Zeros out all voxels in this image that are background (0) in ``mask``.

        Args:
            mask: A segmentation NII used as the mask. Any non-zero voxel in the
                mask is treated as foreground (1). Must have the same shape as
                this image.
            inplace: If True, modifies this NII in place. Defaults to False.

        Returns:
            The masked NII.

        Raises:
            AssertionError: If shapes do not match.
        """
        assert mask.shape == self.shape, f"[def apply_mask] Mask and Shape are not equal: \nMask - {mask},\nSelf - {self})"
        seg_arr = mask.get_seg_array()
        seg_arr[seg_arr != 0] = 1
        arr = self.get_array()
        return self.set_array(arr*seg_arr,inplace=inplace)

    def unique(self,verbose:logging=False,crop=False) -> list[int]:
        """Returns all integer labels WITHOUT 0. Must be performed only on a segmentation nii."""
        arr = self.get_seg_array()
        if crop:
            try:
                arr = arr[np_bbox_binary(arr)]
            except Exception:
                pass
        out = np_unique_withoutzero(arr)
        log.print(out,verbose=verbose)
        return out
    def voxel_volume(self) -> float:
        """Returns the volume of a single voxel in mm³ (product of all zoom values)."""
        product = math.prod(self.spacing)
        return product

    def volumes(self, include_zero: bool = False, in_mm3=False,sort=False) -> dict[int, float]|dict[int, int]:
        """Returns a dict stating how many pixels are present for each label."""
        dic =  np_volume(self.get_seg_array(), include_zero=include_zero)
        if sort:
            dic = dict(sorted(dic.items()))
        if in_mm3:
            voxel_size = self.voxel_volume()
            dic = {k:v*voxel_size for k,v in dic.items()}
        return dic
    def translate_arr(
        self,
        translation_vector: tuple[int, int, int] | dict[str,int]| dict[DIRECTIONS,int],
        inplace: bool = False,
        verbose: bool = True
    ) -> Self:
        """Translate the NIfTI image array by a given vector.

        The vector can be a tuple of voxel offsets or a dict keyed by anatomical
        direction letters (``'S'``, ``'I'``, ``'R'``, ``'L'``, ``'P'``, ``'A'``).

        Args:
            translation_vector (tuple or dict): Vector to translate with. Can be a tuple of ints
                                                or a dict with keys from 'SIRLPA' and int values.
            inplace (bool): Whether to modify the array in place.
            verbose (bool): Whether to print log messages.

        Returns:
            NII: Translated image.
        """
        log.print("Translating array", end="\r", verbose=verbose)
        arr = self.get_array()

        if isinstance(translation_vector, dict):
            # Start with zero translation for all axes
            vector = [0] * arr.ndim
            for direction, amount in translation_vector.items():
                axis = self.get_axis(direction=direction) # type: ignore
                sign = +1 if direction in self.orientation else -1
                vector[axis] += sign * amount
            v: tuple[int, int, int] = tuple(vector) # type: ignore
        else:
            v = translation_vector
        arr_translated = np_translate_arr(arr, v)
        log.print(f"Translated by {v}; ", verbose=verbose)
        return self.set_array(arr_translated, inplace=inplace)

    def center_of_masses(self) -> dict[int, COORDINATE]:
        """Returns a dict stating the center of mass for each present label (not including zero!)."""
        return np_center_of_mass(self.get_seg_array())

nii_abstract property

nii_abstract: Nifti1Image | _unpacked_nii

Returns the internal representation without forcing reconstruction of the Nifti1Image.

If the data has been unpacked (loaded into memory), returns the (array, affine, header) tuple. Otherwise returns the raw Nifti1Image.

nii property writable

nii: Nifti1Image

Returns the underlying Nifti1Image, reconstructing it if the in-memory array has diverged.

The reconstruction synchronises the header dtype and slope/intercept values with the current array. Use nii_abstract if you want to avoid this reconstruction overhead.

shape property

shape: tuple[int, int, int]

Spatial shape of the image array (x, y, z), or more dims for 4-D images.

dtype property writable

dtype: type

NumPy dtype of the voxel data array.

header property

header: Nifti1Header

NIfTI-1 header associated with this image.

affine property writable

affine: AFFINE

(4, 4) affine matrix mapping voxel indices to world (mm) coordinates.

orientation property writable

orientation: AX_CODES

Axis codes describing the image orientation, e.g. ('R', 'A', 'S').

dims property

dims: int

Number of spatial dimensions (typically 3 for a standard NIfTI volume).

zoom property writable

zoom: ZOOMS

Voxel sizes in mm along each spatial axis, e.g. (1.0, 1.0, 1.5).

origin property writable

origin: tuple[float, float, float]

World-space coordinates (in mm) of voxel index (0, 0, 0).

rotation property

rotation: ndarray

Pure rotation matrix extracted from the affine (affine upper-left block divided by zoom).

direction property

direction: list

Flattened rotation matrix as a list (row-major), compatible with ITK/SimpleITK conventions.

direction_itk property

direction_itk: list

Flattened rotation matrix with ITK LPS sign convention (first two rows negated).

orientation_ornt property

orientation_ornt: ndarray

Nibabel orientation array (shape (ndim, 2)) encoding axis permutation and flip.

is_empty property

is_empty: bool

Checks if the array in the nifti is empty.

Returns:

Name Type Description
bool bool

Whether the nifti is empty or not

from_numpy classmethod

from_numpy(arr: ndarray, affine: ndarray, seg=False, c_val=None, desc: str | None = None, info=None) -> Self

Creates an NII instance from a numpy array and an affine matrix.

Parameters:

Name Type Description Default
arr ndarray

The voxel data array (shape must match the spatial dimensions implied by affine).

required
affine ndarray

A (4, 4) affine transformation matrix mapping voxel indices to world coordinates.

required
seg

Whether the image is a segmentation mask (integer-labelled). Defaults to False.

False
c_val

Background / fill value used during resampling. Defaults to None (inferred from data for images; 0 for segmentations).

None
desc str | None

Optional description string stored in the NIfTI header descrip field.

None
info

Optional dict of arbitrary metadata attached to this instance.

None

Returns:

Type Description
Self

A new NII wrapping the given array and affine.

Source code in TPTBox/core/nii_wrapper.py
@classmethod
def from_numpy(cls, arr: np.ndarray, affine: np.ndarray, seg=False, c_val=None, desc:str|None=None, info=None) -> Self:
    """Creates an NII instance from a numpy array and an affine matrix.

    Args:
        arr: The voxel data array (shape must match the spatial dimensions implied by affine).
        affine: A (4, 4) affine transformation matrix mapping voxel indices to world coordinates.
        seg: Whether the image is a segmentation mask (integer-labelled). Defaults to False.
        c_val: Background / fill value used during resampling. Defaults to None (inferred
            from data for images; 0 for segmentations).
        desc: Optional description string stored in the NIfTI header ``descrip`` field.
        info: Optional dict of arbitrary metadata attached to this instance.

    Returns:
        A new NII wrapping the given array and affine.
    """
    nii = nib.nifti1.Nifti1Image(arr,affine)
    return NII(nii=nii, seg=seg, c_val=c_val, desc=desc, info=info)

load classmethod

load(path: Image_Reference, seg: bool, c_val: float | None = None) -> Self

Loads a NIfTI image from a file path or image reference.

Parameters:

Name Type Description Default
path Image_Reference

File path (str or Path), an existing NII, a Nifti1Image, or a BIDS_FILE pointing to the image to load.

required
seg bool

Whether the image is a segmentation mask. When True the array dtype is coerced to the smallest unsigned integer type that can hold all values.

required
c_val float | None

Background / fill value. Defaults to None.

None

Returns:

Type Description
Self

A new NII loaded from the given path.

Source code in TPTBox/core/nii_wrapper.py
@classmethod
def load(cls, path: Image_Reference, seg: bool, c_val: float | None = None) -> Self:
    """Loads a NIfTI image from a file path or image reference.

    Args:
        path: File path (str or Path), an existing NII, a Nifti1Image, or a BIDS_FILE
            pointing to the image to load.
        seg: Whether the image is a segmentation mask. When True the array dtype is
            coerced to the smallest unsigned integer type that can hold all values.
        c_val: Background / fill value. Defaults to None.

    Returns:
        A new NII loaded from the given path.
    """
    nii= to_nii(path,seg)
    if seg:
        nii = nii.set_dtype("smallest_uint")
    nii.c_val = c_val
    return nii

load_nrrd classmethod

load_nrrd(path: str | Path, seg: bool, verbos=False)

Load an NRRD file and convert it into a Nifti1Image object.

Parameters:

Name Type Description Default
path str | Path

The file path to the NRRD file to be loaded.

required
seg bool

A flag indicating if the data represents segmentation data.

required

Returns:

Name Type Description
NII

An NII object containing the loaded Nifti1Image and the segmentation flag.

Raises:

Type Description
ImportError

If the pynrrd package is not installed.

FileNotFoundError

If the specified NRRD file cannot be found.

Example

nii = cls.load_nrrd("example.nrrd", seg=True) print(nii)

Source code in TPTBox/core/nii_wrapper.py
@classmethod
def load_nrrd(cls, path: str | Path, seg: bool,verbos=False):
    """Load an NRRD file and convert it into a Nifti1Image object.

    Args:
        path (str | Path): The file path to the NRRD file to be loaded.
        seg (bool): A flag indicating if the data represents segmentation data.

    Returns:
        NII: An NII object containing the loaded Nifti1Image and the segmentation flag.

    Raises:
        ImportError: If the `pynrrd` package is not installed.
        FileNotFoundError: If the specified NRRD file cannot be found.

    Example:
        >>> nii = cls.load_nrrd("example.nrrd", seg=True)
        >>> print(nii)
    """
    try:
        import nrrd  # pip install pynrrd, if pynrrd is not already installed
    except ModuleNotFoundError:
        raise ImportError("The `pynrrd` package is required but not installed. Install it with `pip install pynrrd`.") from None
    from TPTBox.core.internal.slicer_nrrd import load_slicer_nrrd
    return load_slicer_nrrd(path,seg,verbos=verbos)

load_bids classmethod

load_bids(nii_bids: BIDS_FILE) -> NII

Loads an NII from a BIDS_FILE object, inferring seg and c_val from the format.

Supports .nii, .nii.gz, .nrrd, and any format readable by SimpleITK. The seg flag is set to True when the BIDS file's interpolation order is 0 (i.e., it is a label map). CT images default to c_val=-1024; others to 0.

Parameters:

Name Type Description Default
nii_bids BIDS_FILE

A BIDS_FILE whose file dict contains at least one of the supported image format keys.

required

Returns:

Type Description
NII

A new NII loaded from the BIDS file.

Raises:

Type Description
AssertionError

If no readable image format is found in nii_bids.

Source code in TPTBox/core/nii_wrapper.py
@classmethod
def load_bids(cls, nii_bids: bids_files.BIDS_FILE) -> NII:
    """Loads an NII from a BIDS_FILE object, inferring seg and c_val from the format.

    Supports ``.nii``, ``.nii.gz``, ``.nrrd``, and any format readable by SimpleITK.
    The ``seg`` flag is set to True when the BIDS file's interpolation order is 0
    (i.e., it is a label map). CT images default to ``c_val=-1024``; others to 0.

    Args:
        nii_bids: A BIDS_FILE whose ``file`` dict contains at least one of the
            supported image format keys.

    Returns:
        A new NII loaded from the BIDS file.

    Raises:
        AssertionError: If no readable image format is found in ``nii_bids``.
    """
    nifty = None
    if "nii" in nii_bids.file:
        path = nii_bids.file['nii']
        nifty = nib.load(path)
    elif "nii.gz" in nii_bids.file:
        path = nii_bids.file['nii.gz']
        nifty = nib.load(path)
    elif "nrrd" in nii_bids.file:
        path = nii_bids.file['nrrd']
        nifty = NII.load_nrrd(path,seg=False)
    else:
        import SimpleITK as sitk  # noqa: N813

        from TPTBox.core.sitk_utils import sitk_to_nib
        for f in nii_bids.file:
            try:
                img = sitk.ReadImage(nii_bids.file[f])
                nifty =  sitk_to_nib(img)
            except Exception:
                pass
            break
    if nii_bids.get_interpolation_order() == 0:
        seg = True
        c_val=0
    else:
        seg = False
        c_val = -1024 if "ct" in nii_bids.format.lower() else 0
    assert nifty is not None, f"could not find {nii_bids}"
    return NII(nifty,seg,c_val) # type: ignore

split_4D_image_to_3D

split_4D_image_to_3D() -> list[NII]

Splits a 4-D NIfTI image into a list of 3-D NII objects, one per volume.

Returns:

Type Description
list[NII]

A list of NII objects, each containing one 3-D volume from the 4-D image.

list[NII]

The affine, header, seg flag, and c_val are copied from the original.

Raises:

Type Description
AssertionError

If the image is not 4-D.

Source code in TPTBox/core/nii_wrapper.py
def split_4D_image_to_3D(self) -> list[NII]:
    """Splits a 4-D NIfTI image into a list of 3-D NII objects, one per volume.

    Returns:
        A list of NII objects, each containing one 3-D volume from the 4-D image.
        The affine, header, seg flag, and c_val are copied from the original.

    Raises:
        AssertionError: If the image is not 4-D.
    """
    assert self.get_num_dims() == 4,self.get_num_dims()
    arr_4d = self.get_array()
    out:list[NII] = []
    for i in range(self.shape[-1]):
        arr = arr_4d[...,i]
        out.append(NII(Nifti1Image(arr, self.affine, self.header.copy()),self.seg,self.c_val,self.header['descrip']))
    return out

set_description

set_description(v: str | None) -> None

Writes a description string into the NIfTI header descrip field.

Parameters:

Name Type Description Default
v str | None

Description string. When None, defaults to "seg" for segmentations and "img" for regular images.

required
Source code in TPTBox/core/nii_wrapper.py
def set_description(self, v: str | None) -> None:
    """Writes a description string into the NIfTI header ``descrip`` field.

    Args:
        v: Description string. When None, defaults to ``"seg"`` for segmentations
            and ``"img"`` for regular images.
    """
    if v is None:
        self.header['descrip'] = "seg" if self.seg else "img"
    else:
        self.header['descrip'] = v

get_c_val

get_c_val(default: float | None = None) -> float

Returns the background / fill value for this image.

For segmentations the fill value is always 0. For images it is resolved from self.c_val, the default argument, or the minimum value of the array (computed lazily and cached), in that order.

Parameters:

Name Type Description Default
default float | None

Fallback value if self.c_val is None. Defaults to None.

None

Returns:

Type Description
float

The background fill value as a float.

Source code in TPTBox/core/nii_wrapper.py
def get_c_val(self, default: float | None = None) -> float:
    """Returns the background / fill value for this image.

    For segmentations the fill value is always 0. For images it is resolved from
    ``self.c_val``, the ``default`` argument, or the minimum value of the array
    (computed lazily and cached), in that order.

    Args:
        default: Fallback value if ``self.c_val`` is None. Defaults to None.

    Returns:
        The background fill value as a float.
    """
    if self.seg:
        return 0
    if self.c_val is not None:
        return self.c_val
    if default is not None:
        return default
    if self.__min is None:
        self.__min = self.min()
    return self.__min

get_seg_array

get_seg_array() -> np.ndarray

Returns a copy of the voxel array, emitting a warning if seg is False.

Returns:

Type Description
ndarray

A copy of the underlying numpy array interpreted as a segmentation mask.

Source code in TPTBox/core/nii_wrapper.py
def get_seg_array(self) -> np.ndarray:
    """Returns a copy of the voxel array, emitting a warning if ``seg`` is False.

    Returns:
        A copy of the underlying numpy array interpreted as a segmentation mask.
    """
    if not self.seg:
        warnings.warn(
            "requested a segmentation array, but NII is not set as a segmentation", UserWarning, stacklevel=5
        )
    self._unpack()
    return self._arr.copy() #type: ignore

get_array

get_array() -> np.ndarray

Returns a copy of the voxel data array.

Delegates to get_seg_array when seg=True (which adds a warning if the flag is inconsistent), otherwise returns a plain copy.

Returns:

Type Description
ndarray

A copy of the underlying numpy array.

Source code in TPTBox/core/nii_wrapper.py
def get_array(self) -> np.ndarray:
    """Returns a copy of the voxel data array.

    Delegates to ``get_seg_array`` when ``seg=True`` (which adds a warning if
    the flag is inconsistent), otherwise returns a plain copy.

    Returns:
        A copy of the underlying numpy array.
    """
    if self.seg:
        return self.get_seg_array()
    self._unpack()
    return self._arr.copy()

numpy

numpy(*_args) -> np.ndarray

Returns a copy of the voxel data as a numpy array (alias for get_array).

Source code in TPTBox/core/nii_wrapper.py
def numpy(self, *_args) -> np.ndarray:
    """Returns a copy of the voxel data as a numpy array (alias for ``get_array``)."""
    return self.get_array()

set_array

set_array(arr: ndarray | Self, inplace=False, verbose: logging = False, seg=None) -> Self

Returns an NII whose voxel data is replaced by arr, preserving affine and header.

Note: This function works out-of-place by default, like all other methods.

Parameters:

Name Type Description Default
arr ndarray | Self

New voxel data. May be a numpy array or another NII (in which case get_array() is called automatically). Boolean arrays are cast to uint8; float16 to float32; floating arrays are cast to int32 when self.seg is True.

required
inplace

If True, modifies this NII in place and returns self. Defaults to False.

False
verbose logging

Controls verbosity of dtype-change log messages. Defaults to False.

False
seg

Override the seg flag on the returned/modified NII. Defaults to None (keep the current value).

None

Returns:

Type Description
Self

The modified NII (self when inplace=True, a new NII otherwise).

Source code in TPTBox/core/nii_wrapper.py
def set_array(self, arr: np.ndarray | Self, inplace=False, verbose: logging = False, seg=None) -> Self:  # noqa: ARG002
    """Returns an NII whose voxel data is replaced by ``arr``, preserving affine and header.

    Note: This function works out-of-place by default, like all other methods.

    Args:
        arr: New voxel data. May be a numpy array or another NII (in which case
            ``get_array()`` is called automatically). Boolean arrays are cast to
            ``uint8``; float16 to float32; floating arrays are cast to int32 when
            ``self.seg`` is True.
        inplace: If True, modifies this NII in place and returns ``self``.
            Defaults to False.
        verbose: Controls verbosity of dtype-change log messages. Defaults to False.
        seg: Override the ``seg`` flag on the returned/modified NII. Defaults to None
            (keep the current value).

    Returns:
        The modified NII (``self`` when ``inplace=True``, a new NII otherwise).
    """
    if hasattr(arr,"get_array"):
        arr = arr.get_array() # type: ignore
    if arr.dtype == bool:
        arr = arr.astype(np.uint8)
    if arr.dtype == np.float16:
        arr = arr.astype(np.float32)
    if self.seg and isinstance(arr, (np.floating, float)):
        arr = arr.astype(np.int32)
    #if self.dtype == arr.dtype: #type: ignore
    nii:_unpacked_nii = (arr,self.affine,self.header.copy())
    self.header.set_data_dtype(arr.dtype)
    #else:
    #    if not suppress_dtype_change_printout_in_set_array:
    #        log.print(f"'set_array' with different dtype: from {self.nii.dataobj.dtype} to {arr.dtype}",verbose=verbose) #type: ignore
    #    nii2 = Nifti1Image(self.get_array(),self.affine,self.header)
    #    nii2.set_data_dtype(arr.dtype)
    #    nii = (arr,nii2.affine,nii2.header) # type: ignore
    #if all(a is None for a in self.header.get_slope_inter()):
    #    nii.header.set_slope_inter(1,self.get_c_val()) # type: ignore
    if inplace:
        if seg is not None:
            self.seg = seg
        self.nii = nii
        return self
    else:
        return self.copy(nii,seg=seg) # type: ignore

set_array_

set_array_(arr: ndarray, verbose: logging = True) -> Self

In-place variant of set_array.

Source code in TPTBox/core/nii_wrapper.py
def set_array_(self, arr: np.ndarray, verbose: logging = True) -> Self:
    """In-place variant of `set_array`."""
    return self.set_array(arr,inplace=True,verbose=verbose)

set_dtype

set_dtype(dtype: type | Literal['smallest_int', 'smallest_uint'] = np.float32, order: Literal['C', 'F', 'A', 'K'] = 'K', casting: Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe'] = 'unsafe', inplace=False) -> Self

Returns an NII with the voxel array cast to a different dtype.

Parameters:

Name Type Description Default
dtype type | Literal['smallest_int', 'smallest_uint']

Target dtype. The special strings "smallest_uint" and "smallest_int" select the smallest unsigned or signed integer type that can hold all values in the current array. Defaults to np.float32.

float32
order Literal['C', 'F', 'A', 'K']

Memory layout order passed to ndarray.astype. Defaults to "K".

'K'
casting Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe']

Casting rule passed to ndarray.astype. Defaults to "unsafe".

'unsafe'
inplace

If True, converts in place and returns self. Defaults to False.

False

Returns:

Type Description
Self

The NII with the new dtype (self when inplace=True, a new NII otherwise).

Source code in TPTBox/core/nii_wrapper.py
def set_dtype(self, dtype: type | Literal['smallest_int', 'smallest_uint'] = np.float32, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe", inplace=False) -> Self:
    """Returns an NII with the voxel array cast to a different dtype.

    Args:
        dtype: Target dtype. The special strings ``"smallest_uint"`` and
            ``"smallest_int"`` select the smallest unsigned or signed integer
            type that can hold all values in the current array.
            Defaults to ``np.float32``.
        order: Memory layout order passed to ``ndarray.astype``. Defaults to ``"K"``.
        casting: Casting rule passed to ``ndarray.astype``. Defaults to ``"unsafe"``.
        inplace: If True, converts in place and returns ``self``. Defaults to False.

    Returns:
        The NII with the new dtype (``self`` when ``inplace=True``, a new NII otherwise).
    """
    sel = self if inplace else self.copy()
    if dtype == "smallest_uint":
        arr = self.get_array()
        if arr.max()<256:
            dtype = np.uint8
        elif arr.max()<65536:
            dtype = np.uint16
        else:
            dtype = np.int32
    elif dtype == "smallest_int":
        arr = self.get_array()
        if arr.max()<128:
            dtype = np.int8
        elif arr.max()<32768:
            dtype = np.int16
        else:
            dtype = np.int32
    if self.__unpacked:
        self._unpack()
        sel._arr = sel._arr.astype(dtype)
        sel.header.set_data_dtype(dtype)
    else:
        sel.nii.set_data_dtype(dtype)
        if sel.nii.get_data_dtype() != self.dtype: #type: ignore
            sel.nii = Nifti1Image(self.get_array().astype(dtype,casting=casting,order=order),self.affine,self.header)

    return sel

set_dtype_

set_dtype_(dtype: type | Literal['smallest_uint', 'smallest_int'] = np.float32, order: Literal['C', 'F', 'A', 'K'] = 'K', casting: Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe'] = 'unsafe') -> Self

In-place variant of set_dtype.

Source code in TPTBox/core/nii_wrapper.py
def set_dtype_(self, dtype: type | Literal['smallest_uint', 'smallest_int'] = np.float32, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe") -> Self:
    """In-place variant of `set_dtype`."""
    return self.set_dtype(dtype=dtype,order=order,casting=casting, inplace=True)

astype

astype(dtype, order: Literal['C', 'F', 'A', 'K'] = 'K', casting: Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe'] = 'unsafe', subok=True, copy=True) -> Self

NumPy-compatible dtype conversion wrapper.

When subok=True (default), delegates to set_dtype and returns an NII. When subok=False, returns a plain numpy array.

Parameters:

Name Type Description Default
dtype

Target dtype, forwarded to set_dtype or ndarray.astype.

required
order Literal['C', 'F', 'A', 'K']

Memory layout order. Defaults to "K".

'K'
casting Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe']

Casting rule. Defaults to "unsafe".

'unsafe'
subok

If True, returns an NII; if False, returns a numpy array. Defaults to True.

True
copy

When subok=True this maps to inplace (copy=True → inplace=True). Defaults to True.

True

Returns:

Type Description
Self

An NII or numpy array with the requested dtype.

Source code in TPTBox/core/nii_wrapper.py
def astype(self, dtype, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe", subok=True, copy=True) -> Self:
    """NumPy-compatible dtype conversion wrapper.

    When ``subok=True`` (default), delegates to ``set_dtype`` and returns an NII.
    When ``subok=False``, returns a plain numpy array.

    Args:
        dtype: Target dtype, forwarded to ``set_dtype`` or ``ndarray.astype``.
        order: Memory layout order. Defaults to ``"K"``.
        casting: Casting rule. Defaults to ``"unsafe"``.
        subok: If True, returns an NII; if False, returns a numpy array.
            Defaults to True.
        copy: When ``subok=True`` this maps to ``inplace`` (copy=True → inplace=True).
            Defaults to True.

    Returns:
        An NII or numpy array with the requested dtype.
    """
    if subok:
        c = self.set_dtype(dtype,order=order,casting=casting, inplace=copy)
        return c
    else:
        return self.get_array().astype(dtype,order=order,casting=casting, subok=subok,copy=copy)

reorient

reorient(axcodes_to: AX_CODES | str | None = ('P', 'I', 'R'), verbose: logging = False, inplace=False) -> Self

Reorients the input Nifti image to the desired orientation, specified by the axis codes.

Parameters:

Name Type Description Default
axcodes_to tuple

A tuple of three strings representing the desired axis codes. Default value is ("P", "I", "R").

('P', 'I', 'R')
verbose bool

If True, prints a message indicating the orientation change. Default value is False.

False
inplace bool

If True, modifies the input image in place. Default value is False.

False

Returns:

Type Description
Self

If inplace is True, returns None. Otherwise, returns a new instance of the NII class representing the reoriented image.

Note: The nibabel axes codes describe the direction, not the origin, of axes. The direction "PIR+" corresponds to the origin "ASL".

Source code in TPTBox/core/nii_wrapper.py
def reorient(self:Self, axcodes_to: AX_CODES|str|None = ("P", "I", "R"), verbose:logging=False, inplace=False)-> Self:
    """Reorients the input Nifti image to the desired orientation, specified by the axis codes.

    Args:
        axcodes_to (tuple): A tuple of three strings representing the desired axis codes. Default value is ("P", "I", "R").
        verbose (bool): If True, prints a message indicating the orientation change. Default value is False.
        inplace (bool): If True, modifies the input image in place. Default value is False.

    Returns:
        If inplace is True, returns None. Otherwise, returns a new instance of the NII class representing the reoriented image.

    Note:
    The nibabel axes codes describe the direction, not the origin, of axes. The direction "PIR+" corresponds to the origin "ASL".
    """
    # Note: nibabel axes codes describe the direction not origin of axes
    # direction PIR+ = origin ASL
    if isinstance(axcodes_to,str):
        axcodes_to = tuple(axcodes_to)
    if axcodes_to is not None:
        aff = self.affine
        ornt_fr = self.orientation_ornt
        arr = self.get_array()
        ornt_to = nio.axcodes2ornt(axcodes_to)
        ornt_trans = nio.ornt_transform(ornt_fr, ornt_to)
        if (ornt_fr == ornt_to).all():
            log.print("Image is already rotated to", axcodes_to,verbose=verbose)
            if inplace:
                return self
            return self.copy() # type: ignore
        arr = nio.apply_orientation(arr, ornt_trans)
        aff_trans = nio.inv_ornt_aff(ornt_trans, arr.shape)
        new_aff = np.matmul(aff, aff_trans)
        ### Reset origin ###
        flip = ornt_trans[:, 1]
        change = ((-flip) + 1) / 2  # 1 if flip else 0
        change = tuple(a * (s-1) for a, s in zip(change, self.shape))
        new_aff[:3, 3] = nib.affines.apply_affine(aff,change) # type: ignore
        ######
        #if self.header is not None:
        #    self.header.set_sform(new_aff, code=1)
        new_img = arr, new_aff,self.header
        log.print("Image reoriented from", nio.ornt2axcodes(ornt_fr), "to", axcodes_to,verbose=verbose)
    else:
        return self if not inplace else self.copy()
    if inplace:
        self.nii = new_img
        return self

    return self.copy(new_img) # type: ignore

reorient_

reorient_(axcodes_to: AX_CODES | None = ('P', 'I', 'R'), verbose: logging = False) -> Self

In-place variant of reorient.

Source code in TPTBox/core/nii_wrapper.py
def reorient_(self: Self, axcodes_to: AX_CODES | None = ("P", "I", "R"), verbose: logging = False) -> Self:
    """In-place variant of `reorient`."""
    if axcodes_to is None:
        return self
    return self.reorient(axcodes_to=axcodes_to, verbose=verbose,inplace=True)

compute_crop

compute_crop(minimum: float = 0, dist: float = 0, use_mm=False, other_crop: tuple[slice, ...] | None = None, maximum_size: tuple[slice, ...] | int | tuple[int, ...] | None = None, raise_error=True) -> tuple[slice, slice, slice]

Computes the minimum slice that removes unused space from the image and returns the corresponding slice tuple along with the origin shift required for centroids.

Parameters:

Name Type Description Default
minimum int

The minimum value of the array (0 for MRI, -1024 for CT). Default value is 0.

0
dist int

The amount of padding to be added to the cropped image. Default value is 0.

0
use_mm

dist will be mm instead of number of voxels

False
other_crop tuple[slice, ...]

A tuple of slice objects representing the slice of an other image to be combined with the current slice. Default value is None.

None
raise_error

if crop is empty a "ValueError: bbox_nd: img is empty, cannot calculate a bbox" is produced. When False return None instead.

True

Returns:

Name Type Description
ex_slice slice

A tuple of slice objects that need to be applied to crop the image.

origin_shift slice

A tuple of integers representing the shift required to obtain the centroids of the cropped image.

Note
  • The computed slice removes the unused space from the image based on the minimum value.
  • The padding is added to the computed slice.
  • If the computed slice reduces the array size to zero, a ValueError is raised.
  • If other_crop is not None, the computed slice is combined with the slice of another image to obtain a common region of interest.
  • Only None slice is supported for combining slices.
Source code in TPTBox/core/nii_wrapper.py
def compute_crop(self,minimum: float=0, dist: float = 0, use_mm=False, other_crop:tuple[slice,...]|None=None, maximum_size:tuple[slice,...]|int|tuple[int,...]|None=None, raise_error=True)->tuple[slice,slice,slice]:
    """Computes the minimum slice that removes unused space from the image and returns the corresponding slice tuple along with the origin shift required for centroids.

    Args:
        minimum (int): The minimum value of the array (0 for MRI, -1024 for CT). Default value is 0.
        dist (int): The amount of padding to be added to the cropped image. Default value is 0.
        use_mm: dist will be mm instead of number of voxels
        other_crop (tuple[slice,...], optional): A tuple of slice objects representing the slice of an other image to be combined with the current slice. Default value is None.
        raise_error: if crop is empty a "ValueError: bbox_nd: img is empty, cannot calculate a bbox" is produced. When False return None instead.

    Returns:
        ex_slice: A tuple of slice objects that need to be applied to crop the image.
        origin_shift: A tuple of integers representing the shift required to obtain the centroids of the cropped image.

    Note:
        - The computed slice removes the unused space from the image based on the minimum value.
        - The padding is added to the computed slice.
        - If the computed slice reduces the array size to zero, a ValueError is raised.
        - If other_crop is not None, the computed slice is combined with the slice of another image to obtain a common region of interest.
        - Only None slice is supported for combining slices.
    """
    d = np.around(dist / np.asarray(self.zoom)).astype(int) if use_mm else (int(dist),int(dist),int(dist))
    array = self.get_array() #+ minimum

    ex_slice = list(np_bbox_binary(array > minimum, px_dist=d,raise_error=raise_error))

    if other_crop is not None:
        assert all((a.step is None) for a in other_crop), 'Only None slice is supported for combining x'
        ex_slice = [slice(max(a.start, b.start), min(a.stop, b.stop)) for a, b in zip(ex_slice, other_crop)]

    if maximum_size is not None:
        if isinstance(maximum_size,int):
            maximum_size = (maximum_size,maximum_size,maximum_size)
        for i, min_w in enumerate(maximum_size):
            if isinstance(min_w,slice):
                min_w = min_w.stop - min_w.start  # noqa: PLW2901
            curr_w =  ex_slice[i].stop - ex_slice[i].start
            dif = min_w - curr_w
            if min_w > 0 and dif > 0:
                new_start = ex_slice[i].start - floor(dif/2)
                new_goal = ex_slice[i].stop + ceil(dif/2)
                if new_goal > self.shape[i]:
                    new_start -= new_goal - self.shape[i]
                    new_goal = self.shape[i]
                if new_start < 0:
                    new_goal -= new_start
                    new_start = 0
                ex_slice[i] = slice(new_start,new_goal)


    #origin_shift = tuple([int(ex_slice[i].start) for i in range(len(ex_slice))])
    return tuple(ex_slice)# type: ignore

apply_center_crop

apply_center_crop(center_shape: tuple[int, int, int], inplace=False, verbose: bool = False) -> Self

Crops (and pads if necessary) the image to the given shape, centred on the image.

Parameters:

Name Type Description Default
center_shape tuple[int, int, int]

Desired output shape (x, y, z). Axes smaller than the current image are cropped; axes larger are zero-padded first.

required
inplace

If True, modifies this NII in place. Defaults to False.

False
verbose bool

If True, prints the crop/pad operations. Defaults to False.

False

Returns:

Type Description
Self

The NII cropped/padded to center_shape.

Source code in TPTBox/core/nii_wrapper.py
def apply_center_crop(self, center_shape: tuple[int, int, int], inplace=False, verbose: bool = False) -> Self:
    """Crops (and pads if necessary) the image to the given shape, centred on the image.

    Args:
        center_shape: Desired output shape ``(x, y, z)``. Axes smaller than the
            current image are cropped; axes larger are zero-padded first.
        inplace: If True, modifies this NII in place. Defaults to False.
        verbose: If True, prints the crop/pad operations. Defaults to False.

    Returns:
        The NII cropped/padded to ``center_shape``.
    """
    shp_x, shp_y, shp_z = self.shape
    crop_x, crop_y, crop_z = center_shape
    arr = self.get_array()

    if crop_x > shp_x or crop_y > shp_y or crop_z > shp_z:
        padding_ltrb = [
            ((crop_x - shp_x +1) // 2 if crop_x > shp_x else 0,(crop_x - shp_x) // 2 if crop_x > shp_x else 0),
            ((crop_y - shp_y +1) // 2 if crop_y > shp_y else 0,(crop_y - shp_y) // 2 if crop_y > shp_y else 0),
            ((crop_z - shp_z +1) // 2 if crop_z > shp_z else 0,(crop_z - shp_z) // 2 if crop_z > shp_z else 0),
        ]
        arr_padded = np.pad(arr, padding_ltrb, "constant", constant_values=0)  # PIL uses fill value 0
        log.print(f"Pad from {self.shape} to {arr_padded.shape}", verbose=verbose)
        shp_x, shp_y, shp_z = arr_padded.shape
        if crop_x == shp_x and crop_y == shp_y and crop_z == shp_z:
            return self.set_array(arr_padded)
    else:
        arr_padded = arr

    crop_rel_x = round((shp_x - crop_x) / 2.0)
    crop_rel_y = round((shp_y - crop_y) / 2.0)
    crop_rel_z = round((shp_z - crop_z) / 2.0)

    crop_slices = (slice(crop_rel_x, crop_rel_x + crop_x),slice(crop_rel_y, crop_rel_y + crop_y),slice(crop_rel_z, crop_rel_z + crop_z))
    arr_cropped = arr_padded[crop_slices]
    log.print(f"Center cropped from {arr_padded.shape} to {arr_cropped.shape}", verbose=verbose)
    shp_x, shp_y, shp_z = arr_cropped.shape
    assert crop_x == shp_x and crop_y == shp_y and crop_z == shp_z
    return self.set_array(arr_cropped, inplace=inplace)

apply_crop_slice

apply_crop_slice(*args, **qargs) -> Self

Deprecated alias for apply_crop.

Source code in TPTBox/core/nii_wrapper.py
def apply_crop_slice(self, *args, **qargs) -> Self:
    """Deprecated alias for `apply_crop`."""
    import warnings
    warnings.warn("apply_crop_slice id deprecated use apply_crop instead",stacklevel=5) #TODO remove in version 1.0
    return self.apply_crop(*args,**qargs)

apply_crop_slice_

apply_crop_slice_(*args, **qargs) -> Self

Deprecated alias for apply_crop_.

Source code in TPTBox/core/nii_wrapper.py
def apply_crop_slice_(self, *args, **qargs) -> Self:
    """Deprecated alias for `apply_crop_`."""
    import warnings
    warnings.warn("apply_crop_slice_ id deprecated use apply_crop_ instead",stacklevel=5) #TODO remove in version 1.0
    return self.apply_crop_(*args,**qargs)

apply_crop

apply_crop(ex_slice: tuple[slice, slice, slice] | Sequence[slice] | None, inplace=False) -> Self

The apply_crop_slice function applies a given slice to reduce the Nifti image volume. If a list of slices is provided, it computes the minimum volume of all slices and applies it.

Parameters:

Name Type Description Default
ex_slice tuple[slice, slice, slice] | list[tuple[slice, slice, slice]]

A tuple or a list of tuples, where each tuple represents a slice for each axis (x, y, z).

required
inplace bool

If True, it applies the slice to the original image and returns it. If False, it returns a new NII object with the sliced image.

False

Returns:

Name Type Description
NII Self

A new NII object containing the sliced image if inplace=False. Otherwise, it returns the original NII object after applying the slice.

Source code in TPTBox/core/nii_wrapper.py
def apply_crop(self,ex_slice:tuple[slice,slice,slice]|Sequence[slice]|None , inplace=False) -> Self:
    """The apply_crop_slice function applies a given slice to reduce the Nifti image volume. If a list of slices is provided, it computes the minimum volume of all slices and applies it.

    Args:
        ex_slice (tuple[slice,slice,slice] | list[tuple[slice,slice,slice]]): A tuple or a list of tuples, where each tuple represents a slice for each axis (x, y, z).
        inplace (bool, optional): If True, it applies the slice to the original image and returns it. If False, it returns a new NII object with the sliced image.

    Returns:
        NII: A new NII object containing the sliced image if inplace=False. Otherwise, it returns the original NII object after applying the slice.
    """
    nii = self.nii.slicer[tuple(ex_slice)] if ex_slice is not None else self.nii_abstract
    if inplace:
        self.nii = nii
        return self
    x= self.copy(nii)
    return x

apply_crop_

apply_crop_(ex_slice: tuple[slice, slice, slice] | Sequence[slice]) -> Self

In-place variant of apply_crop.

Source code in TPTBox/core/nii_wrapper.py
def apply_crop_(self, ex_slice: tuple[slice, slice, slice] | Sequence[slice]) -> Self:
    """In-place variant of `apply_crop`."""
    return self.apply_crop(ex_slice=ex_slice,inplace=True)

pad_to

pad_to(target_shape: list[int] | tuple[int, int, int] | Self, mode: MODES = 'constant', crop=False, inplace=False) -> Self

Pads (and optionally crops) the image to match a target shape.

Parameters:

Name Type Description Default
target_shape list[int] | tuple[int, int, int] | Self

Desired output shape (x, y, z) or another NII whose shape is used as the target.

required
mode MODES

Padding mode ("constant", "nearest", "reflect", or "wrap"). Defaults to "constant".

'constant'
crop

If True and the image is larger than target_shape along any axis, that axis is cropped first. Defaults to False.

False
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

The NII padded (and optionally cropped) to target_shape.

Source code in TPTBox/core/nii_wrapper.py
def pad_to(self, target_shape: list[int] | tuple[int, int, int] | Self, mode: MODES = "constant", crop=False, inplace=False) -> Self:
    """Pads (and optionally crops) the image to match a target shape.

    Args:
        target_shape: Desired output shape ``(x, y, z)`` or another NII whose
            shape is used as the target.
        mode: Padding mode (``"constant"``, ``"nearest"``, ``"reflect"``,
            or ``"wrap"``). Defaults to ``"constant"``.
        crop: If True and the image is larger than ``target_shape`` along any
            axis, that axis is cropped first. Defaults to False.
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        The NII padded (and optionally cropped) to ``target_shape``.
    """
    if isinstance(target_shape, NII):
        target_shape = target_shape.shape
    padding, crop, requires_crop = _pad_to_parameters(self.shape, target_shape)
    s = self
    if crop and requires_crop:
        s = s.apply_crop(tuple(crop),inplace=inplace)
    return s.apply_pad(padding,inplace=inplace,mode=mode)

apply_pad

apply_pad(padd: Sequence[tuple[int | None, int | None]] | int | None, mode: MODES = 'constant', inplace=False, verbose: logging = True) -> Self

Pads the image with explicit per-axis (before, after) amounts.

The affine is updated so that the world-space origin is preserved (i.e. the new voxel (0, 0, 0) corresponds to the same world coordinate as before).

Parameters:

Name Type Description Default
padd Sequence[tuple[int | None, int | None]] | int | None

A sequence of (before, after) integer tuples, one per spatial dimension. None as the before value means no padding on that side. Pass None for the whole argument to skip padding entirely.

required
mode MODES

Padding mode forwarded to numpy.pad. Defaults to "constant". In "constant" mode the fill value is self.get_c_val().

'constant'
inplace

If True, modifies this NII in place. Defaults to False.

False
verbose logging

If True, logs the padding parameters. Defaults to True.

True

Returns:

Type Description
Self

The padded NII.

Source code in TPTBox/core/nii_wrapper.py
def apply_pad(self, padd: Sequence[tuple[int | None, int | None]] | int | None, mode: MODES = "constant", inplace=False, verbose: logging = True,) -> Self:
    """Pads the image with explicit per-axis ``(before, after)`` amounts.

    The affine is updated so that the world-space origin is preserved (i.e. the
    new voxel (0, 0, 0) corresponds to the same world coordinate as before).

    Args:
        padd: A sequence of ``(before, after)`` integer tuples, one per spatial
            dimension. ``None`` as the ``before`` value means no padding on that
            side. Pass ``None`` for the whole argument to skip padding entirely.
        mode: Padding mode forwarded to ``numpy.pad``. Defaults to ``"constant"``.
            In ``"constant"`` mode the fill value is ``self.get_c_val()``.
        inplace: If True, modifies this NII in place. Defaults to False.
        verbose: If True, logs the padding parameters. Defaults to True.

    Returns:
        The padded NII.
    """
    #TODO add other modes
    #TODO add testcases and options for modes
    if padd is None:
        return self if inplace else self.copy()

    if isinstance(padd, (int, float)):
        padd = int(padd)
        padd = ((padd, padd),) * self.dims

    assert len(padd) == self.dims

    # Replace None with 0
    padd = tuple((b or 0, a or 0) for b, a in padd)

    # Extend for non-spatial dims
    padd = padd + ((0, 0),) * (len(self.shape) - len(padd))

    # Build affine transform
    transform = np.eye(self.dims + 1, dtype=float)
    for i, (before, _) in enumerate(padd[:self.dims]):
        transform[i, -1] = -before

    affine = self.affine @ transform

    arr = self.get_array()

    # ---- 1. CROPPING (negative padding) ----
    slices = []

    for i, (before, after) in enumerate(padd[:self.dims]):
        start = max(0, -before)
        end = arr.shape[i] - max(0, -after)
        slices.append(slice(start, end))

    # keep non-spatial dims unchanged
    slices += [slice(None)] * (arr.ndim - self.dims)

    arr = arr[tuple(slices)]

    # ---- 2. PADDING (positive only) ----
    padd_positive = tuple(
        (max(0, b), max(0, a)) for b, a in padd
    )

    args = {}
    if mode == "constant":
        args["constant_values"] = self.get_c_val()

    if mode == "nearest":
        mode = "edge"

    log.print(f"Padd {padd}; {mode=}, {args}", verbose=verbose)

    arr = np.pad(arr, padd_positive, mode=mode, **args)

    nii = (arr, affine, self.header)

    if inplace:
        self.nii = nii
        return self

    return self.copy(nii)

rescale_and_reorient

rescale_and_reorient(axcodes_to=None, voxel_spacing=(-1, -1, -1), verbose: logging = True, inplace=False, c_val: float | None = None, mode: MODES = 'nearest') -> Self

Reorients and then rescales the image in a single step.

Parameters:

Name Type Description Default
axcodes_to

Target orientation axis codes, e.g. ("P", "I", "R"). If None, keeps the current orientation. Defaults to None.

None
voxel_spacing

Target voxel spacing in mm. -1 keeps the current spacing for that axis. Defaults to (-1, -1, -1).

(-1, -1, -1)
verbose logging

Verbosity flag. Defaults to True.

True
inplace

If True, modifies this NII in place. Defaults to False.

False
c_val float | None

Background fill value for resampling. Defaults to None.

None
mode MODES

Interpolation / boundary mode. Defaults to "nearest".

'nearest'

Returns:

Type Description
Self

The reoriented and rescaled NII.

Source code in TPTBox/core/nii_wrapper.py
def rescale_and_reorient(self, axcodes_to=None, voxel_spacing=(-1, -1, -1), verbose: logging = True, inplace=False, c_val: float | None = None, mode: MODES = 'nearest') -> Self:
    """Reorients and then rescales the image in a single step.

    Args:
        axcodes_to: Target orientation axis codes, e.g. ``("P", "I", "R")``.
            If None, keeps the current orientation. Defaults to None.
        voxel_spacing: Target voxel spacing in mm. ``-1`` keeps the current spacing
            for that axis. Defaults to ``(-1, -1, -1)``.
        verbose: Verbosity flag. Defaults to True.
        inplace: If True, modifies this NII in place. Defaults to False.
        c_val: Background fill value for resampling. Defaults to None.
        mode: Interpolation / boundary mode. Defaults to ``"nearest"``.

    Returns:
        The reoriented and rescaled NII.
    """
    ## Resample and rotate and Save Tempfiles
    if axcodes_to is None:
        curr = self
        ornt_img = self.orientation
        axcodes_to = nio.ornt2axcodes(ornt_img)
    else:
        curr = self.reorient(axcodes_to=axcodes_to, verbose=verbose, inplace=inplace)
    return curr.rescale(voxel_spacing=voxel_spacing, verbose=verbose, inplace=inplace,c_val=c_val,mode=mode)

rescale_and_reorient_

rescale_and_reorient_(axcodes_to=None, voxel_spacing=(-1, -1, -1), c_val: float | None = None, mode: MODES = 'nearest', verbose: logging = True) -> Self

In-place variant of rescale_and_reorient.

Source code in TPTBox/core/nii_wrapper.py
def rescale_and_reorient_(self, axcodes_to=None, voxel_spacing=(-1, -1, -1), c_val: float | None = None, mode: MODES = 'nearest', verbose: logging = True) -> Self:
    """In-place variant of `rescale_and_reorient`."""
    return self.rescale_and_reorient(axcodes_to=axcodes_to,voxel_spacing=voxel_spacing,c_val=c_val,mode=mode,verbose=verbose,inplace=True)

reorient_same_as

reorient_same_as(img_as: Nifti1Image | Self, verbose: logging = False, inplace=False) -> Self

Reorients this image to match the orientation of another image.

Parameters:

Name Type Description Default
img_as Nifti1Image | Self

Reference image whose orientation is used as the target.

required
verbose logging

If True, logs the orientation change. Defaults to False.

False
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

The reoriented NII.

Source code in TPTBox/core/nii_wrapper.py
def reorient_same_as(self, img_as: Nifti1Image | Self, verbose: logging = False, inplace=False) -> Self:
    """Reorients this image to match the orientation of another image.

    Args:
        img_as: Reference image whose orientation is used as the target.
        verbose: If True, logs the orientation change. Defaults to False.
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        The reoriented NII.
    """
    axcodes_to: AX_CODES = nio.ornt2axcodes(nio.io_orientation(img_as.affine)) # type: ignore
    return self.reorient(axcodes_to=axcodes_to, verbose=verbose, inplace=inplace)

reorient_same_as_

reorient_same_as_(img_as: Nifti1Image | Self, verbose: logging = False) -> Self

In-place variant of reorient_same_as.

Source code in TPTBox/core/nii_wrapper.py
def reorient_same_as_(self, img_as: Nifti1Image | Self, verbose: logging = False) -> Self:
    """In-place variant of `reorient_same_as`."""
    return self.reorient_same_as(img_as=img_as,verbose=verbose,inplace=True)

rescale

rescale(voxel_spacing: float | tuple[float, ...] = (1, 1, 1), c_val: float | None = None, verbose: logging = False, inplace=False, mode: MODES = 'nearest', order: int | None = None, align_corners: bool = False, atol=0.001) -> Self

Rescales the NIfTI image to a new voxel spacing.

Parameters:

Name Type Description Default
voxel_spacing tuple[float, float, float] | float

The desired voxel spacing in millimeters (x, y, z). -1 is keep the voxel spacing. Defaults to (1, 1, 1).

(1, 1, 1)
c_val float | None

The padding value. Defaults to None, meaning that the padding value will be inferred from the image data.

None
verbose bool

Whether to print a message indicating that the image has been resampled. Defaults to False.

False
inplace bool

Whether to modify the current object or return a new one. Defaults to False.

False
mode str

One of the supported modes by scipy.ndimage.interpolation (e.g., "constant", "nearest", "reflect", "wrap"). See the documentation for more details. Defaults to "constant".

'nearest'
align_corners bool | default

If True or not set and seg==True. Aline corners for scaling. This prevents segmentation mask to shift in a direction.

False
atol

absolute tolerance for skipping if already close in voxel_spacing

0.001

Returns: NII: A new NII object with the resampled image data.

Source code in TPTBox/core/nii_wrapper.py
def rescale(self, voxel_spacing:float|tuple[float,...]=(1, 1, 1), c_val:float|None=None, verbose:logging=False, inplace=False,mode:MODES='nearest',order: int |None = None,align_corners:bool=False,atol=0.001) -> Self:
    """Rescales the NIfTI image to a new voxel spacing.

    Args:
        voxel_spacing (tuple[float, float, float] | float): The desired voxel spacing in millimeters (x, y, z). -1 is keep the voxel spacing.
            Defaults to (1, 1, 1).
        c_val (float | None, optional): The padding value. Defaults to None, meaning that the padding value will be
            inferred from the image data.
        verbose (bool, optional): Whether to print a message indicating that the image has been resampled. Defaults to
            False.
        inplace (bool, optional): Whether to modify the current object or return a new one. Defaults to False.
        mode (str, optional): One of the supported modes by scipy.ndimage.interpolation (e.g., "constant", "nearest",
            "reflect", "wrap"). See the documentation for more details. Defaults to "constant".
        align_corners (bool|default): If True or not set and seg==True. Aline corners for scaling. This prevents segmentation mask to shift in a direction.
        atol: absolute tolerance for skipping if already close in voxel_spacing
    Returns:
        NII: A new NII object with the resampled image data.
    """
    if isinstance(voxel_spacing, (int,float)):
        voxel_spacing =(voxel_spacing for _ in range(min(3,self.affine.shape[0]-1)))
    n = self.dims
    while  n> len(voxel_spacing):
        voxel_spacing = (*voxel_spacing, -1)
    if all(a in (-1, b) for a,b in zip(voxel_spacing, self.zoom)):
        log.print(f"Image already resampled to voxel size {self.zoom}",verbose=verbose)
        return self.copy() if inplace else self

    c_val = self.get_c_val(c_val)
    # resample to new voxel spacing based on the current x-y-z-orientation
    aff = self.affine
    shp = self.shape
    zms = self.zoom
    if order is None:
        order = 0 if self.seg else 3
    #print(aff.shape,shp,zms,voxel_spacing)
    voxel_spacing = tuple([v if v != -1 else z for v,z in zip_strict(voxel_spacing,zms)])
    if np.isclose(voxel_spacing, self.zoom,atol=atol).all():
        log.print(f"Image already resampled to voxel size {self.zoom}",verbose=verbose)
        return self.copy() if inplace else self

    # Calculate new shape
    new_shp = tuple(np.rint([shp[i] * zms[i] / voxel_spacing[i] for i in range(len(voxel_spacing))]).astype(int))
    if len(new_shp) < len(shp):
        new_shp = new_shp + shp[len(new_shp):]
    new_aff = _rescale_affine(aff, shp, voxel_spacing, new_shp)  # type: ignore
    new_aff[:n, n] = nib.affines.apply_affine(aff, [0 for _ in range(n)])# type: ignore
    new_img = _resample_from_to(self, (new_shp, new_aff,voxel_spacing), order=order, mode=mode,align_corners=align_corners)
    log.print(f"Image resampled from {zms} to voxel size {voxel_spacing}",verbose=verbose)
    if inplace:
        self.nii = new_img
        return self
    return self.copy(new_img)

rescale_

rescale_(voxel_spacing=(1, 1, 1), c_val: float | None = None, verbose: logging = False, mode: MODES = 'nearest') -> Self

In-place variant of rescale.

Source code in TPTBox/core/nii_wrapper.py
def rescale_(self, voxel_spacing=(1, 1, 1), c_val: float | None = None, verbose: logging = False, mode: MODES = 'nearest') -> Self:
    """In-place variant of `rescale`."""
    return self.rescale( voxel_spacing=voxel_spacing, c_val=c_val, verbose=verbose,mode=mode, inplace=True)

resample_from_to

resample_from_to(to_vox_map: Image_Reference | Has_Grid | tuple[SHAPE, AFFINE, ZOOMS], mode: MODES = 'nearest', order: int | None = None, c_val=None, inplace=False, verbose: logging = True, align_corners: bool = False) -> Self

Self will be resampled in coordinate of given other image. Adheres to global space not to local pixel space.

Parameters:

Name Type Description Default
to_vox_map Image_Reference | Proxy

If object, has attributes shape giving input voxel shape, and affine giving mapping of input voxels to output space. If length 2 sequence, elements are (shape, affine) with same meaning as above. The affine is a (4, 4) array-like.\n

required
mode str

Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap').Defaults to 'constant'.\n

'nearest'
cval float

Value used for points outside the boundaries of the input if mode='nearest'. Defaults to 0.0.\n

required
aline_corners bool | default

If True or not set and seg==True. Aline corners for scaling. This prevents segmentation mask to shift in a direction.

required
inplace bool

Defaults to False.

False

Returns:

Name Type Description
NII Self
Source code in TPTBox/core/nii_wrapper.py
def resample_from_to(self, to_vox_map:Image_Reference|Has_Grid|tuple[SHAPE,AFFINE,ZOOMS], mode:MODES='nearest', order: int |None=None, c_val=None, inplace = False,verbose:logging=True,align_corners:bool=False) -> Self:
    r"""Self will be resampled in coordinate of given other image. Adheres to global space not to local pixel space.

    Args:
        to_vox_map (Image_Reference|Proxy): If object, has attributes shape giving input voxel shape, and affine giving mapping of input voxels to output space. If length 2 sequence, elements are (shape, affine) with same meaning as above. The affine is a (4, 4) array-like.\n
        mode (str, optional): Points outside the boundaries of the input are filled according to the given mode ('constant', 'nearest', 'reflect' or 'wrap').Defaults to 'constant'.\n
        cval (float, optional): Value used for points outside the boundaries of the input if mode='nearest'. Defaults to 0.0.\n
        aline_corners (bool|default): If True or not set and seg==True. Aline corners for scaling. This prevents segmentation mask to shift in a direction.
        inplace (bool, optional): Defaults to False.

    Returns:
        NII:
    """        ''''''
    if to_vox_map is None:
        return self if inplace else self.copy()
    c_val = self.get_c_val(c_val)
    if isinstance(to_vox_map,Has_Grid):
        mapping = to_vox_map.to_gird()
    else:
        mapping = to_vox_map if isinstance(to_vox_map, tuple) else to_nii_optional(to_vox_map, seg=self.seg, default=to_vox_map)
    if isinstance(mapping,Has_Grid):
        if mapping.assert_affine(self,raise_error=False,origin_tolerance=0.000001,error_tolerance=0.000001,shape_tolerance=0):
            log.print(f"resample_from_to skipped; already in space: {self}",verbose=verbose)
            return self if inplace else self.copy()

        m1 = mapping if mapping.orientation == self.orientation else mapping.make_empty_POI().reorient(self.orientation)
        if m1.assert_affine(self,raise_error=False,origin_tolerance=0.00001,error_tolerance=0.00001,shape_tolerance=0):
            log.print(f"resample_from_to only need reorientation; {self.orientation}",verbose=verbose)
            ret = self.reorient(mapping.orientation,inplace=inplace)
            ret.affine = mapping.affine #remove floating point error
            return ret
        if self.orientation == mapping.orientation and np.allclose(self.zoom , mapping.zoom, atol=1e-6):
            shift = (np.array(self.origin) - np.array(m1.origin)) / np.array(m1.zoom)
            if np.allclose(shift, np.round(shift), atol=1e-6):
                s = self.reorient(mapping.orientation,inplace=inplace)  # noqa: PLW0642
                shift = (np.array(self.origin) - np.array(mapping.origin)) / np.array(mapping.zoom)
                shift = np.round(shift).astype(int)
                dst_shape = np.array(mapping.shape)
                src_shape = np.array(s.shape)
                # padding before = how much dst starts before src
                pad_before = shift
                # padding after = remaining dst size after src
                pad_after = dst_shape-shift-src_shape
                pad = tuple((int(b), int(a)) for b, a in zip(pad_before, pad_after))
                ret = s.apply_pad(pad, mode=mode,inplace=inplace,verbose=verbose)

                valid = ret.assert_affine(mapping,raise_error=False,origin_tolerance=0.0001,error_tolerance=0.0001,shape_tolerance=0)
                if valid:
                    log.print(f"resample_from_to only needs padding/cropping {pad}",verbose=verbose)
                    ret.affine = mapping.affine #remove floating point error
                    return ret


    assert mapping is not None
    log.print(f"resample_from_to: {self} to {mapping}",verbose=verbose)
    if order is None:
        order = 0 if self.seg else 3
    nii = _resample_from_to(self, mapping,order=order, mode=mode,align_corners=align_corners)


    if inplace:
        self.nii = nii
        return self
    else:
        return self.copy(nii)

resample_from_to_

resample_from_to_(to_vox_map: Image_Reference | Has_Grid | tuple[SHAPE, AFFINE, ZOOMS], mode: MODES = 'nearest', c_val: float | None = None, verbose: logging = True, aline_corners=False) -> Self

In-place variant of resample_from_to.

Source code in TPTBox/core/nii_wrapper.py
def resample_from_to_(self, to_vox_map: Image_Reference | Has_Grid | tuple[SHAPE, AFFINE, ZOOMS], mode: MODES = 'nearest', c_val: float | None = None, verbose: logging = True, aline_corners=False) -> Self:
    """In-place variant of `resample_from_to`."""
    return self.resample_from_to(to_vox_map,mode=mode,c_val=c_val,inplace=True,verbose=verbose,align_corners=aline_corners)

n4_bias_field_correction

n4_bias_field_correction(threshold=60, mask=None, shrink_factor=4, convergence=None, spline_param=200, verbose=False, weight_mask=None, crop=False, inplace=False) -> Self

Runs a n4 bias field correction over the nifty.

Parameters:

Name Type Description Default
threshold int

If != 0, will mask the input based on the threshold. Defaults to 60.

60
mask _type_

If threshold==0, this can be set to input a individual mask. If none, lets the algorithm automatically determine the mask. Defaults to None.

None
shrink_factor int

description. Defaults to 4.

4
convergence dict

description. Defaults to {"iters": [50, 50, 50, 50], "tol": 1e-07}.

None
spline_param int

description. Defaults to 200.

200
verbose bool

description. Defaults to False.

False
weight_mask _type_

description. Defaults to None.

None
crop bool

description. Defaults to False.

False
inplace bool

description. Defaults to False.

False

Returns:

Name Type Description
NII Self

The NII with bias field corrected image

Source code in TPTBox/core/nii_wrapper.py
def n4_bias_field_correction(
    self,
    threshold = 60,
    mask=None, # type: ignore
    shrink_factor=4,
    convergence=None,
    spline_param=200,
    verbose=False,
    weight_mask=None,
    crop=False,
    inplace=False
) -> Self:
    """Runs a n4 bias field correction over the nifty.

    Args:
        threshold (int, optional): If != 0, will mask the input based on the threshold. Defaults to 60.
        mask (_type_, optional): If threshold==0, this can be set to input a individual mask. If none, lets the algorithm automatically determine the mask. Defaults to None.
        shrink_factor (int, optional): _description_. Defaults to 4.
        convergence (dict, optional): _description_. Defaults to {"iters": [50, 50, 50, 50], "tol": 1e-07}.
        spline_param (int, optional): _description_. Defaults to 200.
        verbose (bool, optional): _description_. Defaults to False.
        weight_mask (_type_, optional): _description_. Defaults to None.
        crop (bool, optional): _description_. Defaults to False.
        inplace (bool, optional): _description_. Defaults to False.

    Returns:
        NII: The NII with bias field corrected image
    """
    if convergence is None:
        convergence = {"iters": [50, 50, 50, 50], "tol": 1e-07}
    assert self.seg is False, "n4 bias field correction on a segmentation does not make any sense"
    # install antspyx not ants!
    import ants
    try:
        import ants.ops.bias_correction as bc  # install antspyx not ants!
    except ModuleNotFoundError:
        import ants.utils.bias_correction as bc  # install antspyx not ants!
    from ants.utils.convert_nibabel import from_nibabel
    from scipy.ndimage import binary_dilation, generate_binary_structure
    dtype = self.dtype
    input_ants:ants.ANTsImage = from_nibabel(nib.nifti1.Nifti1Image(self.get_array(),self.affine))
    if threshold != 0:
        mask_arr = self.get_array()
        mask_arr[mask_arr < threshold] = 0
        mask_arr[mask_arr != 0] = 1
        mask_arr = mask_arr.astype(np.uint8)
        struct = generate_binary_structure(3, 3)
        mask_arr = binary_dilation(mask_arr.copy(), structure=struct, iterations=3)
        mask_arr = mask_arr.astype(np.uint8)
        mask:ants.ANTsImage = from_nibabel(nib.nifti1.Nifti1Image(mask_arr,self.affine))#self.set_array(mask,verbose=False).nii
        mask = mask.set_spacing(input_ants.spacing) # type: ignore
    out = bc.n4_bias_field_correction(
        input_ants,
        mask=mask,
        shrink_factor=shrink_factor,
        convergence=convergence,
        spline_param=spline_param,
        verbose=verbose,
        weight_mask=weight_mask,

    )


    out_nib:Nifti1Image = out.to_nibabel()
    if crop:
        # Crop to regions that had a normalization applied. Removes a lot of dead space
        dif = NII((input_ants - out).to_nibabel())
        dif_arr = dif.get_array()
        dif_arr[dif_arr != 0] = 1
        dif.set_array_(dif_arr,verbose=verbose)
        ex_slice = dif.compute_crop()
        out_nib:Nifti1Image = out_nib.slicer[ex_slice]

    if inplace:
        self.nii = out_nib
        self.set_dtype_(dtype)
        return self
    return self.copy(out_nib).set_dtype_(dtype)

n4_bias_field_correction_

n4_bias_field_correction_(threshold=60, mask=None, shrink_factor=4, convergence=None, spline_param=200, verbose=False, weight_mask=None, crop=False) -> Self

In-place variant of n4_bias_field_correction.

Source code in TPTBox/core/nii_wrapper.py
def n4_bias_field_correction_(self, threshold=60, mask=None, shrink_factor=4, convergence=None, spline_param=200, verbose=False, weight_mask=None, crop=False) -> Self:
    """In-place variant of `n4_bias_field_correction`."""
    if convergence is None:
        convergence = {"iters": [50, 50, 50, 50], "tol": 1e-07}
    return self.n4_bias_field_correction(mask=mask,shrink_factor=shrink_factor,convergence=convergence,spline_param=spline_param,verbose=verbose,weight_mask=weight_mask,crop=crop,inplace=True,threshold = threshold)

normalize_to_range_

normalize_to_range_(min_value: int = 0, max_value: int = 1500, verbose: logging = True) -> None

In-place normalization that clips and scales intensity values to [min_value, max_value].

Parameters:

Name Type Description Default
min_value int

Desired minimum output value. Defaults to 0.

0
max_value int

Desired maximum output value. Defaults to 1500.

1500
verbose logging

If True, logs the before/after intensity range. Defaults to True.

True

Raises:

Type Description
AssertionError

If this NII is a segmentation (seg=True).

Source code in TPTBox/core/nii_wrapper.py
def normalize_to_range_(self, min_value: int = 0, max_value: int = 1500, verbose: logging = True) -> None:
    """In-place normalization that clips and scales intensity values to ``[min_value, max_value]``.

    Args:
        min_value: Desired minimum output value. Defaults to 0.
        max_value: Desired maximum output value. Defaults to 1500.
        verbose: If True, logs the before/after intensity range. Defaults to True.

    Raises:
        AssertionError: If this NII is a segmentation (``seg=True``).
    """
    assert not self.seg
    mi, ma = self.min(), self.max()
    self += -mi + min_value  # min = 0
    self_dtype = self.dtype
    max_value2 = self.max() # this is a new value if min got shifted
    if max_value2 > max_value:
        self *= max_value / max_value2
        self.set_dtype_(self_dtype)
    log.print(f"Shifted from range {mi, ma} to range {self.min(), self.max()}", verbose=verbose)

get_histogram

get_histogram(bins=256, hrange=None, density=False, c_val: float | None = None) -> tuple[np.ndarray, np.ndarray]

Returns the histogram of the image array.

Parameters:

Name Type Description Default
bins int

Number of bins for the histogram. Defaults to 256.

256
range tuple

Range of values to consider for the histogram. Defaults to None.

required
density bool

If True, the result is the probability density function at the bin, normalized such that the integral over the range is 1. Defaults to False.

False
c_val float | None

The value below which all values are set to c_val. Defaults to None.

None

Returns:

Name Type Description
tuple tuple[ndarray, ndarray]

A tuple containing the histogram values and the bin edges.

Source code in TPTBox/core/nii_wrapper.py
def get_histogram(self, bins=256, hrange=None, density=False, c_val:float|None=None) -> tuple[np.ndarray, np.ndarray]:
    """Returns the histogram of the image array.

    Args:
        bins (int, optional): Number of bins for the histogram. Defaults to 256.
        range (tuple, optional): Range of values to consider for the histogram. Defaults to None.
        density (bool, optional): If True, the result is the probability density function at the bin, normalized such that the integral over the range is 1. Defaults to False.
        c_val (float|None, optional): The value below which all values are set to c_val. Defaults to None.

    Returns:
        tuple: A tuple containing the histogram values and the bin edges.
    """
    arr = self.get_array()
    if c_val is not None:
        arr[arr <= c_val] = c_val
    return np.histogram(arr, bins=bins, range=hrange, density=density)

match_histograms

match_histograms(reference: Image_Reference, c_val: float = 0, inplace=False) -> Self

Adjusts the intensity histogram of this image to match a reference image.

Parameters:

Name Type Description Default
reference Image_Reference

Reference image whose histogram is used as the target.

required
c_val float

Background value; voxels at or below this threshold are clamped to c_val after matching. Defaults to 0.

0
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

The histogram-matched NII.

Raises:

Type Description
AssertionError

If either image has seg=True.

ValueError

If c_val <= -999 (CT-range backgrounds are not supported).

Source code in TPTBox/core/nii_wrapper.py
def match_histograms(self, reference: Image_Reference, c_val: float = 0, inplace=False) -> Self:
    """Adjusts the intensity histogram of this image to match a reference image.

    Args:
        reference: Reference image whose histogram is used as the target.
        c_val: Background value; voxels at or below this threshold are clamped
            to ``c_val`` after matching. Defaults to 0.
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        The histogram-matched NII.

    Raises:
        AssertionError: If either image has ``seg=True``.
        ValueError: If ``c_val <= -999`` (CT-range backgrounds are not supported).
    """
    assert not self.seg
    ref_nii = to_nii(reference)
    assert ref_nii.seg is False
    assert self.seg is False
    c_val = self.get_c_val(c_val)
    if c_val <= -999:
        raise ValueError('match_histograms only functions on MRI, which have a minimum 0.')

    from skimage.exposure import match_histograms as ski_match_histograms
    img_arr = self.get_array()
    matched = ski_match_histograms(img_arr, ref_nii.get_array())
    matched[matched <= c_val] = c_val
    return self.set_array(matched, inplace=inplace,verbose=False)

match_histograms_

match_histograms_(reference: Image_Reference, c_val: float = 0) -> Self

In-place variant of match_histograms.

Source code in TPTBox/core/nii_wrapper.py
def match_histograms_(self, reference: Image_Reference, c_val: float = 0) -> Self:
    """In-place variant of `match_histograms`."""
    return self.match_histograms(reference,c_val = c_val,inplace=True)

smooth_gaussian

smooth_gaussian(sigma: float | list[float] | tuple[float], truncate: float = 4.0, nth_derivative: int = 0, inplace=False) -> Self

Applies a Gaussian smoothing filter to the image.

Parameters:

Name Type Description Default
sigma float | list[float] | tuple[float]

Standard deviation of the Gaussian kernel. A scalar applies the same sigma to all axes; a sequence sets per-axis values.

required
truncate float

Truncate the filter at this many standard deviations. Defaults to 4.0.

4.0
nth_derivative int

Order of the derivative (0 = smoothing, 1 = gradient, …). Defaults to 0.

0
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

The smoothed NII.

Raises:

Type Description
AssertionError

If seg=True (use smooth_gaussian_labelwise instead).

Source code in TPTBox/core/nii_wrapper.py
def smooth_gaussian(self, sigma: float | list[float] | tuple[float], truncate: float = 4.0, nth_derivative: int = 0, inplace=False) -> Self:
    """Applies a Gaussian smoothing filter to the image.

    Args:
        sigma: Standard deviation of the Gaussian kernel. A scalar applies the
            same sigma to all axes; a sequence sets per-axis values.
        truncate: Truncate the filter at this many standard deviations.
            Defaults to 4.0.
        nth_derivative: Order of the derivative (0 = smoothing, 1 = gradient, …).
            Defaults to 0.
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        The smoothed NII.

    Raises:
        AssertionError: If ``seg=True`` (use ``smooth_gaussian_labelwise`` instead).
    """
    assert self.seg is False, "You really want to smooth a segmentation? If yes, use smooth_gaussian_channelwise() instead"
    from scipy.ndimage import gaussian_filter
    arr = gaussian_filter(self.get_array(), sigma, order=nth_derivative,cval=self.get_c_val(), truncate=truncate)# radius=None, axes=None
    return self.set_array(arr,inplace,verbose=False)

smooth_gaussian_

smooth_gaussian_(sigma: float | list[float] | tuple[float], truncate: float = 4.0, nth_derivative: int = 0) -> Self

In-place variant of smooth_gaussian.

Source code in TPTBox/core/nii_wrapper.py
def smooth_gaussian_(self, sigma: float | list[float] | tuple[float], truncate: float = 4.0, nth_derivative: int = 0) -> Self:
    """In-place variant of `smooth_gaussian`."""
    return self.smooth_gaussian(sigma=sigma,truncate=truncate,nth_derivative=nth_derivative,inplace=True)

smooth_gaussian_labelwise

smooth_gaussian_labelwise(label_to_smooth: list[int] | int, sigma: float = 3.0, radius: int = 6, truncate: int = 4, boundary_mode: str = 'nearest', dilate_prior: int = 0, dilate_connectivity: int = 1, dilate_channelwise: bool = False, smooth_background: bool = True, background_threshold: float | None = None, inplace: bool = False, verbose: logging = False) -> Self

Smoothes the segmentation mask by applying a gaussian filter label-wise and then using argmax to derive the smoothed segmentation labels again.

Parameters:

Name Type Description Default
label_to_smooth list[int] | int

Which labels to smooth in the mask. Every other label will be untouched

required
sigma float

Sigma of the gaussian blur. Defaults to 3.0.

3.0
radius int

Radius of the gaussian blur. Defaults to 6.

6
truncate int

Truncate of the gaussian blur. Defaults to 4.

4
boundary_mode str

Boundary Mode of the gaussian blur. Defaults to "nearest".

'nearest'
dilate_prior int

Dilate this many voxels before starting the gaussian blur algorithm. Defaults to 0.

0
dilate_connectivity int

Connectivity of the dilation process, if applied. Defaults to 3.

1
smooth_background bool

If true, will also smooth the background. If False, the background voxels stay the same and the segmentation cannot add voxels. Defaults to True.

True
inplace bool

If true, will overwrite the input NII instead of making a copy. Defaults to False.

False

Returns:

Name Type Description
NII Self

The smoothed NII object.

Source code in TPTBox/core/nii_wrapper.py
def smooth_gaussian_labelwise(
    self,
    label_to_smooth: list[int] | int,
    sigma: float = 3.0,
    radius: int = 6,
    truncate: int = 4,
    boundary_mode: str = "nearest",
    dilate_prior: int = 0,
    dilate_connectivity: int = 1,
    dilate_channelwise: bool = False,
    smooth_background: bool = True,
    background_threshold: float | None = None,
    inplace: bool = False,
    verbose:logging=False,
) -> Self:
    """Smoothes the segmentation mask by applying a gaussian filter label-wise and then using argmax to derive the smoothed segmentation labels again.

    Args:
        label_to_smooth (list[int] | int): Which labels to smooth in the mask. Every other label will be untouched
        sigma (float, optional): Sigma of the gaussian blur. Defaults to 3.0.
        radius (int, optional): Radius of the gaussian blur. Defaults to 6.
        truncate (int, optional): Truncate of the gaussian blur. Defaults to 4.
        boundary_mode (str, optional): Boundary Mode of the gaussian blur. Defaults to "nearest".
        dilate_prior (int, optional): Dilate this many voxels before starting the gaussian blur algorithm. Defaults to 0.
        dilate_connectivity (int, optional): Connectivity of the dilation process, if applied. Defaults to 3.
        smooth_background (bool, optional): If true, will also smooth the background. If False, the background voxels stay the same and the segmentation cannot add voxels. Defaults to True.
        inplace (bool, optional): If true, will overwrite the input NII instead of making a copy. Defaults to False.

    Returns:
        NII: The smoothed NII object.
    """
    assert self.seg, "You cannot use this on a non-segmentation NII"
    log.print("smooth_gaussian_labelwise",verbose=verbose)
    smoothed = np_smooth_gaussian_labelwise(
        self.get_seg_array(),
        label_to_smooth=label_to_smooth,
        sigma=sigma,
        radius=radius,
        truncate=truncate,
        boundary_mode=boundary_mode,
        dilate_prior=dilate_prior,
        dilate_connectivity=dilate_connectivity,
        smooth_background=smooth_background,
        background_threshold=background_threshold,
        dilate_channelwise=dilate_channelwise,
    )
    return self.set_array(smoothed, inplace, verbose=False)

smooth_gaussian_labelwise_

smooth_gaussian_labelwise_(label_to_smooth: list[int] | int, sigma: float = 3.0, radius: int = 6, truncate: int = 4, boundary_mode: str = 'nearest', dilate_prior: int = 1, dilate_connectivity: int = 1, dilate_channelwise: bool = False, smooth_background: bool = True, background_threshold: float | None = None) -> Self

In-place variant of smooth_gaussian_labelwise.

Source code in TPTBox/core/nii_wrapper.py
def smooth_gaussian_labelwise_(
    self,
    label_to_smooth: list[int] | int,
    sigma: float = 3.0,
    radius: int = 6,
    truncate: int = 4,
    boundary_mode: str = "nearest",
    dilate_prior: int = 1,
    dilate_connectivity: int = 1,
    dilate_channelwise: bool = False,
    smooth_background: bool = True,
    background_threshold: float | None = None,
) -> Self:
    """In-place variant of `smooth_gaussian_labelwise`."""
    return self.smooth_gaussian_labelwise(
        label_to_smooth=label_to_smooth,
        sigma=sigma,
        radius=radius,
        truncate=truncate,
        boundary_mode=boundary_mode,
        dilate_prior=dilate_prior,
        dilate_connectivity=dilate_connectivity,
        smooth_background=smooth_background,
        inplace=True,
        background_threshold=background_threshold,
        dilate_channelwise=dilate_channelwise,
    )

to_ants

to_ants() -> Any

Converts this NII to an ANTs image (requires the antspyx package).

Returns:

Type Description
Any

An ants.ANTsImage corresponding to this NII.

Raises:

Type Description
ImportError

If antspyx is not installed.

Source code in TPTBox/core/nii_wrapper.py
def to_ants(self) -> Any:
    """Converts this NII to an ANTs image (requires the ``antspyx`` package).

    Returns:
        An ``ants.ANTsImage`` corresponding to this NII.

    Raises:
        ImportError: If ``antspyx`` is not installed.
    """
    try:
        import ants
    except Exception:
        log.print_error()
        log.on_fail("run 'pip install antspyx' to install hf-deepali")
        raise
    return ants.from_nibabel(self.nii)

to_simpleITK

to_simpleITK() -> Any

Converts this NII to a SimpleITK image.

Returns:

Type Description
Any

A SimpleITK.Image corresponding to this NII.

Source code in TPTBox/core/nii_wrapper.py
def to_simpleITK(self) -> Any:
    """Converts this NII to a SimpleITK image.

    Returns:
        A ``SimpleITK.Image`` corresponding to this NII.
    """
    from TPTBox.core.sitk_utils import nii_to_sitk
    return nii_to_sitk(self)

from_deepali classmethod

from_deepali(img, seg=False) -> NII

Construct a NII from a DeepALI Image object.

Parameters:

Name Type Description Default
img

A deepali.data.Image instance.

required
seg

Mark the resulting NII as a segmentation mask.

False
Source code in TPTBox/core/nii_wrapper.py
@classmethod
def from_deepali(cls, img, seg=False) -> NII:
    """Construct a NII from a DeepALI ``Image`` object.

    Args:
        img: A ``deepali.data.Image`` instance.
        seg: Mark the resulting NII as a segmentation mask.
    """
    try:
        from deepali.data import Image as deepaliImage
    except Exception:
        log.print_error()
        log.on_fail("run 'pip install hf-deepali' to install deepali")
        raise
    img_ : deepaliImage =img
    grid = cls.from_deepali_grid(img_.grid())

    arr = img_.data.squeeze().cpu().detach().numpy()
    arr = np.transpose(arr, axes=tuple(reversed(range(arr.ndim))))
    return  NII((nib.Nifti1Image(arr,grid.affine)),seg=seg)

to_deepali

to_deepali(align_corners: bool = True, dtype=None, device: device | str = 'cpu') -> Any

Converts this NII to a DeepALI Image tensor (requires the hf-deepali package).

Parameters:

Name Type Description Default
align_corners bool

If True, aligns grid corners during conversion. Defaults to True.

True
dtype

Optional target torch dtype. Defaults to None (inferred).

None
device device | str

Target torch device. Defaults to "cpu".

'cpu'

Returns:

Type Description
Any

A deepali.data.Image corresponding to this NII.

Raises:

Type Description
ImportError

If hf-deepali is not installed.

Source code in TPTBox/core/nii_wrapper.py
def to_deepali(self, align_corners: bool = True, dtype=None, device: device | str = "cpu") -> Any:
    """Converts this NII to a DeepALI ``Image`` tensor (requires the ``hf-deepali`` package).

    Args:
        align_corners: If True, aligns grid corners during conversion. Defaults to True.
        dtype: Optional target torch dtype. Defaults to None (inferred).
        device: Target torch device. Defaults to ``"cpu"``.

    Returns:
        A ``deepali.data.Image`` corresponding to this NII.

    Raises:
        ImportError: If ``hf-deepali`` is not installed.
    """
    import torch
    try:
        from deepali.data import Image as deepaliImage  # type: ignore
    except Exception:
        log.print_error()
        log.on_fail("run 'pip install hf-deepali' to install deepali")
        raise
    dim = np.asarray(self.header["dim"])
    ndim = int(dim[0])
    # Image data array
    data = self.get_array()
    # Squeeze unused dimensions
    # https://github.com/InsightSoftwareConsortium/ITK/blob/3454d857dc46e4333ad1178be8c186547fba87ef/Modules/IO/NIFTI/src/itkNiftiImageIO.cxx#L1112-L1156
    intent_code = int(self.header["intent_code"]) # type: ignore
    if intent_code in (1005, 1006, 1007):
        # Vector or matrix valued image
        for realdim in range(4, 1, -1):
            if dim[realdim] > 1:
                break
        else:
            realdim = 1
    elif intent_code == 1004:
        raise NotImplementedError("NII has an intent code of NIFTI_INTENT_GENMATRIX which is not yet implemented")
    else:
        # Scalar image
        realdim = ndim
        while realdim > 3 and dim[realdim] == 1:
            realdim -= 1
    data = np.reshape(data, data.shape[:realdim] + data.shape[5:])
    # Reverse order of axes
    data = np.transpose(data, axes=tuple(reversed(range(data.ndim))))
    grid = self.to_deepali_grid(align_corners=align_corners)
    # Add leading channel dimension
    if data.ndim == grid.ndim:
        data = np.expand_dims(data, 0)
    if data.dtype == np.uint16:
        data = data.astype(np.int32)
    elif data.dtype == np.uint32:
        data = data.astype(np.int64)
    grid = grid.align_corners_(align_corners)
    data = torch.Tensor(data)
    #if len(torch.Tensor(data)) == 3:
    #   data = data.unsqueeze(0)
    return deepaliImage(data, grid, dtype=dtype, device=device)  # type: ignore

erode_msk

erode_msk(n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, inplace=False, verbose: logging = True, border_value=0, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self

Erodes the binary segmentation mask by the specified number of voxels.

Parameters:

Name Type Description Default
mm int

The number of voxels to erode the mask by. Defaults to 5.

required
labels LABEL_REFERENCE

Labels that should be dilated. If None, will erode all labels (not including zero!)

None
connectivity int

Elements up to a squared distance of connectivity from the center are considered neighbors. connectivity may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors).

3
inplace bool

Whether to modify the mask in place or return a new object. Defaults to False.

False
verbose bool

Whether to print a message indicating that the mask was eroded. Defaults to True.

True
use_crop

speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image

True

Returns: NII: The eroded mask.

Notes

The method uses binary erosion with a 3D structuring element to erode the mask by the specified number of voxels.

Source code in TPTBox/core/nii_wrapper.py
def erode_msk(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, inplace=False,verbose:logging=True,border_value=0, use_crop=True,ignore_direction:DIRECTIONS|int|None=None) -> Self:
    """Erodes the binary segmentation mask by the specified number of voxels.

    Args:
        mm (int, optional): The number of voxels to erode the mask by. Defaults to 5.
        labels (LABEL_REFERENCE, optional): Labels that should be dilated. If None, will erode all labels (not including zero!)
        connectivity (int, optional): Elements up to a squared distance of connectivity from the center are considered neighbors. connectivity may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors).
        inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
        verbose (bool, optional): Whether to print a message indicating that the mask was eroded. Defaults to True.
        use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
    Returns:
        NII: The eroded mask.

    Notes:
        The method uses binary erosion with a 3D structuring element to erode the mask by the specified number of voxels.

    """
    assert self.seg
    log.print("erode mask",end='\r',verbose=verbose)
    msk_i_data = self.get_seg_array()
    labels = self.unique() if labels is None else labels
    if isinstance(ignore_direction,str):
        ignore_direction = self.get_axis(ignore_direction)
    out = np_erode_msk(msk_i_data, label_ref=labels, n_pixel=n_pixel, connectivity=connectivity,border_value=border_value,ignore_axis=ignore_direction, use_crop=use_crop)
    out = out.astype(self.dtype)
    log.print("Mask eroded by", n_pixel, "voxels",verbose=verbose)
    return self.set_array(out,inplace=inplace)

erode_msk_

erode_msk_(n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, verbose: logging = True, border_value=0, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self

In-place variant of erode_msk.

Source code in TPTBox/core/nii_wrapper.py
def erode_msk_(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, verbose: logging = True, border_value=0, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self:
    """In-place variant of `erode_msk`."""
    return self.erode_msk(n_pixel=n_pixel, labels=labels, connectivity=connectivity, inplace=True, verbose=verbose,border_value=border_value,use_crop=use_crop,ignore_direction=ignore_direction)

erode_msk_euclid

erode_msk_euclid(n_pixel: int = 5, labels: LABEL_REFERENCE = None, mask: Self | None = None, inplace=False, verbose: logging = True, use_crop=True) -> Self

Euclidean erodes (in voxel space) a segmentation mask by the specified number.

Parameters:

Name Type Description Default
n_pixel int

The number of voxels to erode the mask by. Defaults to 5.

5
labels list[int]

Labels that should be eroded. If None, will erode all labels (not including zero!).

None
mask NII

If set, after operation, will zero out everything based on this mask.

None
inplace bool

Whether to modify the mask in place or return a new object. Defaults to False.

False
verbose bool

Whether to print a message. Defaults to True.

True
use_crop

Speed up computation by cropping/un-cropping.

True

Returns:

Name Type Description
NII Self

The eroded mask.

Notes

Uses Euclidean distance transform inside the foreground. Runtime is independent of n_pixel and len(labels). For n_pixel=1 this is similar to connectivity=1 erosion.

Source code in TPTBox/core/nii_wrapper.py
def erode_msk_euclid(
    self,
    n_pixel: int = 5,
    labels: LABEL_REFERENCE = None,
    mask: Self | None = None,
    inplace=False,
    verbose: logging = True,
    use_crop=True,
) -> Self:
    """Euclidean erodes (in voxel space) a segmentation mask by the specified number.

    Args:
        n_pixel (int, optional): The number of voxels to erode the mask by. Defaults to 5.
        labels (list[int], optional): Labels that should be eroded. If None, will erode all labels (not including zero!).
        mask (NII, optional): If set, after operation, will zero out everything based on this mask.
        inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
        verbose (bool, optional): Whether to print a message. Defaults to True.
        use_crop: Speed up computation by cropping/un-cropping.

    Returns:
        NII: The eroded mask.

    Notes:
        Uses Euclidean distance transform inside the foreground.
        Runtime is independent of n_pixel and len(labels).
        For n_pixel=1 this is similar to connectivity=1 erosion.
    """
    assert self.seg
    log.print("erode mask", end="\r", verbose=verbose)

    msk_i_data = self.get_seg_array()
    mask_ = mask.get_seg_array() if mask is not None else None

    out = np_erode_msk_euclid(
        arr=msk_i_data,
        n_pixel=n_pixel,
        labels=labels,
        use_crop=use_crop,
        mask=mask_
    )

    out = out.astype(self.dtype)

    log.print("Mask euclidean eroded by", n_pixel, "voxels", verbose=verbose)

    return self.set_array(out, inplace=inplace)

dilate_msk_euclid

dilate_msk_euclid(n_pixel: int = 5, labels: LABEL_REFERENCE = None, mask: Self | None = None, inplace=False, verbose: logging = True, use_crop=True) -> Self

Euclidean Dilates (in voxel space) a segmentation mask by the specified number.

Parameters:

Name Type Description Default
n_pixel int

The number of voxels to dilate the mask by. Defaults to 5.

5
labels list[int]

Labels that should be dilated. If None, will dilate all labels (not including zero!)

None
mask NII

If set, after each iteration, will zero out everything based on this mask

None
inplace bool

Whether to modify the mask in place or return a new object. Defaults to False.

False
verbose bool

Whether to print a message indicating that the mask was dilated. Defaults to True.

True
use_crop

speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image

True

Returns: NII: The dilated mask.

Notes

The method uses euclidean dilation to dilate the mask by the specified number of voxels. For n_pixel=1 dilate_msk_euclid and dilate_msk/connectivity=1 are equivalent. This will algorithm runtime is independent of n_pixel and len(labels) unlike dilate_msk

Source code in TPTBox/core/nii_wrapper.py
def dilate_msk_euclid(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, mask: Self | None = None, inplace=False, verbose: logging = True, use_crop=True) -> Self:
    """Euclidean Dilates (in voxel space) a segmentation mask by the specified number.

    Args:
        n_pixel (int, optional): The number of voxels to dilate the mask by. Defaults to 5.
        labels (list[int], optional): Labels that should be dilated. If None, will dilate all labels (not including zero!)
        mask (NII, optional): If set, after each iteration, will zero out everything based on this mask
        inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
        verbose (bool, optional): Whether to print a message indicating that the mask was dilated. Defaults to True.
        use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
    Returns:
        NII: The dilated mask.

    Notes:
        The method uses euclidean dilation to dilate the mask by the specified number of voxels.
        For n_pixel=1 dilate_msk_euclid and dilate_msk/connectivity=1 are equivalent.
        This will algorithm runtime is independent of n_pixel and len(labels) unlike dilate_msk

    """
    assert self.seg
    log.print("dilate mask",end='\r',verbose=verbose)
    msk_i_data = self.get_seg_array()
    mask_ = mask.get_seg_array() if mask is not None else None
    out = np_dilate_msk_euclid(arr=msk_i_data, n_pixel=n_pixel,labels=labels,use_crop=use_crop,mask=mask_)
    out = out.astype(self.dtype)
    log.print("Mask euclidean dilated by", n_pixel, "voxels",verbose=verbose)

    return self.set_array(out,inplace=inplace)

dilate_msk

dilate_msk(n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, mask: Self | None = None, inplace=False, verbose: logging = True, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self

Dilates the binary segmentation mask by the specified number of voxels.

Parameters:

Name Type Description Default
n_pixel int

The number of voxels to dilate the mask by. Defaults to 5.

5
labels list[int]

Labels that should be dilated. If None, will dilate all labels (not including zero!)

None
connectivity int

Elements up to a squared distance of connectivity from the center are considered neighbors. connectivity may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors).

3
mask NII

If set, after each iteration, will zero out everything based on this mask

None
inplace bool

Whether to modify the mask in place or return a new object. Defaults to False.

False
verbose bool

Whether to print a message indicating that the mask was dilated. Defaults to True.

True
use_crop

speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image

True

Returns: NII: The dilated mask.

Notes

The method uses binary dilation with a 3D structuring element to dilate the mask by the specified number of voxels.

Source code in TPTBox/core/nii_wrapper.py
def dilate_msk(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, mask: Self | None = None, inplace=False, verbose:logging=True,use_crop=True, ignore_direction:DIRECTIONS|int|None=None) -> Self:
    """Dilates the binary segmentation mask by the specified number of voxels.

    Args:
        n_pixel (int, optional): The number of voxels to dilate the mask by. Defaults to 5.
        labels (list[int], optional): Labels that should be dilated. If None, will dilate all labels (not including zero!)
        connectivity (int, optional): Elements up to a squared distance of connectivity from the center are considered neighbors. connectivity may range from 1 (no diagonal elements are neighbors) to rank (all elements are neighbors).
        mask (NII, optional): If set, after each iteration, will zero out everything based on this mask
        inplace (bool, optional): Whether to modify the mask in place or return a new object. Defaults to False.
        verbose (bool, optional): Whether to print a message indicating that the mask was dilated. Defaults to True.
        use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
    Returns:
        NII: The dilated mask.

    Notes:
        The method uses binary dilation with a 3D structuring element to dilate the mask by the specified number of voxels.

    """
    assert self.seg
    log.print("dilate mask",end='\r',verbose=verbose)
    if labels is None:
        labels = self.unique()
    msk_i_data = self.get_seg_array()
    mask_ = mask.get_seg_array() if mask is not None else None
    if isinstance(ignore_direction,str):
        ignore_direction = self.get_axis(ignore_direction)
    out = np_dilate_msk(arr=msk_i_data, label_ref=labels, n_pixel=n_pixel, mask=mask_, connectivity=connectivity,ignore_axis=ignore_direction, use_crop=use_crop)
    out = out.astype(self.dtype)
    log.print("Mask dilated by", n_pixel, "voxels",verbose=verbose)
    return self.set_array(out,inplace=inplace)

dilate_msk_

dilate_msk_(n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, mask: Self | None = None, verbose: logging = True, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self

In-place variant of dilate_msk.

Source code in TPTBox/core/nii_wrapper.py
def dilate_msk_(self, n_pixel: int = 5, labels: LABEL_REFERENCE = None, connectivity: int = 3, mask: Self | None = None, verbose: logging = True, use_crop=True, ignore_direction: DIRECTIONS | int | None = None) -> Self:
    """In-place variant of `dilate_msk`."""
    return self.dilate_msk(n_pixel=n_pixel, labels=labels, connectivity=connectivity, mask=mask, inplace=True, verbose=verbose,use_crop=use_crop,ignore_direction=ignore_direction)

fill_holes

fill_holes(labels: LABEL_REFERENCE = None, slice_wise_dim: int | str | None = None, verbose: logging = False, inplace=False, use_crop=True) -> Self

Fills holes in segmentation.

Parameters:

Name Type Description Default
labels LABEL_REFERENCE

Labels that the hole-filling should be applied to. If none, applies on all labels found in arr. Defaults to None.

None
verbose logging

whether to print which labels have been filled

False
inplace bool

Whether to modify the current NIfTI image object in place or create a new object with the mapped labels. Default is False.

False
slice_wise_dim int | None

If the input is 3D, the specified dimension here cna be used for 2D slice-wise filling. Defaults to None.

None
use_crop

speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image

True

Returns: NII: If inplace is True, returns the current NIfTI image object with filled holes. Otherwise, returns a new NIfTI image object with filled holes.

Source code in TPTBox/core/nii_wrapper.py
def fill_holes(self, labels: LABEL_REFERENCE = None, slice_wise_dim: int|str | None = None, verbose:logging=False, inplace=False,use_crop=True) -> Self:  # noqa: ARG002
    """Fills holes in segmentation.

    Args:
        labels (LABEL_REFERENCE, optional): Labels that the hole-filling should be applied to. If none, applies on all labels found in arr. Defaults to None.
        verbose: whether to print which labels have been filled
        inplace (bool): Whether to modify the current NIfTI image object in place or create a new object with the mapped labels.
            Default is False.
        slice_wise_dim (int | None, optional): If the input is 3D, the specified dimension here cna be used for 2D slice-wise filling. Defaults to None.
        use_crop: speed up computation by cropping and un-cropping the segmentation. Minor overhead if the segmentation fills most of the image
    Returns:
        NII: If inplace is True, returns the current NIfTI image object with filled holes. Otherwise, returns a new NIfTI image object with filled holes.
    """
    assert self.seg
    if labels is None:
        labels = list(self.unique())

    if isinstance(labels, int):
        labels = [labels]

    seg_arr = self.get_seg_array()
    if isinstance(slice_wise_dim,str):
        slice_wise_dim = self.get_axis(slice_wise_dim)
    #seg_arr = self.get_seg_array()
    filled = np_fill_holes(seg_arr, label_ref=labels, slice_wise_dim=slice_wise_dim, use_crop=use_crop)
    return self.set_array(filled,inplace=inplace)

fill_holes_

fill_holes_(labels: LABEL_REFERENCE = None, slice_wise_dim: int | str | None = None, verbose: logging = True, use_crop=True) -> Self

In-place variant of fill_holes.

Source code in TPTBox/core/nii_wrapper.py
def fill_holes_(self, labels: LABEL_REFERENCE = None, slice_wise_dim: int | str | None = None, verbose: logging = True, use_crop=True) -> Self:
    """In-place variant of `fill_holes`."""
    return self.fill_holes(labels, slice_wise_dim, verbose, inplace=True,use_crop=use_crop)

calc_convex_hull

calc_convex_hull(axis: DIRECTIONS | None = 'S', inplace: bool = False, verbose: bool = False) -> Self

Calculates the convex hull of this segmentation nifty.

Parameters:

Name Type Description Default
axis int | None

If given axis, will calculate convex hull along that axis (remaining dimension must be at least 2). Defaults to None.

'S'
Source code in TPTBox/core/nii_wrapper.py
def calc_convex_hull(
    self,
    axis: DIRECTIONS|None = "S",
    inplace: bool = False,
    verbose: bool = False
) -> Self:
    """Calculates the convex hull of this segmentation nifty.

    Args:
        axis (int | None, optional): If given axis, will calculate convex hull along that axis (remaining dimension must be at least 2). Defaults to None.
    """
    assert self.seg, "To calculate the convex hull, this must be a segmentation"
    axis_int = self.get_axis(axis) if axis is not None else None
    convex_hull_arr = np_calc_convex_hull(self.get_seg_array(), axis=axis_int, verbose=verbose)
    if inplace:
        return self.set_array_(convex_hull_arr)
    return self.set_array(convex_hull_arr)

calc_convex_hull_

calc_convex_hull_(axis: None | DIRECTIONS = 'S', verbose: bool = False) -> Self

In-place variant of calc_convex_hull.

Source code in TPTBox/core/nii_wrapper.py
def calc_convex_hull_(self, axis: None | DIRECTIONS = "S", verbose: bool = False) -> Self:
    """In-place variant of `calc_convex_hull`."""
    return self.calc_convex_hull(axis=axis, inplace=True, verbose=verbose)

boundary_mask

boundary_mask(threshold: float, inplace=False) -> Self

Calculate a boundary mask based on the input image.

Parameters: - img (NII): The image used to create the boundary mask. - threshold(float): threshold

Returns: NII: A segmentation of the boundary.

This function takes a NII and generates a boundary mask by marking specific regions. The intensity of the image can be adjusted for CT scans by adding 1000. The boundary mask is created by initializing corner points and using an "infect" process to mark neighboring points. The boundary mask is initiated with zeros, and specific boundary points are set to 1. The "infect" function iteratively marks neighboring points in the mask. The process starts from the initial points and corner points of the image. The infection process continues until the infect_list is empty. The resulting boundary mask is modified by subtracting 1 from all non-zero values and setting the remaining zeros to 2. The sum of the boundary mask values is printed before returning the modified NII object.

Source code in TPTBox/core/nii_wrapper.py
def boundary_mask(self, threshold: float,inplace = False) -> Self:
    """Calculate a boundary mask based on the input image.

    Parameters:
    - img (NII): The image used to create the boundary mask.
    - threshold(float): threshold

    Returns:
    NII: A segmentation of the boundary.


    This function takes a NII and generates a boundary mask by marking specific regions.
    The intensity of the image can be adjusted for CT scans by adding 1000. The boundary mask is created by initializing
    corner points and using an "infect" process to mark neighboring points. The boundary mask is initiated with
    zeros, and specific boundary points are set to 1. The "infect" function iteratively marks neighboring points in the mask.
    The process starts from the initial points and corner points of the image. The infection process continues until the
    infect_list is empty. The resulting boundary mask is modified by subtracting 1 from all non-zero values and setting
    the remaining zeros to 2. The sum of the boundary mask values is printed before returning the modified NII object.

    """
    return self.set_array(np_calc_boundary_mask(self.get_array(),threshold),inplace=inplace,verbose=False)

get_connected_components

get_connected_components(labels: int | list[int] | None = None, connectivity: int = 3, include_zero: bool = False, inplace=False) -> Self

Replaces each label with a unique connected-component index.

Parameters:

Name Type Description Default
labels int | list[int] | None

Labels to process. If None, processes all non-zero labels.

None
connectivity int

Voxel connectivity (1 = face-adjacent, 3 = corner-adjacent). Defaults to 3.

3
include_zero bool

If True, also labels the background (0) as components. Defaults to False.

False
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

An NII where each connected component has a unique integer label.

Raises:

Type Description
AssertionError

If seg=False.

Source code in TPTBox/core/nii_wrapper.py
def get_connected_components(self, labels: int | list[int] | None = None, connectivity: int = 3, include_zero: bool = False, inplace=False) -> Self:
    """Replaces each label with a unique connected-component index.

    Args:
        labels: Labels to process. If None, processes all non-zero labels.
        connectivity: Voxel connectivity (1 = face-adjacent, 3 = corner-adjacent).
            Defaults to 3.
        include_zero: If True, also labels the background (0) as components.
            Defaults to False.
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        An NII where each connected component has a unique integer label.

    Raises:
        AssertionError: If ``seg=False``.
    """
    assert self.seg, "This only works on segmentations"
    out, _ = np_connected_components(self.get_seg_array(), label_ref=labels, connectivity=connectivity, include_zero=include_zero)
    return self.set_array(out,inplace=inplace)

get_connected_components_per_label

get_connected_components_per_label(labels: int | list[int], connectivity: int = 3, include_zero: bool = False) -> dict[int, Self]

Returns a dict mapping each label to an NII containing only that label's connected components.

Parameters:

Name Type Description Default
labels int | list[int]

Label(s) to process.

required
connectivity int

Voxel connectivity (1 to 3). Defaults to 3.

3
include_zero bool

Whether to include the background. Defaults to False.

False

Returns:

Type Description
dict[int, Self]

A dict {label: NII} where each NII holds the component-indexed array

dict[int, Self]

for that label.

Raises:

Type Description
AssertionError

If seg=False.

Source code in TPTBox/core/nii_wrapper.py
def get_connected_components_per_label(self, labels: int | list[int], connectivity: int = 3, include_zero: bool = False) -> dict[int, Self]:
    """Returns a dict mapping each label to an NII containing only that label's connected components.

    Args:
        labels: Label(s) to process.
        connectivity: Voxel connectivity (1 to 3). Defaults to 3.
        include_zero: Whether to include the background. Defaults to False.

    Returns:
        A dict ``{label: NII}`` where each NII holds the component-indexed array
        for that label.

    Raises:
        AssertionError: If ``seg=False``.
    """
    assert self.seg, "This only works on segmentations"
    out = np_connected_components_per_label(self.get_seg_array(), label_ref=labels, connectivity=connectivity, include_zero=include_zero)
    cc = {i: self.set_array(k) for i,k in out.items()}
    return cc

filter_connected_components

filter_connected_components(labels: int | list[int] | None = None, min_volume: int = 0, max_volume: int | None = None, max_count_component=None, connectivity: int = 3, removed_to_label=0, keep_label=False, inplace=False) -> Self

Filter connected components in a segmentation array based on specified volume constraints.

Parameters: labels (int | list[int]): The labels of the components to filter. min_volume (int | None): Minimum volume for a component to be retained. Components smaller than this will be removed. max_volume (int | None): Maximum volume for a component to be retained. Components larger than this will be removed. max_count_component (int | None): Maximum number of components to retain. Once this limit is reached, remaining components will be removed. connectivity (int): Connectivity criterion for defining connected components (default is 3). removed_to_label (int): Label to assign to removed components (default is 0). TODO : max_count_component currently filters over all labels instead of per label. will be changed. TODO : removed_to_label does not work when keep_label=False Returns: None

Source code in TPTBox/core/nii_wrapper.py
def filter_connected_components(self, labels: int |list[int]|None=None,min_volume:int=0,max_volume:int|None=None, max_count_component = None, connectivity: int = 3,removed_to_label=0,keep_label=False, inplace=False,) -> Self:
    """Filter connected components in a segmentation array based on specified volume constraints.

    Parameters:
    labels (int | list[int]): The labels of the components to filter.
    min_volume (int | None): Minimum volume for a component to be retained. Components smaller than this will be removed.
    max_volume (int | None): Maximum volume for a component to be retained. Components larger than this will be removed.
    max_count_component (int | None): Maximum number of components to retain. Once this limit is reached, remaining components will be removed.
    connectivity (int): Connectivity criterion for defining connected components (default is 3).
    removed_to_label (int): Label to assign to removed components (default is 0).
    TODO : max_count_component currently filters over all labels instead of per label. will be changed.
    TODO : removed_to_label does not work when keep_label=False
    Returns:
    None
    """
    assert self.seg, "This only works on segmentations"
    arr = np_filter_connected_components(self.get_seg_array(), largest_k_components=max_count_component,label_ref=labels,connectivity=connectivity,return_original_labels=keep_label,min_volume=min_volume,max_volume=max_volume,removed_to_label=removed_to_label,)
    assert arr.shape == self.shape, f"Shape mismatch: {arr.shape} != {self.shape}"
    if keep_label and labels is not None:
        if isinstance(labels,int):
            labels = [labels]
        old_labels = [i for i in self.unique() if i not in labels]
        if len(old_labels) != 0:
            s = self.extract_label(old_labels,keep_label=True).get_array()
            arr[s != 0] = s[s!=0]
    #print("filter",nii.unique())
    #assert max_count_component is None or nii.max() <= max_count_component, nii.unique()
    return self.set_array(arr, inplace=inplace)

filter_connected_components_

filter_connected_components_(labels: int | list[int] | None = None, min_volume: int = 0, max_volume: int | None = None, max_count_component=None, connectivity: int = 3, keep_label=False, removed_to_label=0) -> Self

In-place variant of filter_connected_components.

Source code in TPTBox/core/nii_wrapper.py
def filter_connected_components_(self, labels: int | list[int] | None = None, min_volume: int = 0, max_volume: int | None = None, max_count_component=None, connectivity: int = 3, keep_label=False, removed_to_label=0) -> Self:
    """In-place variant of `filter_connected_components`."""
    return self.filter_connected_components(labels,min_volume=min_volume,max_volume=max_volume, max_count_component = max_count_component, connectivity = connectivity,removed_to_label=removed_to_label,keep_label=keep_label,inplace=True)

get_segmentation_connected_components_center_of_mass

get_segmentation_connected_components_center_of_mass(label: int, connectivity: int = 3, sort_by_axis: int | None = None) -> list[COORDINATE]

Calculates the center of mass of each connected component for a given label.

Parameters:

Name Type Description Default
label int

The integer label whose connected components are analysed.

required
connectivity int

Voxel connectivity (1 to 3). Defaults to 3.

3
sort_by_axis int | None

If not None, the returned list is sorted by the voxel coordinate along this axis. Defaults to None.

None

Returns:

Type Description
list[COORDINATE]

A list of (x, y, z) voxel coordinates, one per connected component.

Raises:

Type Description
AssertionError

If seg=False.

Source code in TPTBox/core/nii_wrapper.py
def get_segmentation_connected_components_center_of_mass(self, label: int, connectivity: int = 3, sort_by_axis: int | None = None) -> list[COORDINATE]:
    """Calculates the center of mass of each connected component for a given label.

    Args:
        label: The integer label whose connected components are analysed.
        connectivity: Voxel connectivity (1 to 3). Defaults to 3.
        sort_by_axis: If not None, the returned list is sorted by the voxel
            coordinate along this axis. Defaults to None.

    Returns:
        A list of ``(x, y, z)`` voxel coordinates, one per connected component.

    Raises:
        AssertionError: If ``seg=False``.
    """
    assert self.seg, "This only works on segmentations"
    arr = self.get_seg_array()
    return np_get_connected_components_center_of_mass(arr, label=label, connectivity=connectivity, sort_by_axis=sort_by_axis)

get_largest_k_segmentation_connected_components

get_largest_k_segmentation_connected_components(k: int | None, labels: int | list[int] | None = None, connectivity: int = 1, return_original_labels: bool = True, inplace=False, min_volume: int = 0, max_volume: int | None = None, removed_to_label=0) -> Self

Finds the largest k connected components in a given array (does NOT work with zero as label!).

Parameters:

Name Type Description Default
arr ndarray

input array

required
k int | None

finds the k-largest components. If k is None, will find all connected components and still sort them by size

required
labels int | list[int] | None

Labels that the algorithm should be applied to. If none, applies on all labels found in this NII. Defaults to None.

None
return_original_labels bool

If set to False, will label the components from 1 to k. Defaults to True

True
Source code in TPTBox/core/nii_wrapper.py
def get_largest_k_segmentation_connected_components(self, k: int | None, labels: int | list[int] | None = None, connectivity: int = 1, return_original_labels: bool = True,inplace=False,min_volume:int=0,max_volume:int|None=None,removed_to_label=0) -> Self:
    """Finds the largest k connected components in a given array (does NOT work with zero as label!).

    Args:
        arr (np.ndarray): input array
        k (int | None): finds the k-largest components. If k is None, will find all connected components and still sort them by size
        labels (int | list[int] | None, optional): Labels that the algorithm should be applied to. If none, applies on all labels found in this NII. Defaults to None.
        return_original_labels (bool): If set to False, will label the components from 1 to k. Defaults to True
    """
    raise DeprecationWarning("Use filter_connected_components instead")
    msk_i_data = self.get_seg_array()
    out = np_filter_connected_components(msk_i_data, largest_k_components=k, label_ref=labels, connectivity=connectivity, return_original_labels=return_original_labels,min_volume=min_volume,max_volume=max_volume,removed_to_label=removed_to_label)
    return self.set_array(out,inplace=inplace)

compute_surface_mask

compute_surface_mask(connectivity: int = 3, dilated_surface: bool = False) -> Self

Removes everything but surface voxels.

Parameters:

Name Type Description Default
connectivity int

Connectivity for surface calculation

3
dilated_surface bool

If False, will return msk - eroded mask. If true, will return dilated msk - msk

False
Source code in TPTBox/core/nii_wrapper.py
def compute_surface_mask(self, connectivity: int = 3, dilated_surface: bool = False) -> Self:
    """Removes everything but surface voxels.

    Args:
        connectivity (int): Connectivity for surface calculation
        dilated_surface (bool): If False, will return msk - eroded mask. If true, will return dilated msk - msk
    """
    assert self.seg, "This only works on segmentations"
    return self.set_array(np_compute_surface(self.get_seg_array(), connectivity=connectivity, dilated_surface=dilated_surface))

compute_surface_points

compute_surface_points(connectivity: int = 3, dilated_surface: bool = False) -> list[tuple[int, int, int]]

Returns voxel coordinates of all surface voxels in the segmentation.

Parameters:

Name Type Description Default
connectivity int

Connectivity for surface calculation. Defaults to 3.

3
dilated_surface bool

If False, returns mask - eroded_mask; if True, returns dilated_mask - mask. Defaults to False.

False

Returns:

Type Description
list[tuple[int, int, int]]

A list of (x, y, z) voxel coordinate tuples for every surface voxel.

Raises:

Type Description
AssertionError

If seg=False.

Source code in TPTBox/core/nii_wrapper.py
def compute_surface_points(self, connectivity: int = 3, dilated_surface: bool = False) -> list[tuple[int, int, int]]:
    """Returns voxel coordinates of all surface voxels in the segmentation.

    Args:
        connectivity: Connectivity for surface calculation. Defaults to 3.
        dilated_surface: If False, returns ``mask - eroded_mask``; if True,
            returns ``dilated_mask - mask``. Defaults to False.

    Returns:
        A list of ``(x, y, z)`` voxel coordinate tuples for every surface voxel.

    Raises:
        AssertionError: If ``seg=False``.
    """
    assert self.seg, "This only works on segmentations"
    surface = self.compute_surface_mask(connectivity, dilated_surface)
    return np_point_coordinates(surface.get_seg_array()) # type: ignore

fill_holes_global_with_majority_voting

fill_holes_global_with_majority_voting(connectivity: int = 3, inplace: bool = False, verbose: bool = False) -> Self

Fills 3D holes globally, and resolves inter-label conflicts with majority voting by neighbors.

Parameters:

Name Type Description Default
connectivity int

Connectivity of fill holes. Defaults to 3.

3
inplace bool

Defaults to False.

False
verbose bool

Defaults to False.

False

Returns:

Name Type Description
NII Self
Source code in TPTBox/core/nii_wrapper.py
def fill_holes_global_with_majority_voting(self, connectivity: int = 3, inplace: bool = False, verbose: bool = False) -> Self:
    """Fills 3D holes globally, and resolves inter-label conflicts with majority voting by neighbors.

    Args:
        connectivity (int, optional): Connectivity of fill holes. Defaults to 3.
        inplace (bool, optional): Defaults to False.
        verbose (bool, optional): Defaults to False.

    Returns:
        NII:
    """
    assert self.seg, "This only works on segmentations"
    arr = np_fill_holes_global_with_majority_voting(self.get_seg_array(), connectivity=connectivity, verbose=verbose, inplace=inplace)
    return self.set_array(arr,inplace=inplace)

map_labels_based_on_majority_label_mask_overlap

map_labels_based_on_majority_label_mask_overlap(label_mask: Self, labels: int | list[int] | None = None, dilate_pixel: int = 1, inplace: bool = False, no_match_label=0) -> Self

Relabels all individual labels from input array to the majority labels of a given label_mask.

Parameters:

Name Type Description Default
label_mask ndarray

the mask from which to pull the target labels.

required
labels int | list[int] | None

Which labels in the input to process. Defaults to None.

None
dilate_pixel int

If true, will dilate the input to calculate the overlap. Defaults to 1.

1
inplace bool

Defaults to False.

False

Returns:

Name Type Description
NII Self

Relabeled nifti

Source code in TPTBox/core/nii_wrapper.py
def map_labels_based_on_majority_label_mask_overlap(self, label_mask: Self, labels: int | list[int] | None = None, dilate_pixel: int = 1, inplace: bool = False,no_match_label=0) -> Self:
    """Relabels all individual labels from input array to the majority labels of a given label_mask.

    Args:
        label_mask (np.ndarray): the mask from which to pull the target labels.
        labels (int | list[int] | None, optional): Which labels in the input to process. Defaults to None.
        dilate_pixel (int, optional): If true, will dilate the input to calculate the overlap. Defaults to 1.
        inplace (bool, optional): Defaults to False.

    Returns:
        NII: Relabeled nifti
    """
    assert self.seg and label_mask.seg, "This only works on segmentations"
    return self.set_array(np_map_labels_based_on_majority_label_mask_overlap(self.get_seg_array(), label_mask.get_seg_array(), label_ref=labels, dilate_pixel=dilate_pixel, inplace=inplace,no_match_label=no_match_label), inplace=inplace,)

get_segmentation_difference_to

get_segmentation_difference_to(mask_gt: Self, ignore_background_tp: bool = False) -> Self

Calculates an NII that represents the segmentation difference between self and given groundtruth mask.

Parameters:

Name Type Description Default
mask_groundtruth Self

The ground truth mask. Must match in orientation, zoom, and shape

required

Returns:

Name Type Description
NII Self

Difference NII (1: FN, 2: TP, 3: FP, 4: Wrong label)

Source code in TPTBox/core/nii_wrapper.py
def get_segmentation_difference_to(self, mask_gt: Self, ignore_background_tp: bool = False) -> Self:
    """Calculates an NII that represents the segmentation difference between self and given groundtruth mask.

    Args:
        mask_groundtruth (Self): The ground truth mask. Must match in orientation, zoom, and shape

    Returns:
        NII: Difference NII (1: FN, 2: TP, 3: FP, 4: Wrong label)
    """
    assert self.seg and mask_gt.seg, "This only works on segmentations"
    if self.orientation != mask_gt.orientation:
        mask_gt = mask_gt.reorient_same_as(self)

    self.assert_affine(zoom=mask_gt.zoom, shape=mask_gt.shape)
    arr = self.get_seg_array()
    gt = mask_gt.get_seg_array()
    diff_arr = arr.copy() * 0
    # TP
    diff_arr[gt == arr] = 2
    # FN
    diff_arr[(gt != 0) & (arr == 0)] = 1
    # FP
    diff_arr[(gt == 0) & (arr != 0)] = 3
    # Wrong label
    diff_arr[(diff_arr == 0) & (gt != arr)] = 4

    if ignore_background_tp:
        diff_arr[(gt == 0) & (arr == 0)] = 0

    return self.set_array(diff_arr)

get_overlapping_labels_to

get_overlapping_labels_to(mask_other: Self) -> list[tuple[int, int]]

Calculates the pairs of labels that are overlapping in at least one voxel (fast).

Parameters:

Name Type Description Default
mask_other NII

The array to be compared with.

required

Returns:

Type Description
list[tuple[int, int]]

list[tuple[int, int]]: List of tuples of labels that overlap in at least one voxel. First label in the tuple is Self NII, the second is of the mask_other

Source code in TPTBox/core/nii_wrapper.py
def get_overlapping_labels_to(
    self,
    mask_other: Self
) -> list[tuple[int, int]]:
    """Calculates the pairs of labels that are overlapping in at least one voxel (fast).

    Args:
        mask_other (NII): The array to be compared with.

    Returns:
        list[tuple[int, int]]: List of tuples of labels that overlap in at least one voxel. First label in the tuple is Self NII, the second is of the mask_other
    """
    assert self.seg and mask_other.seg
    return np_calc_overlapping_labels(self.get_seg_array(), mask_other.get_seg_array())

is_segmentation_in_border

is_segmentation_in_border(minimum=0, voxel_tolerance: int = 2, use_mm=False) -> bool

Checks if the segmentation is touching the border of the image volume.

Parameters: - minimum (int, optional): Minimum intensity threshold for segmentation. Defaults to 0. - voxel_tolerance (int, optional): Number of voxels allowed as tolerance from the border. Defaults to 2. - use_mm (bool, optional): Whether to use millimeter units instead of voxels. Defaults to False.

Returns: - bool: True if the segmentation is within the defined voxel tolerance of the border, False otherwise.

Source code in TPTBox/core/nii_wrapper.py
def is_segmentation_in_border(self,minimum=0, voxel_tolerance: int = 2,use_mm=False) -> bool:
    """Checks if the segmentation is touching the border of the image volume.

    Parameters:
    - minimum (int, optional): Minimum intensity threshold for segmentation. Defaults to 0.
    - voxel_tolerance (int, optional): Number of voxels allowed as tolerance from the border. Defaults to 2.
    - use_mm (bool, optional): Whether to use millimeter units instead of voxels. Defaults to False.

    Returns:
    - bool: True if the segmentation is within the defined voxel tolerance of the border, False otherwise.
    """
    slices = self.compute_crop(minimum,dist=0,use_mm=use_mm,raise_error=False)
    if slices is None:
        return False
    shp = self.shape
    seg_at_border = False
    for d in range(3):
        if slices[d].start <= voxel_tolerance or slices[d].stop - 1 >= shp[d] - voxel_tolerance:
            seg_at_border = True
            break
    return seg_at_border

truncate_labels_beyond_reference_

truncate_labels_beyond_reference_(idx: int | list[int] = 1, not_beyond: int | list[int] = 1, fill: int = 0, axis: DIRECTIONS = 'S', inclusion: bool = False, inplace: bool = True) -> Self

Remove voxels with label idx beyond a reference label along a specified axis.

Replaces those voxels with fill (default 0).

Parameters:

Name Type Description Default
nii NII

The NIfTI-like object with 3D imaging data.

required
idx int or list[int]

The index/label(s) to process in the array. Default is 1.

1
not_beyond int or list[int]

The label/index used to determine the reference position. Default is 1.

1
fill int

The value to set for voxels beyond the reference point. Default is 0.

0
axis str

The anatomical axis along which truncation is applied. Default is "S" (superior). Options: - "S" (Superior) - "I" (Inferior) - "R" (Right) - "L" (Left) - "A" (Anterior) - "P" (Posterior)

'S'
inclusion bool

Controls whether the reference label not_beyond itself is considered a boundary. - False (default): The truncation occurs strictly beyond the reference label. - True: The truncation includes the reference label as well.

False
inplace bool

If True, modifies the NIfTI object in place. If False, returns a modified copy.

True

Returns:

Name Type Description
NII Self

The modified NIfTI object.

Source code in TPTBox/core/nii_wrapper.py
def truncate_labels_beyond_reference_(
    self, idx: int | list[int] = 1, not_beyond: int | list[int] = 1, fill: int = 0,  axis: DIRECTIONS = "S", inclusion: bool = False, inplace: bool = True
) -> Self:
    """Remove voxels with label ``idx`` beyond a reference label along a specified axis.

    Replaces those voxels with ``fill`` (default 0).

    Parameters:
        nii (NII): The NIfTI-like object with 3D imaging data.
        idx (int or list[int]): The index/label(s) to process in the array. Default is 1.
        not_beyond (int or list[int]): The label/index used to determine the reference position. Default is 1.
        fill (int): The value to set for voxels beyond the reference point. Default is 0.
        axis (str): The anatomical axis along which truncation is applied. Default is "S" (superior).
            Options:
            - "S" (Superior)
            - "I" (Inferior)
            - "R" (Right)
            - "L" (Left)
            - "A" (Anterior)
            - "P" (Posterior)
        inclusion (bool): Controls whether the reference label `not_beyond` itself is considered a boundary.
            - `False` (default): The truncation occurs strictly beyond the reference label.
            - `True`: The truncation includes the reference label as well.
        inplace (bool): If `True`, modifies the NIfTI object in place. If `False`, returns a modified copy.

    Returns:
        NII: The modified NIfTI object.
    """
    # Identify the axis to work on
    axis_ = self.get_axis(axis)
    flip = self.orientation[axis_] != axis  # Check orientation for flipping
    # Get the array data
    np_array = self.get_array()
    np_array_cond = self.extract_label(idx).get_seg_array()

    # Find the lowest point (smallest index) along the axis where `not_above` exists
    threshold = np.where(self.extract_label(not_beyond).get_seg_array() == 1)
    if len(threshold[axis_]) == 0:
        return self if inplace else self.copy()
    flip_up = flip
    if not inclusion:
        flip_up = not flip_up
    # Determine the lowest index along the axis
    limit = threshold[axis_].min() if flip_up else threshold[axis_].max()

    # Create an array of indices along the specified axis
    index_grid = np.arange(self.shape[axis_])

    # Create a mask to identify the region above or below the threshold
    mask = index_grid < limit if flip else index_grid >= limit

    # Apply the mask along the specified axis
    mask = np.expand_dims(mask, axis=tuple(i for i in range(np_array.ndim) if i != axis_))
    mask = np.broadcast_to(mask, self.shape)

    # Replace values of `idx` with `fill` in the masked region
    np_array = np.where((np_array_cond == 1) & mask, fill, np_array)

    # Update the NIfTI object with the modified array
    return self.set_array(np_array, inplace=inplace)

truncate_labels_beyond_reference

truncate_labels_beyond_reference(idx: int | list[int] = 1, not_beyond: int | list[int] = 1, fill: int = 0, axis: DIRECTIONS = 'S', inclusion: bool = False, inplace=False) -> Self

Removes label idx voxels beyond the extent of not_beyond along axis.

This is the out-of-place counterpart of truncate_labels_beyond_reference_. See that method for full parameter documentation.

Returns:

Type Description
Self

The modified NII (new object by default).

Source code in TPTBox/core/nii_wrapper.py
def truncate_labels_beyond_reference(
    self,
    idx: int | list[int] = 1,
    not_beyond: int | list[int] = 1,
    fill: int = 0,
    axis: DIRECTIONS = "S",
    inclusion: bool = False,
    inplace=False,
) -> Self:
    """Removes label ``idx`` voxels beyond the extent of ``not_beyond`` along ``axis``.

    This is the out-of-place counterpart of ``truncate_labels_beyond_reference_``.
    See that method for full parameter documentation.

    Returns:
        The modified NII (new object by default).
    """
    return self.truncate_labels_beyond_reference_(idx,not_beyond,fill,axis,inclusion,inplace=inplace)

infect

infect(reference_mask: NII, inplace=False, verbose=True, axis: int | str | None = None, max_depth=None, _do_crop=True) -> Self

Expands labels from this segmentation into a reference mask via breadth-first diffusion.

Starting from the surface voxels of this NII, the algorithm propagates existing labels into neighbouring voxels where reference_mask == 1, until no more unlabelled neighbour voxels remain (or max_depth is reached).

Parameters:

Name Type Description Default
reference_mask NII

Binary NII that defines the region into which labels may spread. Must have the same affine as self.

required
inplace

If True, modifies this NII in place. Defaults to False.

False
verbose

If True, shows a tqdm progress bar. Defaults to True.

True
axis int | str | None

If given, restricts diffusion to the plane perpendicular to this axis (int or anatomical direction string). Defaults to None (3-D).

None
max_depth

Maximum number of propagation steps (layers). Defaults to None (unlimited).

None

Returns:

Type Description
Self

The NII with expanded labels.

Source code in TPTBox/core/nii_wrapper.py
def infect(self: NII, reference_mask: NII, inplace=False, verbose=True, axis: int | str | None = None, max_depth=None, _do_crop=True) -> Self:
    """Expands labels from this segmentation into a reference mask via breadth-first diffusion.

    Starting from the surface voxels of this NII, the algorithm propagates existing
    labels into neighbouring voxels where ``reference_mask == 1``, until no more
    unlabelled neighbour voxels remain (or ``max_depth`` is reached).

    Args:
        reference_mask: Binary NII that defines the region into which labels may
            spread. Must have the same affine as ``self``.
        inplace: If True, modifies this NII in place. Defaults to False.
        verbose: If True, shows a tqdm progress bar. Defaults to True.
        axis: If given, restricts diffusion to the plane perpendicular to this
            axis (int or anatomical direction string). Defaults to None (3-D).
        max_depth: Maximum number of propagation steps (layers). Defaults to None
            (unlimited).

    Returns:
        The NII with expanded labels.
    """
    self.assert_affine(reference_mask)
    if _do_crop:
        crop = reference_mask.compute_crop(0,5,raise_error=False)
        s = self.apply_crop(crop)
        reference_mask = reference_mask.apply_crop(crop)
    else:
        s = self
    self_mask = s.compute_surface_mask().get_seg_array().copy()
    self_mask_org = s.get_seg_array().copy()
    ref_mask = np.clip(reference_mask.get_seg_array(), 0, 1)
    ref_mask[self_mask_org != 0] = 0
    searched = np.clip(self_mask,0,1).astype(np.uint8)

    # Define neighborhood kernel
    if axis is None:
        kernel = [(1,0,0),(0,1,0),(0,0,1),(-1,0,0),(0,-1,0),(0,0,-1)]
    else:
        if isinstance(axis,str):
            axis = self.get_axis(axis)
        if axis == 0:
            kernel = [(0,1,0),(0,0,1),(0,-1,0),(0,0,-1)]
        elif axis == 1:
            kernel = [(1,0,0),(0,0,1),(-1,0,0),(0,0,-1)]
        elif axis == 2:
            kernel = [(1,0,0),(0,1,0),(-1,0,0),(0,-1,0)]
        else:
            raise NotImplementedError(axis)

    search = deque()
    coords = np.where(self_mask != 0)
    def _add_idx(x,y,z,v,d):
        for x1,y1,z1 in kernel:
            a = x+x1
            b = y+y1
            c = z+z1

            if a < 0 or b < 0 or c < 0:
                continue
            if a >= self_mask.shape[0] or b >= self_mask.shape[1] or c >= self_mask.shape[2]:
                continue
            #try:
            if searched[a,b,c] == 0 and ref_mask[a,b,c] == 1:
                search.append((a,b,c,v,d))
            #except Exception:
            #    pass
    def _infect(a,b,c,v,d):
        if d-1 == max_depth:
            return
        if searched[x,y,z] != 0:
            return
        if ref_mask[x,y,z] == 0:
            return
        #print(a,b,c)
        searched[a,b,c] = 1
        self_mask[a,b,c] = v
        _add_idx(a,b,c,v,d)

    from tqdm import tqdm
    for x,y,z in tqdm(zip(coords[0],coords[1],coords[2]),total=len(coords[0]),disable=not verbose,desc="Collecting Surface"):
        _add_idx(x,y,z,self_mask[x,y,z],0)
    while len(search) != 0:
        search2 = search
        search = deque()
        for _ in tqdm(range(len(search2)),disable=not verbose,desc="infect"):
            x,y,z,v,d = search2.popleft()
            _infect(x,y,z,v,d+1)
    self_mask[self_mask == 0] = self_mask_org[self_mask == 0]
    if _do_crop:
        if inplace:
            self[crop] = self_mask
            return self
        else:
            arr = self.get_array()
            arr[crop] = self_mask
            self_mask = arr
    return self.set_array(self_mask,inplace=inplace)

infect_

infect_(reference_mask: NII, verbose=True, axis: int | str | None = None, _do_crop=True) -> Self

In-place variant of infect.

Source code in TPTBox/core/nii_wrapper.py
def infect_(self: NII, reference_mask: NII, verbose=True, axis: int | str | None = None,_do_crop=True) -> Self:
    """In-place variant of `infect`."""
    return self.infect(reference_mask, inplace=True,verbose=verbose,axis=axis,_do_crop=_do_crop)

map_labels

map_labels(label_map: LABEL_MAP, verbose: logging = True, inplace=False) -> Self

Maps labels in the given NIfTI image according to the label_map dictionary.

Parameters:

Name Type Description Default
label_map dict

A dictionary that maps the original label values (str or int) to the new label values (int). For example, {"T1": 1, 2: 3, 4: 5} will map the original labels "T1", 2, and 4 to the new labels 1, 3, and 5, respectively.

required
verbose bool

Whether to print the label mapping and the number of labels reassigned. Default is True.

True
inplace bool

Whether to modify the current NIfTI image object in place or create a new object with the mapped labels. Default is False.

False

Returns:

Type Description
Self

If inplace is True, returns the current NIfTI image object with mapped labels. Otherwise, returns a new NIfTI image object with mapped labels.

Source code in TPTBox/core/nii_wrapper.py
def map_labels(self, label_map:LABEL_MAP , verbose:logging=True, inplace=False) -> Self:
    """Maps labels in the given NIfTI image according to the label_map dictionary.

    Args:
        label_map (dict): A dictionary that maps the original label values (str or int) to the new label values (int).
            For example, `{"T1": 1, 2: 3, 4: 5}` will map the original labels "T1", 2, and 4 to the new labels 1, 3, and 5, respectively.
        verbose (bool): Whether to print the label mapping and the number of labels reassigned. Default is True.
        inplace (bool): Whether to modify the current NIfTI image object in place or create a new object with the mapped labels.
            Default is False.

    Returns:
        If inplace is True, returns the current NIfTI image object with mapped labels. Otherwise, returns a new NIfTI image object with mapped labels.
    """
    data_orig = self.get_seg_array()
    labels_before = [v for v in np_unique(data_orig) if v > 0]
    # enforce keys to be str to support both str and int
    label_map_ = {
        (v_name2idx[k] if k in v_name2idx else int(k)): (
            v_name2idx[v] if v in v_name2idx else (0 if v is None else int(v))
        )
        for k, v in label_map.items()
    }
    log.print("label_map_ =", label_map_, verbose=verbose)
    data = np_map_labels(data_orig, label_map_)
    labels_after = [v for v in np_unique(data) if v > 0]
    log.print(
            "N =",
            len(label_map_),
            "labels reassigned, before labels: ",
            labels_before,
            " after: ",
            labels_after,verbose=verbose
        )
    nii = data.astype(np.uint16), self.affine, self.header
    if inplace:
        self.nii = nii
        return self
    return self.copy(nii)

map_labels_

map_labels_(label_map: LABEL_MAP, verbose: logging = True) -> Self

In-place variant of map_labels.

Source code in TPTBox/core/nii_wrapper.py
def map_labels_(self, label_map: LABEL_MAP, verbose: logging = True) -> Self:
    """In-place variant of `map_labels`."""
    return self.map_labels(label_map,verbose=verbose,inplace=True)

copy

copy(nib: Nifti1Image | _unpacked_nii | None = None, seg=None) -> NII

Returns a deep copy of this NII, optionally with a replacement image.

Parameters:

Name Type Description Default
nib Nifti1Image | _unpacked_nii | None

If provided, the copy will use this image data instead of copying the current array. Accepts a Nifti1Image or an (array, affine, header) tuple. Defaults to None (copy current data).

None
seg

Override the seg flag in the returned copy. Defaults to None (keep the current value).

None

Returns:

Type Description
NII

A new NII with the same c_val and info as this instance.

Source code in TPTBox/core/nii_wrapper.py
def copy(self, nib: Nifti1Image | _unpacked_nii | None = None, seg=None) -> NII:
    """Returns a deep copy of this NII, optionally with a replacement image.

    Args:
        nib: If provided, the copy will use this image data instead of copying
            the current array. Accepts a ``Nifti1Image`` or an
            ``(array, affine, header)`` tuple. Defaults to None (copy current data).
        seg: Override the ``seg`` flag in the returned copy. Defaults to None
            (keep the current value).

    Returns:
        A new NII with the same ``c_val`` and ``info`` as this instance.
    """
    if nib is None:
        nib = (self.get_array().copy(), self.affine.copy(), self.header.copy())
    return NII(nib,seg=self.seg if seg is None else seg,c_val = self.c_val,info = self.info)

flip

flip(axis: int | str, keep_global_coords=True, inplace=False) -> Self

Flips the image along a spatial axis.

Parameters:

Name Type Description Default
axis int | str

The axis to flip, specified as an integer index or an anatomical direction string (e.g. "S", "R").

required
keep_global_coords

If True, the flip is implemented via a reorientation so that world-space coordinates are preserved. If False, the array is flipped in-place without adjusting the affine. Defaults to True.

True
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

The flipped NII.

Source code in TPTBox/core/nii_wrapper.py
def flip(self, axis: int | str, keep_global_coords=True, inplace=False) -> Self:
    """Flips the image along a spatial axis.

    Args:
        axis: The axis to flip, specified as an integer index or an anatomical
            direction string (e.g. ``"S"``, ``"R"``).
        keep_global_coords: If True, the flip is implemented via a reorientation
            so that world-space coordinates are preserved. If False, the array is
            flipped in-place without adjusting the affine. Defaults to True.
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        The flipped NII.
    """
    axis = self.get_axis(axis) if not isinstance(axis,int) else axis
    if keep_global_coords:
        orient = list(self.orientation)
        orient[axis] = _same_direction[orient[axis]]
        return self.reorient(tuple(orient),inplace=inplace)
    else:
        return self.set_array(np.flip(self.get_array(),axis),inplace=inplace)

clone

clone() -> NII

Returns a deep copy of this NII (alias for copy()).

Source code in TPTBox/core/nii_wrapper.py
def clone(self) -> NII:
    """Returns a deep copy of this NII (alias for ``copy()``)."""
    return self.copy()

save

save(file: str | Path, make_parents=True, verbose: logging = True, dtype=None) -> None

Saves this NII to a NIfTI file on disk.

Parameters:

Name Type Description Default
file str | Path

Destination file path (e.g. "/path/to/image.nii.gz").

required
make_parents

If True, parent directories are created automatically. Defaults to True.

True
verbose logging

If True (or a non-zero int), logs the save path and dtype. Defaults to True.

True
dtype

Override the on-disk dtype. Defaults to None (use the array dtype).

None
Source code in TPTBox/core/nii_wrapper.py
@secure_save
def save(self, file: str | Path, make_parents=True, verbose: logging = True, dtype=None) -> None:
    """Saves this NII to a NIfTI file on disk.

    Args:
        file: Destination file path (e.g. ``"/path/to/image.nii.gz"``).
        make_parents: If True, parent directories are created automatically.
            Defaults to True.
        verbose: If True (or a non-zero int), logs the save path and dtype.
            Defaults to True.
        dtype: Override the on-disk dtype. Defaults to None (use the array dtype).
    """
    if make_parents:
        Path(file).parent.mkdir(0o777,exist_ok=True,parents=True)
    if str(file).endswith(".nrrd"):
        return self.save_nrrd(file,verbose=verbose)

    arr = self.get_array() if not self.seg else self.get_seg_array()
    if isinstance(arr,np.floating) and self.seg:
        self.set_dtype_("smallest_uint")
        arr = self.get_array() if not self.seg else self.get_seg_array()

    self.header.set_data_dtype(arr.dtype)
    out = Nifti1Image(arr, self.affine,self.header)#,dtype=arr.dtype)
    if dtype is not None:
        out.set_data_dtype(dtype)
    if out.header["qform_code"] == 0: #NIFTI_XFORM_UNKNOWN Will cause an error for some rounding of the affine in ITKSnap ...
        # 1 means Scanner coordinate system
        # 2 means align (to something) coordinate system
        out.header["qform_code"] = 2 if self.seg else 1
    nib.save(out, file) #type: ignore
    log.print(f"Save {file} as {out.get_data_dtype()}",verbose=verbose,ltype=Log_Type.SAVE)

save_nrrd

save_nrrd(file: str | Path | BIDS_FILE, make_parents=True, verbose: logging = True, **args) -> None

Save an NII object to an NRRD file.

Parameters:

Name Type Description Default
nii_obj NII

The NII object to be saved.

required
path str | Path

The file path where the NRRD file will be saved.

required

Raises:

Type Description
ImportError

If the pynrrd package is not installed.

ValueError

If the affine matrix is invalid or incompatible.

Source code in TPTBox/core/nii_wrapper.py
@secure_save
def save_nrrd(self:Self, file: str | Path|bids_files.BIDS_FILE,make_parents=True,verbose:logging=True,**args) -> None:
    """Save an NII object to an NRRD file.

    Args:
        nii_obj (NII): The NII object to be saved.
        path (str | Path): The file path where the NRRD file will be saved.

    Raises:
        ImportError: If the `pynrrd` package is not installed.
        ValueError: If the affine matrix is invalid or incompatible.
    """
    try:
        import nrrd
    except ModuleNotFoundError:
        raise ImportError("The `pynrrd` package is required but not installed. Install it with `pip install pynrrd`." ) from None
    if isinstance(file, bids_files.BIDS_FILE):
        file = file.file['nrrd']
    from TPTBox.core.internal.slicer_nrrd import save_slicer_nrrd
    save_slicer_nrrd(self,file,make_parents=make_parents,verbose=verbose,**args)

to_stls

to_stls(out_path: Path | dict[int, Path] | None = None, bb: tuple | None = None, to_world: bool = True, include_normals: bool = False, number_path: bool | None = None) -> dict[int, Mesh]

Convert all labels in a segmentation into STL meshes.

This function iterates over all unique labels in the segmentation and applies to_stl_single to each label independently.

Parameters:

Name Type Description Default
seg NII

Segmentation object containing one or more labels.

required
out_path Path | dict[int, Path] | None

Output specification: - Path → save all meshes into the same directory or file pattern - dict[label, Path] → per-label output paths - None → do not save meshes

None
bb tuple | None

Optional bounding box (e.g., slices). If provided and to_world=False, vertex coordinates are shifted by the bounding box start indices.

None
to_world bool

If True, transform vertices from voxel coordinates into world coordinates using seg.affine. Defaults to True.

True
include_normals bool

If True, compute per-face normals for each mesh using mesh.Mesh.update_normals(). Defaults to False.

False
number_path bool | None

Controls filename numbering when saving: - If None (default): Automatically set to True if out_path is not a dict, and False otherwise. - If True: Append the label to the output filename. - If False: Do not modify the filename.

None

Returns:

Type Description
dict[int, Mesh]

dict[int, mesh.Mesh]: Dictionary mapping each label to its corresponding STL mesh.

Notes
  • Each label is processed independently via to_stl_single.
  • Padding is applied internally to ensure closed surfaces.
  • STL format stores only triangle geometry and per-face normals; it does not support per-vertex attributes such as scalar values.
  • If to_world=True, all meshes are returned in physical space (e.g., millimeters).
Source code in TPTBox/core/nii_wrapper.py
def to_stls(
    self: NII,
    out_path: Path | dict[int, Path] | None = None,
    bb: tuple | None = None,
    to_world: bool = True,
    include_normals: bool = False,
    number_path: bool | None = None,
) -> dict[int, Mesh]:
    """Convert all labels in a segmentation into STL meshes.

    This function iterates over all unique labels in the segmentation and
    applies `to_stl_single` to each label independently.

    Args:
        seg (NII):
            Segmentation object containing one or more labels.
        out_path (Path | dict[int, Path] | None, optional):
            Output specification:
                - Path → save all meshes into the same directory or file pattern
                - dict[label, Path] → per-label output paths
                - None → do not save meshes
        bb (tuple | None, optional):
            Optional bounding box (e.g., slices). If provided and `to_world=False`,
            vertex coordinates are shifted by the bounding box start indices.
        to_world (bool, optional):
            If True, transform vertices from voxel coordinates into world
            coordinates using `seg.affine`. Defaults to True.
        include_normals (bool, optional):
            If True, compute per-face normals for each mesh using
            `mesh.Mesh.update_normals()`. Defaults to False.
        number_path (bool | None, optional):
            Controls filename numbering when saving:
                - If None (default):
                    Automatically set to True if `out_path` is not a dict,
                    and False otherwise.
                - If True:
                    Append the label to the output filename.
                - If False:
                    Do not modify the filename.

    Returns:
        dict[int, mesh.Mesh]:
            Dictionary mapping each label to its corresponding STL mesh.

    Notes:
        - Each label is processed independently via `to_stl_single`.
        - Padding is applied internally to ensure closed surfaces.
        - STL format stores only triangle geometry and per-face normals;
        it does not support per-vertex attributes such as scalar values.
        - If `to_world=True`, all meshes are returned in physical space
        (e.g., millimeters).
    """
    ret = {}

    # Resolve default numbering behavior
    if number_path is None:
        number_path = not isinstance(out_path, dict)

    for i in self.unique():
        ret[i] = self.to_stl(
            label=i, out_path=out_path, bb=bb, to_world=to_world, include_normals=include_normals, number_path=number_path
        )

    return ret

to_stl

to_stl(label: int | Enum | Sequence[int] | Sequence[Enum], out_path: Path | dict[int, Path] | None = None, bb: tuple | None = None, to_world: bool = True, include_normals: bool = False, number_path=False) -> Mesh

Convert a binary segmentation label into an STL surface mesh using marching cubes.

The function extracts a single label from a segmentation, runs marching cubes to generate a triangular surface mesh, and optionally transforms the vertices into world (physical) coordinates using the NIfTI affine.

Parameters:

Name Type Description Default
seg NII

Segmentation object containing a 3D mask.

required
label int

Label value to extract from the segmentation. Defaults to 1.

required
out_path Path | dict[int, Path] | None

Output specification: - Path → save mesh to this file - dict[label, Path] → per-label output path - None → do not save mesh

None
bb tuple | None

Optional bounding box (e.g., slices). If provided and to_world=False, vertex coordinates are shifted by the bounding box start indices.

None
to_world bool

If True, transform vertices from voxel coordinates into world coordinates using seg.affine. Defaults to True.

True
include_normals bool

If True, compute and include per-face normals in the returned mesh using mesh.Mesh.update_normals(). Note that STL supports only one normal per face. Defaults to False.

False
number_path bool

If True, append the label to the output filename when saving. Defaults to False.

False

Returns:

Type Description
Mesh

mesh.Mesh: The generated STL mesh. If include_normals=True, normals are stored in mesh.normals (per face).

Notes
  • Marching cubes is applied to a padded volume to ensure closed surfaces at the segmentation boundaries.
  • Vertex coordinates are initially in voxel space and shifted to account for padding.
  • If to_world=True, vertices are transformed to physical space (e.g. mm) using the affine matrix of the input segmentation.
  • STL format stores only triangle geometry and per-face normals; it does not support per-vertex attributes such as scalar values from marching cubes.
Source code in TPTBox/core/nii_wrapper.py
def to_stl(
    self: NII,
    label: int|Enum|Sequence[int]|Sequence[Enum],
    out_path: Path | dict[int, Path] | None = None,
    bb: tuple | None = None,
    to_world: bool = True,
    include_normals: bool = False,
    number_path=False,
) -> Mesh:
    """Convert a binary segmentation label into an STL surface mesh using marching cubes.

    The function extracts a single label from a segmentation, runs marching cubes
    to generate a triangular surface mesh, and optionally transforms the vertices
    into world (physical) coordinates using the NIfTI affine.

    Args:
        seg (NII):
            Segmentation object containing a 3D mask.
        label (int, optional):
            Label value to extract from the segmentation. Defaults to 1.
        out_path (Path | dict[int, Path] | None, optional):
            Output specification:
                - Path → save mesh to this file
                - dict[label, Path] → per-label output path
                - None → do not save mesh
        bb (tuple | None, optional):
            Optional bounding box (e.g., slices). If provided and `to_world=False`,
            vertex coordinates are shifted by the bounding box start indices.
        to_world (bool, optional):
            If True, transform vertices from voxel coordinates into world
            coordinates using `seg.affine`. Defaults to True.
        include_normals (bool, optional):
            If True, compute and include per-face normals in the returned mesh
            using `mesh.Mesh.update_normals()`. Note that STL supports only
            one normal per face. Defaults to False.
        number_path (bool, optional):
            If True, append the label to the output filename when saving.
            Defaults to False.

    Returns:
        mesh.Mesh:
            The generated STL mesh. If `include_normals=True`, normals are stored
            in `mesh.normals` (per face).

    Notes:
        - Marching cubes is applied to a padded volume to ensure closed surfaces
        at the segmentation boundaries.
        - Vertex coordinates are initially in voxel space and shifted to account
        for padding.
        - If `to_world=True`, vertices are transformed to physical space (e.g. mm)
        using the affine matrix of the input segmentation.
        - STL format stores only triangle geometry and per-face normals; it does
        not support per-vertex attributes such as scalar values from marching cubes.
    """
    from stl import mesh
    seg = self.extract_label(label)
    # Prepare binary mask
    seg_arr = np.pad(seg.clamp(0, 1).get_array(), 1)
    # Marching cubes (voxel coordinates)
    try:
        verts, faces, normals, values = marching_cubes(seg_arr, gradient_direction="ascent", step_size=1)
    except RuntimeError as e:
        raise RuntimeError(str(e),f"{label=}, {self.unique()}, {out_path=}") from None
    # Remove padding offset (since we padded by 1 voxel)
    verts -= 1
    # Apply bounding box offset (still voxel space)
    if bb is not None and not to_world:
        verts += np.array([b.start for b in bb])
    # Convert to world coordinates using affine
    if to_world:
        affine = self.affine  # (4, 4)
        verts_h = np.c_[verts, np.ones(len(verts))]  # homogeneous coords
        verts = (affine @ verts_h.T).T[:, :3]

    # Build STL mesh
    cube: mesh.Mesh = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
    for i, f in enumerate(faces):
        cube.vectors[i] = verts[f]

    # Save if requested
    if out_path is not None:
        out_path = out_path.get(label) if isinstance(out_path, dict) else out_path

        if out_path is not None:
            out_path = Path(out_path)
            if out_path.is_dir():
                out_path = out_path / f"mask_{label}.stl"
            elif number_path:
                out_path.with_name(f"{out_path.stem}_{label}.stl")
            log.on_save(f"Saving STL to {out_path}")
            out_path.parent.mkdir(exist_ok=True)
            cube.save(str(out_path))

    if include_normals:
        cube.update_normals()

    return cube

suppress_dtype_change_printout_in_set_array classmethod

suppress_dtype_change_printout_in_set_array(value=True) -> None

Globally suppresses the log message emitted when set_array changes the dtype.

Parameters:

Name Type Description Default
value

Set to True to suppress the message, False to re-enable it. Defaults to True.

True
Source code in TPTBox/core/nii_wrapper.py
@classmethod
def suppress_dtype_change_printout_in_set_array(cls, value=True) -> None:
    """Globally suppresses the log message emitted when ``set_array`` changes the dtype.

    Args:
        value: Set to True to suppress the message, False to re-enable it.
            Defaults to True.
    """
    global suppress_dtype_change_printout_in_set_array  # noqa: PLW0603
    suppress_dtype_change_printout_in_set_array = value

is_intersecting_vertical

is_intersecting_vertical(b: Self, min_overlap=40) -> bool

Tests whether this image and b overlap vertically in global (world) space.

Uses the z-axis extent of both images' affines. Assumes the same rotation.

Parameters:

Name Type Description Default
b Self

The other NII to test intersection against.

required
min_overlap

Minimum number of mm that must overlap. Defaults to 40.

40

Returns:

Type Description
bool

True if the two images overlap by at least min_overlap mm along z.

Note

This method is untested; prefer get_intersecting_volume for reliable results.

Source code in TPTBox/core/nii_wrapper.py
def is_intersecting_vertical(self, b: Self, min_overlap=40) -> bool:
    """Tests whether this image and ``b`` overlap vertically in global (world) space.

    Uses the z-axis extent of both images' affines. Assumes the same rotation.

    Args:
        b: The other NII to test intersection against.
        min_overlap: Minimum number of mm that must overlap. Defaults to 40.

    Returns:
        True if the two images overlap by at least ``min_overlap`` mm along z.

    Note:
        This method is untested; prefer ``get_intersecting_volume`` for reliable results.
    """
    #warnings.warn('is_intersecting is untested use get_intersecting_volume instead')
    x1 = self.affine.dot([0, 0, 0, 1])[:3] # type: ignore
    x2 = self.affine.dot((*self.shape, 1))[:3]# type: ignore
    y1 = b.affine.dot([0, 0, 0, 1])[:3]# type: ignore
    y2 = b.affine.dot((*b.shape, 1))[:3]# type: ignore
    max_v = max(x1[2],x2[2])- min_overlap
    min_v = min(x1[2],x2[2])+ min_overlap
    if min_v < y1[2] < max_v:
        return True
    if min_v < y2[2] < max_v:
        return True

    max_v = max(y1[2],y2[2])- min_overlap
    min_v = min(y1[2],y2[2])+ min_overlap
    if min_v < x1[2] < max_v:
        return True
    return min_v < x2[2] < max_v

get_intersecting_volume

get_intersecting_volume(b: Self) -> float

Returns the number of voxels in self's grid that overlap with image b.

b is binarised (all non-zero → 1) and resampled into self's voxel grid using constant-mode (zero fill) before summing the overlap.

Parameters:

Name Type Description Default
b Self

The other image whose spatial extent is tested for overlap.

required

Returns:

Type Description
float

The count of overlapping voxels as a float.

Source code in TPTBox/core/nii_wrapper.py
def get_intersecting_volume(self, b: Self) -> float:
    """Returns the number of voxels in ``self``'s grid that overlap with image ``b``.

    ``b`` is binarised (all non-zero → 1) and resampled into ``self``'s voxel
    grid using constant-mode (zero fill) before summing the overlap.

    Args:
        b: The other image whose spatial extent is tested for overlap.

    Returns:
        The count of overlapping voxels as a float.
    """
    b = to_nii(b).copy() # type: ignore
    b.nii = Nifti1Image(b.get_array()*0+1,affine=b.affine)
    b.seg = True
    b.set_dtype_(np.uint8)
    b.c_val = 0
    b = b.resample_from_to(self,c_val=0,verbose=False,mode="constant") # type: ignore
    return b.get_array().sum()

extract_background

extract_background(inplace=False) -> Self

Returns a binary mask where all background (0) voxels are set to 1.

Parameters:

Name Type Description Default
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

An NII with 1 where the original segmentation had 0, and 0 elsewhere.

Raises:

Type Description
AssertionError

If seg=False.

Source code in TPTBox/core/nii_wrapper.py
def extract_background(self, inplace=False) -> Self:
    """Returns a binary mask where all background (0) voxels are set to 1.

    Args:
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        An NII with 1 where the original segmentation had 0, and 0 elsewhere.

    Raises:
        AssertionError: If ``seg=False``.
    """
    assert self.seg, "extracting the background only makes sense for a segmentation mask"
    arr_bg = self.get_seg_array()
    arr_bg = np_extract_label(arr_bg, label=0, to_label=1)
    return self.set_array(arr_bg, inplace, False)

extract_label

extract_label(label: int | Enum | Sequence[int] | Sequence[Enum] | None, keep_label=False, inplace=False) -> Self

If this NII is a segmentation you can single out one label with [0,1].

Source code in TPTBox/core/nii_wrapper.py
def extract_label(self,label:int|Enum|Sequence[int]|Sequence[Enum]|None, keep_label=False,inplace=False) -> Self:
    """If this NII is a segmentation you can single out one label with [0,1]."""
    assert self.seg, "extracting a label only makes sense for a segmentation mask"
    if label is None:
        if keep_label:
            return self.copy() if inplace else self
        else:
            return self.clamp(0,1,inplace=inplace)
    seg_arr = self.get_seg_array()

    if isinstance(label, Sequence):
        label_int:list[int] = [idx.value if isinstance(idx,Enum) else idx for idx in label]
        assert 0 not in label_int, 'Zero label does not make sense. This is the background'
        seg_arr = np_extract_label(seg_arr, label_int, to_label=1, inplace=True)
    else:
        if isinstance(label,Enum):
            label = label.value
        if isinstance(label,str):
            label = int(label)

        assert label != 0, 'Zero label does not make sense. This is the background'
        seg_arr = np_extract_label(seg_arr, label, to_label=1, inplace=True)
    if keep_label:
        seg_arr = seg_arr * self.get_seg_array()
    return self.set_array(seg_arr,inplace=inplace)

extract_label_

extract_label_(label: int | Enum | Sequence[int] | Sequence[Enum], keep_label=False) -> Self

In-place variant of extract_label.

Source code in TPTBox/core/nii_wrapper.py
def extract_label_(self, label: int | Enum | Sequence[int] | Sequence[Enum], keep_label=False) -> Self:
    """In-place variant of `extract_label`."""
    return self.extract_label(label,keep_label,inplace=True)

remove_labels

remove_labels(label: int | Enum | Sequence[int] | Sequence[Enum], inplace=False, verbose: logging = True, removed_to_label=0) -> Self

If this NII is a segmentation you can single out one label.

Source code in TPTBox/core/nii_wrapper.py
def remove_labels(self,label:int|Enum|Sequence[int]|Sequence[Enum], inplace=False, verbose:logging=True, removed_to_label=0) -> Self:
    """If this NII is a segmentation you can single out one label."""
    assert label != 0, 'Zero label does not make sens.  This is the background'
    seg_arr = self.get_seg_array()
    if not isinstance(label,Sequence):
        label = [label] # type: ignore
    for l in label:
        if isinstance(l, list):
            for g in l:
                seg_arr[seg_arr == g] = removed_to_label
        else:
            seg_arr[seg_arr == l] = removed_to_label
    return self.set_array(seg_arr,inplace=inplace, verbose=verbose)

remove_labels_

remove_labels_(label: int | Enum | Sequence[int] | Sequence[Enum], removed_to_label=0, verbose: logging = True) -> Self

In-place variant of remove_labels.

Source code in TPTBox/core/nii_wrapper.py
def remove_labels_(self, label: int | Enum | Sequence[int] | Sequence[Enum], removed_to_label=0, verbose: logging = True) -> Self:
    """In-place variant of `remove_labels`."""
    return self.remove_labels(label,inplace=True,removed_to_label=removed_to_label,verbose=verbose)

apply_mask

apply_mask(mask: Self, inplace=False) -> Self

Zeros out all voxels in this image that are background (0) in mask.

Parameters:

Name Type Description Default
mask Self

A segmentation NII used as the mask. Any non-zero voxel in the mask is treated as foreground (1). Must have the same shape as this image.

required
inplace

If True, modifies this NII in place. Defaults to False.

False

Returns:

Type Description
Self

The masked NII.

Raises:

Type Description
AssertionError

If shapes do not match.

Source code in TPTBox/core/nii_wrapper.py
def apply_mask(self, mask: Self, inplace=False) -> Self:
    """Zeros out all voxels in this image that are background (0) in ``mask``.

    Args:
        mask: A segmentation NII used as the mask. Any non-zero voxel in the
            mask is treated as foreground (1). Must have the same shape as
            this image.
        inplace: If True, modifies this NII in place. Defaults to False.

    Returns:
        The masked NII.

    Raises:
        AssertionError: If shapes do not match.
    """
    assert mask.shape == self.shape, f"[def apply_mask] Mask and Shape are not equal: \nMask - {mask},\nSelf - {self})"
    seg_arr = mask.get_seg_array()
    seg_arr[seg_arr != 0] = 1
    arr = self.get_array()
    return self.set_array(arr*seg_arr,inplace=inplace)

unique

unique(verbose: logging = False, crop=False) -> list[int]

Returns all integer labels WITHOUT 0. Must be performed only on a segmentation nii.

Source code in TPTBox/core/nii_wrapper.py
def unique(self,verbose:logging=False,crop=False) -> list[int]:
    """Returns all integer labels WITHOUT 0. Must be performed only on a segmentation nii."""
    arr = self.get_seg_array()
    if crop:
        try:
            arr = arr[np_bbox_binary(arr)]
        except Exception:
            pass
    out = np_unique_withoutzero(arr)
    log.print(out,verbose=verbose)
    return out

voxel_volume

voxel_volume() -> float

Returns the volume of a single voxel in mm³ (product of all zoom values).

Source code in TPTBox/core/nii_wrapper.py
def voxel_volume(self) -> float:
    """Returns the volume of a single voxel in mm³ (product of all zoom values)."""
    product = math.prod(self.spacing)
    return product

volumes

volumes(include_zero: bool = False, in_mm3=False, sort=False) -> dict[int, float] | dict[int, int]

Returns a dict stating how many pixels are present for each label.

Source code in TPTBox/core/nii_wrapper.py
def volumes(self, include_zero: bool = False, in_mm3=False,sort=False) -> dict[int, float]|dict[int, int]:
    """Returns a dict stating how many pixels are present for each label."""
    dic =  np_volume(self.get_seg_array(), include_zero=include_zero)
    if sort:
        dic = dict(sorted(dic.items()))
    if in_mm3:
        voxel_size = self.voxel_volume()
        dic = {k:v*voxel_size for k,v in dic.items()}
    return dic

translate_arr

translate_arr(translation_vector: tuple[int, int, int] | dict[str, int] | dict[DIRECTIONS, int], inplace: bool = False, verbose: bool = True) -> Self

Translate the NIfTI image array by a given vector.

The vector can be a tuple of voxel offsets or a dict keyed by anatomical direction letters ('S', 'I', 'R', 'L', 'P', 'A').

Parameters:

Name Type Description Default
translation_vector tuple or dict

Vector to translate with. Can be a tuple of ints or a dict with keys from 'SIRLPA' and int values.

required
inplace bool

Whether to modify the array in place.

False
verbose bool

Whether to print log messages.

True

Returns:

Name Type Description
NII Self

Translated image.

Source code in TPTBox/core/nii_wrapper.py
def translate_arr(
    self,
    translation_vector: tuple[int, int, int] | dict[str,int]| dict[DIRECTIONS,int],
    inplace: bool = False,
    verbose: bool = True
) -> Self:
    """Translate the NIfTI image array by a given vector.

    The vector can be a tuple of voxel offsets or a dict keyed by anatomical
    direction letters (``'S'``, ``'I'``, ``'R'``, ``'L'``, ``'P'``, ``'A'``).

    Args:
        translation_vector (tuple or dict): Vector to translate with. Can be a tuple of ints
                                            or a dict with keys from 'SIRLPA' and int values.
        inplace (bool): Whether to modify the array in place.
        verbose (bool): Whether to print log messages.

    Returns:
        NII: Translated image.
    """
    log.print("Translating array", end="\r", verbose=verbose)
    arr = self.get_array()

    if isinstance(translation_vector, dict):
        # Start with zero translation for all axes
        vector = [0] * arr.ndim
        for direction, amount in translation_vector.items():
            axis = self.get_axis(direction=direction) # type: ignore
            sign = +1 if direction in self.orientation else -1
            vector[axis] += sign * amount
        v: tuple[int, int, int] = tuple(vector) # type: ignore
    else:
        v = translation_vector
    arr_translated = np_translate_arr(arr, v)
    log.print(f"Translated by {v}; ", verbose=verbose)
    return self.set_array(arr_translated, inplace=inplace)

center_of_masses

center_of_masses() -> dict[int, COORDINATE]

Returns a dict stating the center of mass for each present label (not including zero!).

Source code in TPTBox/core/nii_wrapper.py
def center_of_masses(self) -> dict[int, COORDINATE]:
    """Returns a dict stating the center of mass for each present label (not including zero!)."""
    return np_center_of_mass(self.get_seg_array())