Skip to content

Grains Modules

Find grains in an image.

Grains

Find grains in an image.

Parameters:

Name Type Description Default
topostats_object TopoStats

TopoStats object with a minimum of image, filename and pixel_to_nm_scaling attributes defined.

required
grain_crop_padding int

Padding to add to the bounding box of the grain during cropping.

1
unet_config dict[str, str | int | float | tuple[int | None, int, int, int] | None]

Configuration for the UNet model. model_path: str Path to the UNet model. upper_norm_bound: float Upper bound for normalising the image. lower_norm_bound: float Lower bound for normalising the image.

None
threshold_method str

Method for determining thershold to mask values, default is 'otsu'.

None
otsu_threshold_multiplier float | None

Factor by which the below threshold is to be scaled prior to masking.

None
threshold_std_dev dict[str, float | list] | None

Dictionary of 'below' and 'above' factors by which standard deviation is multiplied to derive the threshold if threshold_method is 'std_dev'.

None
threshold_absolute dict[str, float | list] | None

Dictionary of absolute 'below' and 'above' thresholds for grain finding.

None
area_thresholds dict[str, list[float | None]]

Dictionary of above and below grain's area thresholds.

None
remove_edge_intersecting_grains bool

Whether or not to remove grains that intersect the edge of the image.

True
classes_to_merge list[tuple[int, int]] | None

List of tuples of classes to merge.

None
vetting dict | None

Dictionary of vetting parameters.

None
Source code in topostats\grains.py
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
class Grains:
    """
    Find grains in an image.

    Parameters
    ----------
    topostats_object : TopoStats
        TopoStats object with a minimum of ``image``, ``filename`` and ``pixel_to_nm_scaling`` attributes defined.
    grain_crop_padding : int
        Padding to add to the bounding box of the grain during cropping.
    unet_config : dict[str, str | int | float | tuple[int | None, int, int, int] | None]
        Configuration for the UNet model.
        model_path: str
            Path to the UNet model.
        upper_norm_bound: float
            Upper bound for normalising the image.
        lower_norm_bound: float
            Lower bound for normalising the image.
    threshold_method : str
        Method for determining thershold to mask values, default is 'otsu'.
    otsu_threshold_multiplier : float | None
        Factor by which the below threshold is to be scaled prior to masking.
    threshold_std_dev : dict[str, float | list] | None
        Dictionary of 'below' and 'above' factors by which standard deviation is multiplied to derive the threshold
        if threshold_method is 'std_dev'.
    threshold_absolute : dict[str, float | list] | None
        Dictionary of absolute 'below' and 'above' thresholds for grain finding.
    area_thresholds : dict[str, list[float | None]]
        Dictionary of above and below grain's area thresholds.
    remove_edge_intersecting_grains : bool
        Whether or not to remove grains that intersect the edge of the image.
    classes_to_merge : list[tuple[int, int]] | None
        List of tuples of classes to merge.
    vetting : dict | None
        Dictionary of vetting parameters.
    """

    # pylint: disable=too-many-locals
    def __init__(
        self,
        topostats_object: TopoStats,
        grain_crop_padding: int = 1,
        unet_config: dict[str, str | int | float | tuple[int | None, int, int, int] | None] | None = None,
        threshold_method: str | None = None,
        otsu_threshold_multiplier: float | None = None,
        threshold_std_dev: dict[str, float | list] | None = None,
        threshold_absolute: dict[str, float | list] | None = None,
        area_thresholds: dict[str, list[float | None]] | None = None,
        remove_edge_intersecting_grains: bool = True,
        classes_to_merge: list[list[int]] | None = None,
        vetting: dict | None = None,
    ):
        """
        Initialise the class.

        Parameters
        ----------
        topostats_object : TopoStats
            TopoStats object.
        grain_crop_padding : int
            Padding to add to the bounding box of grains during cropping.
        unet_config : dict[str, str | int | float | tuple[int | None, int, int, int] | None]
            Configuration for the UNet model which is a dictionary with the following keys and values.
            model_path : str
                Path to the UNet model.
            upper_norm_bound: float
                Upper bound for normalising the image.
            lower_norm_bound : float
                Lower bound for normalising the image.
        threshold_method : str
            Method for determining thershold to mask values, default is 'otsu'.
        otsu_threshold_multiplier : float | None
            Factor by which the below threshold is to be scaled prior to masking.
        threshold_std_dev : dict[str, float | list] | None
            Dictionary of 'below' and 'above' factors by which standard deviation is multiplied to derive the threshold
            if threshold_method is 'std_dev'.
        threshold_absolute : dict[str, float | list] | None
            Dictionary of absolute 'below' and 'above' thresholds for grain finding.
        area_thresholds : dict[str, list[float | None]]
            Dictionary of above and below grain's area thresholds.
        remove_edge_intersecting_grains : bool
            Direction for which grains are to be detected, valid values are 'above', 'below' and 'both'.
        classes_to_merge : list[tuple[int, int]] | None
            List of tuples of classes to merge.
        vetting : dict | None
            Dictionary of vetting parameters.
        """
        assert topostats_object.config is not None, AttributeError(
            f"[{topostats_object.filename}] : Missing 'config' "
            "attribute. If loading '.topostats' objects you may need to run the whole processing pipeline anew."
        )
        config = topostats_object.config["grains"]
        if unet_config is None:
            unet_config = {
                "model_path": None,
                "upper_norm_bound": 1.0,
                "lower_norm_bound": 0.0,
            }
        if area_thresholds is None:
            area_thresholds = {"above": [None, None], "below": [None, None]}
        self.topostats_object = topostats_object
        self.image = topostats_object.image
        self.filename = topostats_object.filename
        self.pixel_to_nm_scaling = topostats_object.pixel_to_nm_scaling
        self.threshold_method = config["threshold_method"] if threshold_method is None else threshold_method
        self.otsu_threshold_multiplier = (
            config["otsu_threshold_multiplier"] if otsu_threshold_multiplier is None else otsu_threshold_multiplier
        )

        # Ensure thresholds are lists (might not be from passing in CLI args)
        def _make_list(x: int | float | list[int | float]) -> list[int | float]:
            """
            Ensure item(s) are stored in a list.

            Parameters
            ----------
            x : int | float | list[int | float]
                Item to be converted to a list.

            Returns
            -------
            list[int | float]
                Item as a list.
            """
            if not isinstance(x, list):
                return [x]
            return x

        self.threshold_std_dev = config["threshold_std_dev"] if threshold_std_dev is None else threshold_std_dev
        self.threshold_std_dev["above"] = _make_list(self.threshold_std_dev["above"])
        self.threshold_std_dev["below"] = _make_list(self.threshold_std_dev["below"])
        self.threshold_absolute = config["threshold_absolute"] if threshold_absolute is None else threshold_absolute
        self.threshold_absolute["above"] = _make_list(self.threshold_absolute["above"])
        self.threshold_absolute["below"] = _make_list(self.threshold_absolute["below"])
        self.area_thresholds = config["area_thresholds"] if area_thresholds is None else area_thresholds
        self.area_thresholds["above"] = _make_list(self.area_thresholds["above"])
        self.area_thresholds["below"] = _make_list(self.area_thresholds["below"])
        self.remove_edge_intersecting_grains = (
            config["remove_edge_intersectin_grains"]
            if remove_edge_intersecting_grains is None
            else remove_edge_intersecting_grains
        )
        self.thresholds: dict[str, list[float]] | None = None
        self.mask_images: dict[str, dict[str, npt.NDArray]] = {}
        self.grain_crop_padding = grain_crop_padding
        self.unet_config = config["unet_config"] if unet_config is None else unet_config
        self.vetting_config = config["vetting"] if vetting is None else vetting
        self.classes_to_merge = config["classes_to_merge"] if classes_to_merge is None else classes_to_merge

        # Hardcoded minimum pixel size for grains. This should not be able to be changed by the user as this is
        # determined by what is processable by the rest of the pipeline.
        self.minimum_grain_size_px = 10
        self.minimum_bbox_size_px = 5

        self.grain_crops = {}

    @staticmethod
    def get_region_properties(image: npt.NDArray, **kwargs) -> list:
        """
        Extract the properties of each region.

        Parameters
        ----------
        image : np.array
            Numpy array representing image.
        **kwargs :
            Arguments passed to 'skimage.measure.regionprops(**kwargs)'.

        Returns
        -------
        list
            List of region property objects.
        """
        return regionprops(image, **kwargs)

    @staticmethod
    def tidy_border_tensor(grain_mask_tensor: npt.NDArray[np.bool_]) -> npt.NDArray[np.bool_]:
        """
        Remove whole grains touching the border.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the grain mask tensor with grains touching the border removed.
        """
        # flattened_grain_mask_tensor = Grains.flatten_multi_class_tensor(grain_mask_tensor)
        flattened_grain_mask_tensor = flatten_multi_class_tensor(grain_mask_tensor)
        # Find the grains that touch the border then remove them from the full mask tensor
        flattened_grain_mask_tensor_labelled = morphology.label(flattened_grain_mask_tensor)
        flattened_grain_mask_tensor_regionprops = regionprops(flattened_grain_mask_tensor_labelled)
        for region in flattened_grain_mask_tensor_regionprops:
            if (
                region.bbox[0] == 0
                or region.bbox[1] == 0
                or region.bbox[2] == flattened_grain_mask_tensor.shape[0]
                or region.bbox[3] == flattened_grain_mask_tensor.shape[1]
            ):
                # Remove the grain from the full mask tensor
                for class_index in range(1, grain_mask_tensor.shape[2]):
                    grain_mask_tensor[:, :, class_index][flattened_grain_mask_tensor_labelled == region.label] = 0

        # return Grains.update_background_class(grain_mask_tensor)
        return update_background_class(grain_mask_tensor)

    @staticmethod
    def label_regions(image: npt.NDArray, background: int = 0) -> npt.NDArray:
        """
        Label regions.

        This method is used twice, once prior to removal of small regions and again afterwards which is why an image
        must be supplied rather than using 'self'.

        Parameters
        ----------
        image : npt.NDArray
            2-D Numpy array of image.
        background : int
            Value used to indicate background of image. Default = 0.

        Returns
        -------
        npt.NDArray
            2-D Numpy array of image with regions numbered.
        """
        return morphology.label(image, background)

    def remove_objects_too_small_to_process(
        self, image: npt.NDArray, minimum_size_px: int, minimum_bbox_size_px: int
    ) -> npt.NDArray[np.bool_]:
        """
        Remove objects whose dimensions in pixels are too small to process.

        Parameters
        ----------
        image : npt.NDArray
            2-D Numpy array of image.
        minimum_size_px : int
            Minimum number of pixels for an object.
        minimum_bbox_size_px : int
            Limit for the minimum dimension of an object in pixels. Eg: 5 means the object's bounding box must be at
            least 5x5.

        Returns
        -------
        npt.NDArray
            2-D Numpy array of image with objects removed that are too small to process.
        """
        labelled_image = label(image)
        region_properties = self.get_region_properties(labelled_image)
        for region in region_properties:
            # If the number of true pixels in the region is less than the minimum number of pixels, remove the region
            if region.area < minimum_size_px:
                labelled_image[labelled_image == region.label] = 0
            bbox_width = region.bbox[2] - region.bbox[0]
            bbox_height = region.bbox[3] - region.bbox[1]
            # If the minimum dimension of the bounding box is less than the minimum dimension, remove the region
            if min(bbox_width, bbox_height) < minimum_bbox_size_px:
                labelled_image[labelled_image == region.label] = 0

        return labelled_image.astype(bool)

    @staticmethod
    def area_thresholding_tensor(
        grain_mask_tensor: npt.NDArray[np.bool_],
        area_thresholds: tuple[float | None, float | None],
        pixel_to_nm_scaling: float,
    ) -> npt.NDArray[np.bool_]:
        """
        Remove objects larger and smaller than the specified thresholds.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the full mask tensor.
        area_thresholds : tuple
            List of area thresholds (in nanometres squared), first is the lower limit for size, second is the upper.
        pixel_to_nm_scaling : float
            Scaling of pixels to nanometres.

        Returns
        -------
        npt.NDArray
            3-D Numpy array with small and large objects removed.
        """
        lower_size_limit, upper_size_limit = area_thresholds
        if upper_size_limit is None:
            upper_size_limit = grain_mask_tensor.size * pixel_to_nm_scaling**2
        if lower_size_limit is None:
            lower_size_limit = 0

        # Iterate over all classes except background
        for class_index in range(1, grain_mask_tensor.shape[2]):
            class_mask = grain_mask_tensor[:, :, class_index]
            class_mask_labelled = label(class_mask)
            class_mask_regionprops = regionprops(class_mask_labelled)
            for region in class_mask_regionprops:
                region_area = region.area * pixel_to_nm_scaling**2
                if region_area > upper_size_limit or region_area < lower_size_limit:
                    grain_mask_tensor[class_mask_labelled == region.label, class_index] = 0

        return Grains.update_background_class(grain_mask_tensor)

    @staticmethod
    def bbox_size_thresholding_tensor(
        grain_mask_tensor: npt.NDArray[np.bool_], bbox_size_thresholds: tuple[int | None, int | None]
    ) -> npt.NDArray[np.bool_]:
        """
        Remove objects whose bounding box is smaller than the specified threshold.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray[np.bool_]
            3-D Numpy array of the full mask tensor.
        bbox_size_thresholds : tuple[int | None, int | None]
            List of bounding box size thresholds (in pixels), first is the lower limit for size, second is the upper.

        Returns
        -------
        npt.NDArray
            3-D Numpy array with objects removed that are too small to process.
        """
        lower_size_limit, upper_size_limit = bbox_size_thresholds

        # Iterate over all classes except background
        for class_index in range(1, grain_mask_tensor.shape[2]):
            class_mask = grain_mask_tensor[:, :, class_index]
            class_mask_labelled = label(class_mask)
            class_mask_regionprops = regionprops(class_mask_labelled)
            for region in class_mask_regionprops:
                bbox_width = region.bbox[2] - region.bbox[0]
                bbox_height = region.bbox[3] - region.bbox[1]
                if lower_size_limit is not None:
                    if min(bbox_width, bbox_height) < lower_size_limit:
                        grain_mask_tensor[class_mask_labelled == region.label, class_index] = 0
                if upper_size_limit is not None:
                    if max(bbox_width, bbox_height) > upper_size_limit:
                        grain_mask_tensor[class_mask_labelled == region.label, class_index] = 0

        return Grains.update_background_class(grain_mask_tensor)

    # Sylvia: This function is more readable and easier to work on if we don't split it up into smaller functions.
    # pylint: disable=too-many-branches
    # pylint: disable=too-many-statements
    def find_grains(self) -> None:
        """Find grains."""
        LOGGER.debug(f"[{self.filename}] : Thresholding method (grains) : {self.threshold_method}")
        assert self.threshold_method is not None, "Threshold method must be specified"  # type safety
        # calculate thresholds based on configuration
        self.thresholds = get_thresholds(
            image=self.image,
            threshold_method=self.threshold_method,
            otsu_threshold_multiplier=self.otsu_threshold_multiplier,
            threshold_std_dev=self.threshold_std_dev,
            absolute=self.threshold_absolute,
        )

        for direction, direction_thresholds in self.thresholds.items():
            LOGGER.debug(f"[{self.filename}] : Finding {direction} grains, threshold: ({direction_thresholds})")
            self.mask_images[direction] = {}

            # iterate over the thresholds for the current direction
            traditional_full_mask_tensor = Grains.multi_class_thresholding(
                image=self.image,
                thresholds=direction_thresholds,
                threshold_direction=direction,
                image_name=self.filename,
            )

            self.mask_images[direction]["thresholded_grains"] = traditional_full_mask_tensor.copy()

            # pre-GrainCrop checks

            # Tidy border - done here and not in vetting to not make vetting dependent on image size argument.
            if self.remove_edge_intersecting_grains:
                traditional_full_mask_tensor = Grains.tidy_border_tensor(grain_mask_tensor=traditional_full_mask_tensor)
            self.mask_images[direction]["tidied_border"] = traditional_full_mask_tensor.copy()

            # Remove objects with area too small to process
            traditional_full_mask_tensor = Grains.area_thresholding_tensor(
                grain_mask_tensor=traditional_full_mask_tensor,
                area_thresholds=(self.minimum_grain_size_px * self.pixel_to_nm_scaling**2, None),
                pixel_to_nm_scaling=self.pixel_to_nm_scaling,
            )
            # Remove objects with bounding box too small to process
            traditional_full_mask_tensor = Grains.bbox_size_thresholding_tensor(
                grain_mask_tensor=traditional_full_mask_tensor,
                bbox_size_thresholds=(self.minimum_bbox_size_px, None),
            )
            self.mask_images[direction]["removed_objects_too_small_to_process"] = traditional_full_mask_tensor.copy()

            # Area threshold using user specified thresholds
            traditional_full_mask_tensor = Grains.area_thresholding_tensor(
                grain_mask_tensor=traditional_full_mask_tensor,
                area_thresholds=self.area_thresholds[direction],
                pixel_to_nm_scaling=self.pixel_to_nm_scaling,
            )

            self.mask_images[direction]["area_thresholded"] = traditional_full_mask_tensor.copy()

            # Extract GrainCrops from the full mask tensor
            traditional_graincrops = self.extract_grains_from_full_image_tensor(
                image=self.image,
                full_mask_tensor=traditional_full_mask_tensor,
                padding=self.grain_crop_padding,
                pixel_to_nm_scaling=self.pixel_to_nm_scaling,
                filename=self.filename,
            )

            # If there are no grains, then later steps will fail, so skip the stages if no grains are found.
            if len(traditional_graincrops) > 0:
                # Grains found

                # Create a tensor out of the grain mask of shape NxNx2, where the two classes are a binary background
                # mask and the second is a binary grain mask. This is because we want to support multiple classes, and
                # so we standardise so that the first layer is background mask, then feature mask 1, then feature mask
                # 2 etc.

                # Optionally run a user-supplied u-net model on the grains to improve the segmentation
                if self.unet_config["model_path"] is not None:
                    # Run unet segmentation on only the class 1 layer of the labelled_regions_02. Need to make this configurable
                    # later on along with all the other hardcoded class 1s.
                    graincrops = Grains.improve_grain_segmentation_unet(
                        filename=self.filename,
                        direction=direction,
                        unet_config=self.unet_config,
                        graincrops=traditional_graincrops,
                    )
                else:
                    # otherwise use the traditional graincrops
                    graincrops = traditional_graincrops
                # Construct full masks from the crops
                full_mask_tensor = Grains.construct_full_mask_from_graincrops(
                    graincrops=graincrops,
                    image_shape=self.image.shape,
                )

                # Set the unet tensor regardless of if the unet model was run, since the plotting expects it
                # can be changed when we do a plotting overhaul
                self.mask_images[direction]["unet"] = full_mask_tensor.copy()

                # Vet the grains
                if self.vetting_config is not None:
                    graincrops_vetted = Grains.vet_grains(
                        graincrops=graincrops,
                        **self.vetting_config,
                    )
                else:
                    graincrops_vetted = graincrops
                graincrops_vetted = Grains.graincrops_update_background_class(graincrops=graincrops_vetted)

                full_mask_tensor_vetted = Grains.construct_full_mask_from_graincrops(
                    graincrops=graincrops_vetted,
                    image_shape=self.image.shape,
                )
                self.mask_images[direction]["vetted"] = full_mask_tensor_vetted.copy()

                # Mandatory check to remove any objects in any classes that are too small to process
                graincrops_removed_too_small_to_process = Grains.graincrops_remove_objects_too_small_to_process(
                    graincrops=graincrops_vetted,
                    min_object_size=self.minimum_grain_size_px,
                    min_object_bbox_size=self.minimum_bbox_size_px,
                )
                graincrops_removed_too_small_to_process = Grains.graincrops_update_background_class(
                    graincrops=graincrops_removed_too_small_to_process
                )

                # Merge classes as specified by the user
                graincrops_merged_classes = Grains.graincrops_merge_classes(
                    graincrops=graincrops_removed_too_small_to_process,
                    classes_to_merge=self.classes_to_merge,
                )
                graincrops_merged_classes = Grains.graincrops_update_background_class(
                    graincrops=graincrops_merged_classes
                )

                full_mask_tensor_merged_classes = Grains.construct_full_mask_from_graincrops(
                    graincrops=graincrops_merged_classes,
                    image_shape=self.image.shape,
                )
                self.mask_images[direction]["merged_classes"] = full_mask_tensor_merged_classes.copy()
                self.grain_crops = graincrops_merged_classes
                self.topostats_object.grain_crops = graincrops_merged_classes
                self.topostats_object.full_mask_tensor = full_mask_tensor_merged_classes
            else:
                # No grains found
                self.grain_crops = None
                # self.topostats_object.grain_crops = self.grain_crops
                self.topostats_object.full_mask_tensor = None

    @staticmethod
    def multi_class_thresholding(
        image: npt.NDArray,
        thresholds: list[float],
        threshold_direction: str,
        image_name: str,
    ) -> npt.NDArray[np.bool_]:
        """
        Perform multi-class thresholding on an image to obtain a mask tensor.

        Parameters
        ----------
        image : npt.NDArray
            2-D Numpy array of image.
        thresholds : list[float]
            List of thresholds for each class.
        threshold_direction : str
            Direction for which the threshold is applied.
        image_name : str
            Name of the image being processed (used in logging).

        Returns
        -------
        npt.NDArray
            WxHxC Numpy array of the mask tensor.
        """
        traditional_full_mask_tensor = np.zeros(
            (image.shape[0], image.shape[1], len(thresholds) + 1), dtype=np.int32
        ).astype(bool)
        for threshold_index, direction_threshold in enumerate(thresholds):
            # mask the grains
            traditional_full_mask_tensor[:, :, threshold_index + 1] = _get_mask(
                image=image,
                thresh=direction_threshold,
                threshold_direction=threshold_direction,
                img_name=image_name,
            ).astype(bool)
        # Update background class in the full mask tensor
        return Grains.update_background_class(traditional_full_mask_tensor)

    # pylint: disable=too-many-locals
    @staticmethod
    def improve_grain_segmentation_unet(
        graincrops: dict[int, GrainCrop],
        filename: str,
        direction: str,
        unet_config: dict[str, str | int | float | tuple[int | None, int, int, int] | None],
    ) -> dict[int, GrainCrop]:
        """
        Use a UNet model to re-segment existing grains to improve their accuracy.

        Parameters
        ----------
        graincrops : dict[int, GrainCrop]
            Dictionary of grain crops.
        filename : str
            File being processed (used in logging).
        direction : str
            Direction of threshold for which bounding boxes are being calculated.
        unet_config : dict[str, str | int | float | tuple[int | None, int, int, int] | None]
            Configuration for the UNet model.
            model_path: str
                Path to the UNet model.
            grain_crop_padding: int
                Padding to add to the bounding box of the grain before cropping.
            upper_norm_bound: float
                Upper bound for normalising the image.
            lower_norm_bound: float
                Lower bound for normalising the image.
            confidence: float
                Confidence threshold for the UNet model. Smaller is more generous, larger is more strict.

        Returns
        -------
        dict[int, GrainCrop]
            Dictionary of (hopefully) improved grain crops.
        """
        LOGGER.debug(f"[{filename}] : Running UNet model on {direction} grains")

        # When debugging, you might find that the custom_objects are incorrect. This is entirely based on what the model used
        # for its loss during training and so this will need to be changed a lot.
        # Once the group has gotten used to training models, this can be made configurable, but currently it's too changeable.
        # unet_model = keras.models.load_model(
        #     self.unet_config["model_path"], custom_objects={"dice_loss": dice_loss, "iou_loss": iou_loss}
        # )
        # You may also get an error referencing a "group_1" parameter, this is discussed in this issue:
        # https://github.com/keras-team/keras/issues/19441 which also has an experimental fix that we can try but
        # I haven't tested it yet.

        try:
            unet_model = keras.models.load_model(
                unet_config["model_path"], custom_objects={"mean_iou": mean_iou, "iou_loss": iou_loss}, compile=False
            )
        except Exception as e:
            LOGGER.debug(f"Python executable: {sys.executable}")
            LOGGER.debug(f"Keras version: {keras.__version__}")
            LOGGER.debug(f"Model path: {unet_config['model_path']}")
            raise e

        # unet_model = keras.models.load_model(unet_config["model_path"], custom_objects={"mean_iou": mean_iou})
        LOGGER.debug(f"Output shape of UNet model: {unet_model.output_shape}")

        new_graincrops: dict[int, GrainCrop] = {}
        num_empty_removed_grains = 0
        for grain_number, graincrop in graincrops.items():
            LOGGER.debug(f"Unet predicting mask for grain {grain_number} of {len(graincrops)}")
            # Run the UNet on the region. This is allowed to be a single class
            # as we can add a background class afterwards if needed.
            # Remember that this region is cropped from the original image, so it's not
            # the same size as the original image.
            predicted_mask = predict_unet(
                image=graincrop.image,
                model=unet_model,
                confidence=unet_config["confidence"],
                model_input_shape=unet_model.input_shape,
                upper_norm_bound=unet_config["upper_norm_bound"],
                lower_norm_bound=unet_config["lower_norm_bound"],
            )
            assert len(predicted_mask.shape) == 3
            LOGGER.debug(f"Predicted mask shape: {predicted_mask.shape}")

            if unet_config["remove_disconnected_grains"]:
                # Remove grains that are not connected to the original grain
                original_grain_mask = graincrop.mask
                predicted_mask = Grains.remove_disconnected_grains(
                    original_grain_tensor=original_grain_mask,
                    predicted_grain_tensor=predicted_mask,
                )

            # Check if all of the non-background classes are empty
            if np.sum(predicted_mask[:, :, 1:]) == 0:
                num_empty_removed_grains += 1
            else:
                # @ns-rse 2025-10-14 - do we need to instantiate a new instance here? I don't think we do as
                #                      we have setter methods so could just update the .mask attribute in
                #                      place (could maybe set it above?)
                # graincrop.mask = predicted_mask
                new_graincrops[grain_number] = GrainCrop(
                    image=graincrop.image,
                    mask=predicted_mask,
                    padding=graincrop.padding,
                    bbox=graincrop.bbox,
                    pixel_to_nm_scaling=graincrop.pixel_to_nm_scaling,
                    filename=graincrop.filename,
                    height_profiles=graincrop.height_profiles,
                    stats=graincrop.stats,
                    disordered_trace=graincrop.disordered_trace,
                    nodes=graincrop.nodes,
                    ordered_trace=graincrop.ordered_trace,
                    threshold_method=graincrop.threshold_method,
                    thresholds=graincrop.thresholds,
                )

        LOGGER.debug(f"Number of empty removed grains: {num_empty_removed_grains}")

        return new_graincrops

    @staticmethod
    def keep_largest_labelled_region(
        labelled_image: npt.NDArray[np.int32],
    ) -> npt.NDArray[np.bool_]:
        """
        Keep only the largest region in a labelled image.

        Parameters
        ----------
        labelled_image : npt.NDArray
            2-D Numpy array of labelled regions.

        Returns
        -------
        npt.NDArray
            2-D Numpy boolean array of labelled regions with only the largest region.
        """
        # Check if there are any labelled regions
        if labelled_image.max() == 0:
            return np.zeros_like(labelled_image).astype(np.bool_)
        # Get the sizes of the regions
        sizes = np.array([(labelled_image == label).sum() for label in range(1, labelled_image.max() + 1)])
        # Keep only the largest region
        return np.where(labelled_image == sizes.argmax() + 1, labelled_image, 0).astype(bool)

    @staticmethod
    def flatten_multi_class_tensor(grain_mask_tensor: npt.NDArray) -> npt.NDArray:
        """
        Flatten a multi-class image tensor to a single binary mask.

        The returned tensor is of boolean type in case there are multiple hits in the same pixel. We dont want to have
        2s, 3s etc because this would cause issues in labelling and cause erroneous grains within grains.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            Multi class grain mask tensor tensor of shape (N, N, C).

        Returns
        -------
        npt.NDArray
            Combined binary mask of all but the background class (:, :, 0).
        """
        assert len(grain_mask_tensor.shape) == 3, f"Tensor not 3D: {grain_mask_tensor.shape}"
        return np.sum(grain_mask_tensor[:, :, 1:], axis=-1).astype(bool)

    @staticmethod
    def get_multi_class_grain_bounding_boxes(grain_mask_tensor: npt.NDArray) -> dict:
        """
        Get the bounding boxes for each grain in a multi-class image tensor.

        Finds the bounding boxes for each grain in a multi-class image tensor. Grains can span multiple classes, so the
        bounding boxes are found for the combined binary mask of contiguous grains across all classes.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of grain mask tensor.

        Returns
        -------
        dict
            Dictionary of bounding boxes indexed by grain number.
        """
        flattened_mask = Grains.flatten_multi_class_tensor(grain_mask_tensor)
        labelled_regions = Grains.label_regions(flattened_mask)
        region_properties = Grains.get_region_properties(labelled_regions)
        bounding_boxes = {index: region.bbox for index, region in enumerate(region_properties)}
        return {
            index: pad_bounding_box_cutting_off_at_image_bounds(
                crop_min_row=bbox[0],
                crop_min_col=bbox[1],
                crop_max_row=bbox[2],
                crop_max_col=bbox[3],
                image_shape=(grain_mask_tensor.shape[0], grain_mask_tensor.shape[1]),
                padding=1,
            )
            for index, bbox in bounding_boxes.items()
        }

    @staticmethod
    def update_background_class(
        grain_mask_tensor: npt.NDArray,
    ) -> npt.NDArray[np.bool_]:
        """
        Update the background class to reflect the other classes.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.

        Returns
        -------
        npt.NDArray
            3-D Numpy array of image tensor with updated background class.
        """
        flattened_mask = Grains.flatten_multi_class_tensor(grain_mask_tensor)
        new_background = np.where(flattened_mask == 0, 1, 0)
        grain_mask_tensor[:, :, 0] = new_background
        return grain_mask_tensor.astype(bool)

    @staticmethod
    def vet_class_sizes_single_grain(
        single_grain_mask_tensor: npt.NDArray,
        pixel_to_nm_scaling: float,
        class_size_thresholds: list[tuple[int, int, int]] | None,
    ) -> tuple[npt.NDArray, bool]:
        """
        Remove regions of particular classes based on size thresholds.

        Regions of classes that are too large or small may need to be removed for many reasons (eg removing noise
        erroneously detected by the model or larger-than-expected molecules that are obviously erroneous), this method
        allows for the removal of these regions based on size thresholds.

        Parameters
        ----------
        single_grain_mask_tensor : npt.NDArray
            3-D Numpy array of the mask tensor.
        pixel_to_nm_scaling : float
            Scaling of pixels to nanometres.
        class_size_thresholds : list[list[int, int, int]] | None
            List of class size thresholds. Structure is [(class_index, lower, upper)].

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the mask tensor with grains removed based on size thresholds.
        bool
            True if the grain passes the vetting, False if it fails.
        """
        if class_size_thresholds is None:
            return single_grain_mask_tensor, True

        # Iterate over the classes and check the sizes
        for class_index in range(1, single_grain_mask_tensor.shape[2]):
            class_size = np.sum(single_grain_mask_tensor[:, :, class_index]) * pixel_to_nm_scaling**2
            # Check the size against the thresholds

            classes_to_vet = [vetting_criteria[0] for vetting_criteria in class_size_thresholds]

            if class_index not in classes_to_vet:
                continue

            lower_threshold, upper_threshold = [
                vetting_criteria[1:] for vetting_criteria in class_size_thresholds if vetting_criteria[0] == class_index
            ][0]

            if lower_threshold is not None:
                if class_size < lower_threshold:
                    # Return empty tensor
                    empty_crop_tensor = np.zeros_like(single_grain_mask_tensor)
                    # Fill the background class with 1s
                    empty_crop_tensor[:, :, 0] = 1
                    return empty_crop_tensor, False
            if upper_threshold is not None:
                if class_size > upper_threshold:
                    # Return empty tensor
                    empty_crop_tensor = np.zeros_like(single_grain_mask_tensor)
                    # Fill the background class with 1s
                    empty_crop_tensor[:, :, 0] = 1
                    return empty_crop_tensor, False

        return single_grain_mask_tensor, True

    @staticmethod
    def get_individual_grain_crops(
        grain_mask_tensor: npt.NDArray,
        padding: int = 1,
    ) -> tuple[list[npt.NDArray], list[npt.NDArray], int]:
        """
        Get individual grain crops from an image tensor.

        Fetches individual grain crops from an image tensor, but zeros any non-connected grains
        in the crop region. This is to ensure that other grains do not affect further processing
        steps.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of image tensor.
        padding : int
            Padding to add to the bounding box of the grain before cropping. Default is 1.

        Returns
        -------
        list[npt.NDArray]
            List of individual grain crops.
        list[npt.NDArray]
            List of bounding boxes for each grain.
        int
            Padding used for the bounding boxes.
        """
        grain_crops = []
        bounding_boxes = []

        # Label the regions
        flattened_multi_class_mask = Grains.flatten_multi_class_tensor(grain_mask_tensor)
        labelled_regions = Grains.label_regions(flattened_multi_class_mask)

        # Iterate over the regions and return the crop, but zero any non-connected grains
        for region in Grains.get_region_properties(labelled_regions):
            binary_labelled_regions = labelled_regions == region.label

            # Zero any non-connected grains
            # For each class, set all pixels to zero that are not in the current region
            this_region_only_grain_tensor = np.copy(grain_mask_tensor)
            # Iterate over the non-background classes
            for class_index in range(1, grain_mask_tensor.shape[2]):
                # Set all pixels to zero that are not in the current region
                this_region_only_grain_tensor[:, :, class_index] = (
                    binary_labelled_regions * grain_mask_tensor[:, :, class_index]
                )

            # Update background class to reflect the removal of any non-connected grains
            this_region_only_grain_tensor = Grains.update_background_class(
                grain_mask_tensor=this_region_only_grain_tensor
            )

            # Get the bounding box
            bounding_box = region.bbox

            # Pad the bounding box
            bounding_box = pad_bounding_box_cutting_off_at_image_bounds(
                crop_min_row=bounding_box[0],
                crop_min_col=bounding_box[1],
                crop_max_row=bounding_box[2],
                crop_max_col=bounding_box[3],
                image_shape=(grain_mask_tensor.shape[0], grain_mask_tensor.shape[1]),
                padding=padding,
            )

            # Crop the grain
            grain_crop = this_region_only_grain_tensor[
                bounding_box[0] : bounding_box[2],
                bounding_box[1] : bounding_box[3],
                :,
            ]

            # Add the crop to the list
            grain_crops.append(grain_crop.astype(bool))
            bounding_boxes.append(bounding_box)

        return grain_crops, bounding_boxes, padding

    @staticmethod
    def vet_numbers_of_regions_single_grain(
        grain_mask_tensor: npt.NDArray,
        class_region_number_thresholds: list[tuple[int, int, int]] | None,
    ) -> tuple[npt.NDArray, bool]:
        """
        Check if the number of regions of different classes for a single grain is within thresholds.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor, should be of only one grain.
        class_region_number_thresholds : list[list[int, int, int]]
            List of class region number thresholds. Structure is [(class_index, lower, upper)].

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the grain mask tensor with grains removed based on region number thresholds.
        bool
            True if the grain passes the vetting, False if it fails.
        """
        if class_region_number_thresholds is None:
            return grain_mask_tensor, True

        # Iterate over the classes and check the number of regions
        for class_index in range(1, grain_mask_tensor.shape[2]):
            # Get the number of regions
            class_labelled_regions = Grains.label_regions(grain_mask_tensor[:, :, class_index])
            number_of_regions = np.unique(class_labelled_regions).shape[0] - 1
            # Check the number of regions against the thresholds, skip if no thresholds provided
            # Get the classes we are trying to vet (the first element of each tuple)
            classes_to_vet = [vetting_criteria[0] for vetting_criteria in class_region_number_thresholds]

            if class_index not in classes_to_vet:
                continue

            lower_threshold, upper_threshold = [
                vetting_criteria[1:]
                for vetting_criteria in class_region_number_thresholds
                if vetting_criteria[0] == class_index
            ][0]

            # Check the number of regions against the thresholds
            if lower_threshold is not None:
                if number_of_regions < lower_threshold:
                    # Return empty tensor
                    empty_crop_tensor = np.zeros_like(grain_mask_tensor)
                    # Fill the background class with 1s
                    empty_crop_tensor[:, :, 0] = 1
                    return empty_crop_tensor, False
            if upper_threshold is not None:
                if number_of_regions > upper_threshold:
                    # Return empty tensor
                    empty_crop_tensor = np.zeros_like(grain_mask_tensor)
                    # Fill the background class with 1s
                    empty_crop_tensor[:, :, 0] = 1
                    return empty_crop_tensor, False

        return grain_mask_tensor, True

    @staticmethod
    def convert_classes_to_nearby_classes(
        grain_mask_tensor: npt.NDArray,
        classes_to_convert: list[tuple[int, int]] | None,
        class_touching_threshold: int = 1,
    ) -> npt.NDArray:
        """
        Convert all but the largest regions of one class into another class provided the former touches the latter.

        Specifically, it takes a list of tuples of two integers (dubbed class A and class B). For each class A, class B
        pair, it will find the largest region of class A and flag it to be ignored. Then for each non-largest region of
        class A, it will check if it touches any class B region (within the ``class_touching_threshold`` distance). If it
        does, it will convert the region to class B.

        This is useful for situations where you want just one region of class A and the model has a habit of producing
        small regions of class A interspersed in the class B regions, which should be class B instead.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.
        classes_to_convert : list
            List of tuples of classes to convert. Structure is [(class_a, class_b)].
        class_touching_threshold : int
            Number of dilation passes to do to determine class A connectivity with class B.

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the grain mask tensor with classes converted.
        """
        # If no classes to convert, return the original tensor
        if not classes_to_convert:
            return grain_mask_tensor

        # Iterate over class pairs
        for class_a, class_b in classes_to_convert:
            # Get the binary mask for class A and class B
            class_a_mask = grain_mask_tensor[:, :, class_a]
            class_b_mask = grain_mask_tensor[:, :, class_b]

            # Skip if no regions of class A
            if np.max(class_a_mask) == 0:
                continue

            # Find the largest region of class A
            class_a_labelled_regions = Grains.label_regions(class_a_mask)
            class_a_region_properties = Grains.get_region_properties(class_a_labelled_regions)
            class_a_areas = [region.area for region in class_a_region_properties]
            largest_class_a_region = class_a_region_properties[np.argmax(class_a_areas)]

            # For all other regions, check if they touch the class B region
            for region in class_a_region_properties:
                if region.label == largest_class_a_region.label:
                    continue
                # Get only the pixels in the region
                region_mask = class_a_labelled_regions == region.label
                # Dilate the region
                dilated_region_mask = region_mask
                for _ in range(class_touching_threshold):
                    dilated_region_mask = dilation(dilated_region_mask)
                # Get the intersection with the class B mask
                intersection = dilated_region_mask & class_b_mask
                # If there is any intersection, turn the region into class B
                if np.any(intersection):
                    # Add to the class B mask
                    class_b_mask = np.where(region_mask, class_b, class_b_mask)
                    # Remove from the class A mask
                    class_a_mask = np.where(region_mask, 0, class_a_mask)

            # Update the tensor
            grain_mask_tensor[:, :, class_a] = class_a_mask
            grain_mask_tensor[:, :, class_b] = class_b_mask

        return grain_mask_tensor.astype(bool)

    @staticmethod
    def keep_largest_labelled_region_classes(
        single_grain_mask_tensor: npt.NDArray,
        keep_largest_labelled_regions_classes: list[int] | None,
    ) -> npt.NDArray:
        """
        Keep only the largest region in specific classes.

        Parameters
        ----------
        single_grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.
        keep_largest_labelled_regions_classes : list[int]
            List of classes to keep only the largest region.

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the grain mask tensor with only the largest regions in specific classes.
        """
        if keep_largest_labelled_regions_classes is None:
            return single_grain_mask_tensor

        # Iterate over the classes
        for class_index in keep_largest_labelled_regions_classes:
            # Get the binary mask for the class
            class_mask = single_grain_mask_tensor[:, :, class_index]

            # Skip if no regions
            if np.max(class_mask) == 0:
                continue

            # Label the regions
            labelled_regions = Grains.label_regions(class_mask)
            # Get the region properties
            region_properties = Grains.get_region_properties(labelled_regions)
            # Get the region areas
            region_areas = [region.area for region in region_properties]
            # Keep only the largest region
            largest_region = region_properties[np.argmax(region_areas)]
            class_mask_largest_only = np.where(labelled_regions == largest_region.label, labelled_regions, 0)
            # Update the tensor
            single_grain_mask_tensor[:, :, class_index] = class_mask_largest_only.astype(bool)

        # Update the background class
        return Grains.update_background_class(single_grain_mask_tensor)

    @staticmethod
    def calculate_region_connection_regions(
        grain_mask_tensor: npt.NDArray,
        classes: tuple[int, int],
    ) -> tuple[int, npt.NDArray, dict[int, npt.NDArray[int]]]:
        """
        Get a list of connection regions between two classes.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.
        classes : tuple[int, int]
            Tuple pair of classes to calculate the connection regions.

        Returns
        -------
        int
            Number of connection regions.
        npt.NDArray
            2-D Numpy array of the intersection labels.
        dict
            Dictionary of connection points indexed by region label.
        """
        # Get the binary masks for the classes
        class_a_mask = grain_mask_tensor[:, :, classes[0]]
        class_b_mask = grain_mask_tensor[:, :, classes[1]]

        # Dilate class A mask
        dilated_class_a_mask = dilation(class_a_mask)
        # Get the intersection with the class B mask
        intersection = dilated_class_a_mask & class_b_mask

        # Get number of separate intersection regions
        intersection_labels = label(intersection)
        intersection_regions = regionprops(intersection_labels)
        num_connection_regions = len(intersection_regions)
        # Create a dictionary of the connection points
        intersection_points = {region.label: region.coords for region in intersection_regions}

        return num_connection_regions, intersection_labels, intersection_points

    @staticmethod
    def vet_class_connection_points(
        grain_mask_tensor: npt.NDArray,
        class_connection_point_thresholds: list[tuple[tuple[int, int], tuple[int, int]]] | None,
    ) -> bool:
        """
        Vet the number of connection points between regions in specific classes.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.
        class_connection_point_thresholds : list[tuple[tuple[int, int], tuple[int, int]]] | None
            List of tuples of classes and connection point thresholds. Structure is [(class_pair, (lower, upper))].

        Returns
        -------
        bool
            True if the grain passes the vetting, False if it fails.
        """
        if class_connection_point_thresholds is None:
            return True

        # Iterate over the class pairs
        for class_pair, connection_point_thresholds in class_connection_point_thresholds:
            # Get the connection regions
            num_connection_regions, _, _ = Grains.calculate_region_connection_regions(
                grain_mask_tensor=grain_mask_tensor,
                classes=class_pair,
            )
            # Check the number of connection regions against the thresholds
            lower_threshold, upper_threshold = connection_point_thresholds
            if lower_threshold is not None:
                if num_connection_regions < lower_threshold:
                    return False
            if upper_threshold is not None:
                if num_connection_regions > upper_threshold:
                    return False

        return True

    @staticmethod
    def assemble_grain_mask_tensor_from_crops(
        grain_mask_tensor_shape: tuple[int, int, int],
        grain_crops_and_bounding_boxes: list[dict[str, npt.NDArray]],
    ) -> npt.NDArray:
        """
        Combine individual grain crops into a single grain mask tensor.

        Parameters
        ----------
        grain_mask_tensor_shape : tuple
            Shape of the grain mask tensor.
        grain_crops_and_bounding_boxes : list
            List of dictionaries containing the grain crops and bounding boxes.
            Structure: [{"grain_tensor": npt.NDArray, "bounding_box": tuple, "padding": int}].

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the grain mask tensor.
        """
        # Initialise the grain mask tensor
        grain_mask_tensor = np.zeros(grain_mask_tensor_shape).astype(np.int32)

        # Iterate over the grain crops
        for grain_crop_and_bounding_box in grain_crops_and_bounding_boxes:
            # Get the grain crop and bounding box
            grain_crop = grain_crop_and_bounding_box["grain_tensor"]
            bounding_box = grain_crop_and_bounding_box["bounding_box"]
            padding = grain_crop_and_bounding_box["padding"]

            # Get the bounding box coordinates
            min_row, min_col, max_row, max_col = bounding_box

            # Crop the grain
            cropped_grain = grain_crop[
                padding:-padding,
                padding:-padding,
                :,
            ]

            # Update the grain mask tensor
            grain_mask_tensor[min_row + padding : max_row - padding, min_col + padding : max_col - padding, :] = (
                np.maximum(
                    grain_mask_tensor[min_row + padding : max_row - padding, min_col + padding : max_col - padding, :],
                    cropped_grain,
                )
            )

        # Update the background class
        grain_mask_tensor = Grains.update_background_class(grain_mask_tensor)

        return grain_mask_tensor.astype(bool)

    # Ignore too complex, to break the function down into smaller functions would make it more complex.
    # ruff: noqa: C901
    @staticmethod
    def convert_classes_when_too_big_or_small(
        grain_mask_tensor: npt.NDArray,
        pixel_to_nm_scaling: float,
        class_conversion_size_thresholds: list[tuple[tuple[int, int, int], tuple[int, int]]] | None,
    ) -> npt.NDArray:
        """
        Convert classes when they are too big or too small based on size thresholds.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.
        pixel_to_nm_scaling : float
            Scaling of pixels to nanometres.
        class_conversion_size_thresholds : list
            List of class conversion size thresholds.
            Structure is [(class_index, class_to_convert_to_if_to_small, class_to_convert_to_if_too_big),
            (lower_threshold, upper_threshold)].

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the grain mask tensor with classes converted based on size thresholds.
        """
        if class_conversion_size_thresholds is None:
            return grain_mask_tensor

        new_grain_mask_tensor = np.copy(grain_mask_tensor)
        classes_to_vet = [vetting_criteria[0][0] for vetting_criteria in class_conversion_size_thresholds]
        for class_index in range(1, grain_mask_tensor.shape[2]):
            if class_index not in classes_to_vet:
                continue

            lower_threshold, upper_threshold = [
                vetting_criteria[1]
                for vetting_criteria in class_conversion_size_thresholds
                if vetting_criteria[0][0] == class_index
            ][0]

            class_to_convert_to_if_too_small, class_to_convert_to_if_too_big = [
                vetting_criteria[0][1:]
                for vetting_criteria in class_conversion_size_thresholds
                if vetting_criteria[0][0] == class_index
            ][0]

            # For each region in the class, check its size and convert if needed
            labelled_regions = Grains.label_regions(grain_mask_tensor[:, :, class_index])
            region_properties = Grains.get_region_properties(labelled_regions)
            for region in region_properties:
                region_mask = labelled_regions == region.label
                region_size = np.sum(region_mask) * pixel_to_nm_scaling**2
                if lower_threshold is not None:
                    if region_size < lower_threshold:
                        if class_to_convert_to_if_too_small is not None:
                            # Add the region to the class to convert to in the new tensor
                            new_grain_mask_tensor[:, :, class_to_convert_to_if_too_small] = np.where(
                                region_mask,
                                class_to_convert_to_if_too_small,
                                new_grain_mask_tensor[:, :, class_to_convert_to_if_too_small],
                            )
                        # Remove the region from the original class
                        new_grain_mask_tensor[:, :, class_index] = np.where(
                            region_mask,
                            0,
                            new_grain_mask_tensor[:, :, class_index],
                        )
                if upper_threshold is not None:
                    if region_size > upper_threshold:
                        if class_to_convert_to_if_too_big is not None:
                            # Add the region to the class to convert to in the new tensor
                            new_grain_mask_tensor[:, :, class_to_convert_to_if_too_big] = np.where(
                                region_mask,
                                class_to_convert_to_if_too_big,
                                new_grain_mask_tensor[:, :, class_to_convert_to_if_too_big],
                            )
                        # Remove the region from the original class
                        new_grain_mask_tensor[:, :, class_index] = np.where(
                            region_mask,
                            0,
                            new_grain_mask_tensor[:, :, class_index],
                        )

        # Update the background class
        new_grain_mask_tensor = Grains.update_background_class(new_grain_mask_tensor)

        return new_grain_mask_tensor.astype(bool)

    @staticmethod
    def vet_whole_grain_size(
        grain_mask_tensor: npt.NDArray,
        pixel_to_nm_scaling: float,
        whole_grain_size_thresholds: tuple[float, float] | None,
    ) -> bool:
        """
        Vet the size of the whole grain based on size thresholds.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.
        pixel_to_nm_scaling : float
            Scaling of pixels to nanometres.
        whole_grain_size_thresholds : tuple
            Tuple of whole grain size thresholds. Structure is (lower, upper).

        Returns
        -------
        bool
            True if the grain size is within the area thresholds, False if it fails.
        """
        if whole_grain_size_thresholds is None:
            return True

        whole_grain_size_nm = (
            Grains.flatten_multi_class_tensor(grain_mask_tensor).astype(bool).sum() * pixel_to_nm_scaling**2
        )

        lower_threshold, upper_threshold = whole_grain_size_thresholds
        if lower_threshold is not None:
            if whole_grain_size_nm < lower_threshold:
                return False
        if upper_threshold is not None:
            if whole_grain_size_nm > upper_threshold:
                return False

        return True

    @staticmethod
    def vet_grains(
        graincrops: dict[int, GrainCrop],
        whole_grain_size_thresholds: tuple[float, float] | None,
        class_conversion_size_thresholds: list[tuple[tuple[int, int, int], tuple[int, int]]] | None,
        class_size_thresholds: list[tuple[int, int, int]] | None,
        class_region_number_thresholds: list[tuple[int, int, int]] | None,
        nearby_conversion_classes_to_convert: list[tuple[int, int]] | None,
        class_touching_threshold: int,
        keep_largest_labelled_regions_classes: list[int] | None,
        class_connection_point_thresholds: list[tuple[tuple[int, int], tuple[int, int]]] | None,
    ) -> dict[int, GrainCrop]:
        """
        Vet grains in a grain mask tensor based on a variety of criteria.

        Parameters
        ----------
        graincrops : dict[int, GrainCrop]
            Dictionary of grain crops.
        whole_grain_size_thresholds : tuple
            Tuple of whole grain size thresholds. Structure is (lower, upper).
        class_conversion_size_thresholds : list
            List of class conversion size thresholds. Structure is [(class_index, class_to_convert_to_if_too_small,
            class_to_convert_to_if_too_big), (lower_threshold, upper_threshold)].
        class_size_thresholds : list
            List of class size thresholds. Structure is [(class_index, lower, upper)].
        class_region_number_thresholds : list
            List of class region number thresholds. Structure is [(class_index, lower, upper)].
        nearby_conversion_classes_to_convert : list
            List of tuples of classes to convert. Structure is [(class_a, class_b)].
        class_touching_threshold : int
            Number of dilation passes to do to determine class A connectivity with class B.
        keep_largest_labelled_regions_classes : list
            List of classes to keep only the largest region.
        class_connection_point_thresholds : list
            List of tuples of classes and connection point thresholds. Structure is [(class_pair, (lower, upper))].

        Returns
        -------
        dict[int, GrainCrop]
            Dictionary of grain crops that passed the vetting.
        """
        passed_graincrops: dict[int, GrainCrop] = {}

        # Iterate over the grain crops
        for grain_number, graincrop in graincrops.items():
            single_grain_mask_tensor = graincrop.mask
            pixel_to_nm_scaling = graincrop.pixel_to_nm_scaling

            # Vet whole grain size
            if not Grains.vet_whole_grain_size(
                grain_mask_tensor=single_grain_mask_tensor,
                pixel_to_nm_scaling=pixel_to_nm_scaling,
                whole_grain_size_thresholds=whole_grain_size_thresholds,
            ):
                continue

            # Convert small / big areas to other classes
            single_grain_mask_tensor = Grains.convert_classes_when_too_big_or_small(
                grain_mask_tensor=single_grain_mask_tensor,
                pixel_to_nm_scaling=pixel_to_nm_scaling,
                class_conversion_size_thresholds=class_conversion_size_thresholds,
            )

            # Vet number of regions (foreground and background)
            _, passed = Grains.vet_numbers_of_regions_single_grain(
                grain_mask_tensor=single_grain_mask_tensor,
                class_region_number_thresholds=class_region_number_thresholds,
            )
            if not passed:
                continue

            # Vet size of regions (foreground and background)
            _, passed = Grains.vet_class_sizes_single_grain(
                single_grain_mask_tensor=single_grain_mask_tensor,
                pixel_to_nm_scaling=pixel_to_nm_scaling,
                class_size_thresholds=class_size_thresholds,
            )
            if not passed:
                continue

            # Turn all but largest region of class A into class B provided that the class A region touched a class B
            # region
            converted_single_grain_mask_tensor = Grains.convert_classes_to_nearby_classes(
                grain_mask_tensor=single_grain_mask_tensor,
                classes_to_convert=nearby_conversion_classes_to_convert,
                class_touching_threshold=class_touching_threshold,
            )

            # Remove all but largest region in specific classes
            largest_only_single_grain_mask_tensor = Grains.keep_largest_labelled_region_classes(
                single_grain_mask_tensor=converted_single_grain_mask_tensor,
                keep_largest_labelled_regions_classes=keep_largest_labelled_regions_classes,
            )

            # Vet number of connection points between regions in specific classes
            if not Grains.vet_class_connection_points(
                grain_mask_tensor=largest_only_single_grain_mask_tensor,
                class_connection_point_thresholds=class_connection_point_thresholds,
            ):
                continue

            # @ns-rse 2025-10-14 - do we need to instantiate a new instance here? I don't think we do as
            #                      we have setter methods so could just update the .mask attribute in
            #                      place (could perhaps set directly above?)
            # graincrop.mask = largest_only_single_grain_mask_tensor
            # If passed all vetting steps, add to the dictionary of passed grain crops
            passed_graincrops[grain_number] = GrainCrop(
                image=graincrop.image,
                mask=largest_only_single_grain_mask_tensor,
                padding=graincrop.padding,
                bbox=graincrop.bbox,
                pixel_to_nm_scaling=graincrop.pixel_to_nm_scaling,
                filename=graincrop.filename,
                height_profiles=graincrop.height_profiles,
                stats=graincrop.stats,
                disordered_trace=graincrop.disordered_trace,
                nodes=graincrop.nodes,
                ordered_trace=graincrop.ordered_trace,
                threshold_method=graincrop.threshold_method,
                thresholds=graincrop.thresholds,
            )

        return passed_graincrops

    @staticmethod
    def merge_classes(
        grain_mask_tensor: npt.NDArray,
        classes_to_merge: list[list[int]] | None,
    ) -> npt.NDArray:
        """
        Merge classes in a grain mask tensor and add them to the grain tensor.

        Parameters
        ----------
        grain_mask_tensor : npt.NDArray
            3-D Numpy array of the grain mask tensor.
        classes_to_merge : list | None
            List of tuples for classes to merge, can be any number of classes.

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the grain mask tensor with classes merged.
        """
        if classes_to_merge is None:
            return grain_mask_tensor
        # For each set of classes to merge:
        for classes in classes_to_merge:
            # Get the binary masks for all the classes
            class_masks = [grain_mask_tensor[:, :, class_index] for class_index in classes]
            # Combine the masks
            combined_mask = np.logical_or.reduce(class_masks)

            # Add new class to the grain tensor with the combined mask
            grain_mask_tensor = np.dstack([grain_mask_tensor, combined_mask])

        return grain_mask_tensor.astype(bool)

    @staticmethod
    def construct_full_mask_from_graincrops(
        graincrops: dict[int, GrainCrop], image_shape: tuple[int, int, int]
    ) -> npt.NDArray[np.bool_]:
        """
        Construct a full mask tensor from the grain crops.

        Parameters
        ----------
        graincrops : dict[int, GrainCrop]
            Dictionary of grain crops.
        image_shape : tuple[int, int, int]
            Shape of the original image.

        Returns
        -------
        npt.NDArray[np.bool_]
            HxWxC Numpy array of the full mask tensor (H = height, W = width, C = class >= 2).
        """
        # Calculate the number of classes from the first grain crop
        # Check if graincrops is empty
        if not graincrops:
            raise ValueError("No grain crops provided to construct the full mask tensor.")
        num_classes: int = list(graincrops.values())[0].mask.shape[2]
        full_mask_tensor: npt.NDArray[np.bool] = np.zeros((image_shape[0], image_shape[1], num_classes), dtype=np.bool_)
        for _grain_number, graincrop in graincrops.items():
            bounding_box = graincrop.bbox
            crop_tensor = graincrop.mask

            # Add the crop to the full mask tensor without overriding anything else, for all classes
            for class_index in range(crop_tensor.shape[2]):
                full_mask_tensor[
                    bounding_box[0] : bounding_box[2],
                    bounding_box[1] : bounding_box[3],
                    class_index,
                ] += crop_tensor[:, :, class_index]

        # Update background class and return
        return Grains.update_background_class(full_mask_tensor)

    def extract_grains_from_full_image_tensor(
        self,
        image: npt.NDArray[np.float32],
        full_mask_tensor: npt.NDArray[np.bool_],
        padding: int,
        pixel_to_nm_scaling: float,
        filename: str,
    ) -> dict[int, GrainCrop]:
        """
        Extract grains from the full image mask tensor.

        Grains are detected using connected components across all classes in the full mask tensor.

        Parameters
        ----------
        image : npt.NDArray[np.float32]
            2-D Numpy array of the image.
        full_mask_tensor : npt.NDArray[np.bool_]
            3-D NxNxC boolean numpy array of all the class masks for the image.
        padding : int
            Padding added to the bounding box of the grain before cropping.
        pixel_to_nm_scaling : float
            Pixel to nanometre scaling factor.
        filename : str
            Filename of the image.

        Returns
        -------
        dict[int, GrainCrop]
            Dictionary of grain crops.
        """
        # Flatten the mask tensor
        flat_mask = Grains.flatten_multi_class_tensor(full_mask_tensor)
        labelled_flat_full_mask = label(flat_mask)
        flat_regionprops_full_mask = regionprops(labelled_flat_full_mask)
        graincrops = {}
        for grain_number, flat_region in enumerate(flat_regionprops_full_mask):
            # Get a flattened binary mask for the whole grain and no other grains
            flattened_grain_binary_mask = labelled_flat_full_mask == flat_region.label

            # For each class, set all pixels to zero that are not in the current region
            grain_tensor_full_mask = np.zeros_like(full_mask_tensor).astype(bool)
            for class_index in range(1, full_mask_tensor.shape[2]):
                # Set all pixels to zero that are not in the current region's pixels by multiplying by a binary mask
                # for the whole flattened grain mask
                grain_tensor_full_mask[:, :, class_index] = (
                    flattened_grain_binary_mask * full_mask_tensor[:, :, class_index]
                ).astype(bool)

            # Crop the tensor
            # Get the bounding box for the region
            flat_bounding_box: tuple[int, int, int, int] = tuple(flat_region.bbox)  # min_row, min_col, max_row, max_col

            # Pad the mask
            padded_flat_bounding_box = pad_bounding_box_cutting_off_at_image_bounds(
                crop_min_row=flat_bounding_box[0],
                crop_min_col=flat_bounding_box[1],
                crop_max_row=flat_bounding_box[2],
                crop_max_col=flat_bounding_box[3],
                image_shape=(full_mask_tensor.shape[0], full_mask_tensor.shape[1]),
                padding=padding,
            )

            # Make the mask square
            square_flat_bounding_box = make_bounding_box_square(
                crop_min_row=padded_flat_bounding_box[0],
                crop_min_col=padded_flat_bounding_box[1],
                crop_max_row=padded_flat_bounding_box[2],
                crop_max_col=padded_flat_bounding_box[3],
                image_shape=(full_mask_tensor.shape[0], full_mask_tensor.shape[1]),
            )

            assert (
                square_flat_bounding_box[0] - square_flat_bounding_box[2]
                == square_flat_bounding_box[1] - square_flat_bounding_box[3]
            )

            # Grab image and mask for the cropped region
            grain_cropped_image = image[
                square_flat_bounding_box[0] : square_flat_bounding_box[2],
                square_flat_bounding_box[1] : square_flat_bounding_box[3],
            ]

            grain_cropped_tensor = grain_tensor_full_mask[
                square_flat_bounding_box[0] : square_flat_bounding_box[2],
                square_flat_bounding_box[1] : square_flat_bounding_box[3],
                :,
            ]

            # Update background class to reflect the removal of any non-connected grains
            grain_cropped_tensor = Grains.update_background_class(grain_mask_tensor=grain_cropped_tensor)

            assert grain_cropped_image.shape[0] == grain_cropped_image.shape[1]
            assert grain_cropped_tensor.shape[0] == grain_cropped_tensor.shape[1]
            # Check that the bounding box is square
            bounding_box_shape = (
                square_flat_bounding_box[2] - square_flat_bounding_box[0],
                square_flat_bounding_box[3] - square_flat_bounding_box[1],
            )
            assert bounding_box_shape[0] == bounding_box_shape[1]
            # Check bounding box shape is same as image shape and first two dimensions of tensor
            assert bounding_box_shape == grain_cropped_image.shape
            assert bounding_box_shape == (grain_cropped_tensor.shape[0], grain_cropped_tensor.shape[1])

            graincrops[grain_number] = GrainCrop(
                image=grain_cropped_image,
                mask=grain_cropped_tensor,
                padding=padding,
                bbox=square_flat_bounding_box,
                pixel_to_nm_scaling=pixel_to_nm_scaling,
                filename=filename,
                height_profiles=None,
                stats=None,
                disordered_trace=None,
                nodes=None,
                ordered_trace=None,
                threshold_method=self.threshold_method,
                thresholds=self.thresholds,
            )

        return graincrops

    @staticmethod
    def graincrops_remove_objects_too_small_to_process(
        graincrops: dict[int, GrainCrop],
        min_object_size: int,
        min_object_bbox_size: int,
    ) -> dict[int, GrainCrop]:
        """
        Remove objects that are too small to process from each class of the grain crops.

        Parameters
        ----------
        graincrops : dict[int, GrainCrop]
            Dictionary of grain crops.
        min_object_size : int
            Minimum object size to keep (pixels).
        min_object_bbox_size : int
            Minimum object bounding box size to keep (pixels^2).

        Returns
        -------
        dict[int, GrainCrop]
            Dictionary of grain crops with objects too small to process removed.
        """
        for _grain_number, graincrop in graincrops.items():
            # Iterate over the classes
            for class_index in range(1, graincrop.mask.shape[2]):
                # Get the binary mask for the class
                class_mask = graincrop.mask[:, :, class_index]

                # Label the regions
                labelled_regions = Grains.label_regions(class_mask)
                region_properties = Grains.get_region_properties(labelled_regions)

                # Iterate over the regions
                for region in region_properties:
                    # Get the region mask
                    region_mask = labelled_regions == region.label

                    # Check the region size
                    if (
                        region.area < min_object_size
                        or (region.bbox[2] - region.bbox[0]) < min_object_bbox_size
                        or (region.bbox[3] - region.bbox[1]) < min_object_bbox_size
                    ):
                        # Remove the region from the class
                        graincrop.mask[:, :, class_index] = np.where(
                            region_mask,
                            0,
                            graincrop.mask[:, :, class_index],
                        )

            # Update the background class
            graincrop.mask = Grains.update_background_class(graincrop.mask)

        return graincrops

    @staticmethod
    def graincrops_merge_classes(
        graincrops: dict[int, GrainCrop],
        classes_to_merge: list[list[int]] | None,
    ) -> dict[int, GrainCrop]:
        """
        Merge classes in the grain crops.

        Parameters
        ----------
        graincrops : dict[int, GrainCrop]
            Dictionary of grain crops.
        classes_to_merge : list | None
            List of tuples for classes to merge, can be any number of classes.

        Returns
        -------
        dict[int, GrainCrop]
            Dictionary of grain crops with classes merged.
        """
        if classes_to_merge is None:
            return graincrops

        for _grain_number, graincrop in graincrops.items():
            graincrop.mask = Grains.merge_classes(
                grain_mask_tensor=graincrop.mask,
                classes_to_merge=classes_to_merge,
            )

        return graincrops

    @staticmethod
    def graincrops_update_background_class(
        graincrops: dict[int, GrainCrop],
    ) -> dict[int, GrainCrop]:
        """
        Update the background class in the grain crops.

        Parameters
        ----------
        graincrops : dict[int, GrainCrop]
            Dictionary of grain crops.

        Returns
        -------
        dict[int, GrainCrop]
            Dictionary of grain crops with updated background class.
        """
        for _grain_number, graincrop in graincrops.items():
            graincrop.mask = Grains.update_background_class(graincrop.mask)

        return graincrops

    @staticmethod
    def remove_disconnected_grains(
        original_grain_tensor: npt.NDArray,
        predicted_grain_tensor: npt.NDArray,
    ):
        """
        Remove grains that are not connected to the original grains.

        Parameters
        ----------
        original_grain_tensor : npt.NDArray
            3-D Numpy array of the original grain tensor.
        predicted_grain_tensor : npt.NDArray
            3-D Numpy array of the predicted grain tensor.

        Returns
        -------
        npt.NDArray
            3-D Numpy array of the predicted grain tensor with grains not connected to the original grains removed.
        """
        # flatten the masks and compare connected components
        original_mask_flattened = Grains.flatten_multi_class_tensor(original_grain_tensor)
        predicted_mask_flattened = Grains.flatten_multi_class_tensor(predicted_grain_tensor)
        # Get the connected components of the original grain mask
        original_mask_flattened_labelled = label(original_mask_flattened)
        predicted_mask_flattened_labelled = label(predicted_mask_flattened)
        # for each region of the predicted mask, check if it overlaps with any of the original mask regions
        # (the original mask is expected to only have one region, but just in case future edits don't follow
        # this assumption, I check all regions)
        predicted_mask_regions = regionprops(predicted_mask_flattened_labelled)
        original_mask_regions = regionprops(original_mask_flattened_labelled)
        # if the predicted mask region doesn't overlap with any of the original mask regions, set it to 0
        for predicted_mask_region in predicted_mask_regions:
            predicted_mask_region_mask = predicted_mask_flattened_labelled == predicted_mask_region.label
            overlap = False
            for original_mask_region in original_mask_regions:
                original_mask_region_mask = original_mask_flattened_labelled == original_mask_region.label
                if np.any(predicted_mask_region_mask & original_mask_region_mask):
                    # a region in the flattened original mask shares a pixel with the flattened predicted mask
                    overlap = True
                    break
            if not overlap:
                # zero the region in all channels of the predicted mask
                for channel in range(1, predicted_grain_tensor.shape[-1]):
                    predicted_grain_tensor[predicted_mask_region_mask, channel] = 0

        return predicted_grain_tensor

__init__(topostats_object: TopoStats, grain_crop_padding: int = 1, unet_config: dict[str, str | int | float | tuple[int | None, int, int, int] | None] | None = None, threshold_method: str | None = None, otsu_threshold_multiplier: float | None = None, threshold_std_dev: dict[str, float | list] | None = None, threshold_absolute: dict[str, float | list] | None = None, area_thresholds: dict[str, list[float | None]] | None = None, remove_edge_intersecting_grains: bool = True, classes_to_merge: list[list[int]] | None = None, vetting: dict | None = None)

Initialise the class.

Parameters:

Name Type Description Default
topostats_object TopoStats

TopoStats object.

required
grain_crop_padding int

Padding to add to the bounding box of grains during cropping.

1
unet_config dict[str, str | int | float | tuple[int | None, int, int, int] | None]

Configuration for the UNet model which is a dictionary with the following keys and values. model_path : str Path to the UNet model. upper_norm_bound: float Upper bound for normalising the image. lower_norm_bound : float Lower bound for normalising the image.

None
threshold_method str

Method for determining thershold to mask values, default is 'otsu'.

None
otsu_threshold_multiplier float | None

Factor by which the below threshold is to be scaled prior to masking.

None
threshold_std_dev dict[str, float | list] | None

Dictionary of 'below' and 'above' factors by which standard deviation is multiplied to derive the threshold if threshold_method is 'std_dev'.

None
threshold_absolute dict[str, float | list] | None

Dictionary of absolute 'below' and 'above' thresholds for grain finding.

None
area_thresholds dict[str, list[float | None]]

Dictionary of above and below grain's area thresholds.

None
remove_edge_intersecting_grains bool

Direction for which grains are to be detected, valid values are 'above', 'below' and 'both'.

True
classes_to_merge list[tuple[int, int]] | None

List of tuples of classes to merge.

None
vetting dict | None

Dictionary of vetting parameters.

None
Source code in topostats\grains.py
def __init__(
    self,
    topostats_object: TopoStats,
    grain_crop_padding: int = 1,
    unet_config: dict[str, str | int | float | tuple[int | None, int, int, int] | None] | None = None,
    threshold_method: str | None = None,
    otsu_threshold_multiplier: float | None = None,
    threshold_std_dev: dict[str, float | list] | None = None,
    threshold_absolute: dict[str, float | list] | None = None,
    area_thresholds: dict[str, list[float | None]] | None = None,
    remove_edge_intersecting_grains: bool = True,
    classes_to_merge: list[list[int]] | None = None,
    vetting: dict | None = None,
):
    """
    Initialise the class.

    Parameters
    ----------
    topostats_object : TopoStats
        TopoStats object.
    grain_crop_padding : int
        Padding to add to the bounding box of grains during cropping.
    unet_config : dict[str, str | int | float | tuple[int | None, int, int, int] | None]
        Configuration for the UNet model which is a dictionary with the following keys and values.
        model_path : str
            Path to the UNet model.
        upper_norm_bound: float
            Upper bound for normalising the image.
        lower_norm_bound : float
            Lower bound for normalising the image.
    threshold_method : str
        Method for determining thershold to mask values, default is 'otsu'.
    otsu_threshold_multiplier : float | None
        Factor by which the below threshold is to be scaled prior to masking.
    threshold_std_dev : dict[str, float | list] | None
        Dictionary of 'below' and 'above' factors by which standard deviation is multiplied to derive the threshold
        if threshold_method is 'std_dev'.
    threshold_absolute : dict[str, float | list] | None
        Dictionary of absolute 'below' and 'above' thresholds for grain finding.
    area_thresholds : dict[str, list[float | None]]
        Dictionary of above and below grain's area thresholds.
    remove_edge_intersecting_grains : bool
        Direction for which grains are to be detected, valid values are 'above', 'below' and 'both'.
    classes_to_merge : list[tuple[int, int]] | None
        List of tuples of classes to merge.
    vetting : dict | None
        Dictionary of vetting parameters.
    """
    assert topostats_object.config is not None, AttributeError(
        f"[{topostats_object.filename}] : Missing 'config' "
        "attribute. If loading '.topostats' objects you may need to run the whole processing pipeline anew."
    )
    config = topostats_object.config["grains"]
    if unet_config is None:
        unet_config = {
            "model_path": None,
            "upper_norm_bound": 1.0,
            "lower_norm_bound": 0.0,
        }
    if area_thresholds is None:
        area_thresholds = {"above": [None, None], "below": [None, None]}
    self.topostats_object = topostats_object
    self.image = topostats_object.image
    self.filename = topostats_object.filename
    self.pixel_to_nm_scaling = topostats_object.pixel_to_nm_scaling
    self.threshold_method = config["threshold_method"] if threshold_method is None else threshold_method
    self.otsu_threshold_multiplier = (
        config["otsu_threshold_multiplier"] if otsu_threshold_multiplier is None else otsu_threshold_multiplier
    )

    # Ensure thresholds are lists (might not be from passing in CLI args)
    def _make_list(x: int | float | list[int | float]) -> list[int | float]:
        """
        Ensure item(s) are stored in a list.

        Parameters
        ----------
        x : int | float | list[int | float]
            Item to be converted to a list.

        Returns
        -------
        list[int | float]
            Item as a list.
        """
        if not isinstance(x, list):
            return [x]
        return x

    self.threshold_std_dev = config["threshold_std_dev"] if threshold_std_dev is None else threshold_std_dev
    self.threshold_std_dev["above"] = _make_list(self.threshold_std_dev["above"])
    self.threshold_std_dev["below"] = _make_list(self.threshold_std_dev["below"])
    self.threshold_absolute = config["threshold_absolute"] if threshold_absolute is None else threshold_absolute
    self.threshold_absolute["above"] = _make_list(self.threshold_absolute["above"])
    self.threshold_absolute["below"] = _make_list(self.threshold_absolute["below"])
    self.area_thresholds = config["area_thresholds"] if area_thresholds is None else area_thresholds
    self.area_thresholds["above"] = _make_list(self.area_thresholds["above"])
    self.area_thresholds["below"] = _make_list(self.area_thresholds["below"])
    self.remove_edge_intersecting_grains = (
        config["remove_edge_intersectin_grains"]
        if remove_edge_intersecting_grains is None
        else remove_edge_intersecting_grains
    )
    self.thresholds: dict[str, list[float]] | None = None
    self.mask_images: dict[str, dict[str, npt.NDArray]] = {}
    self.grain_crop_padding = grain_crop_padding
    self.unet_config = config["unet_config"] if unet_config is None else unet_config
    self.vetting_config = config["vetting"] if vetting is None else vetting
    self.classes_to_merge = config["classes_to_merge"] if classes_to_merge is None else classes_to_merge

    # Hardcoded minimum pixel size for grains. This should not be able to be changed by the user as this is
    # determined by what is processable by the rest of the pipeline.
    self.minimum_grain_size_px = 10
    self.minimum_bbox_size_px = 5

    self.grain_crops = {}

area_thresholding_tensor(grain_mask_tensor: npt.NDArray[np.bool_], area_thresholds: tuple[float | None, float | None], pixel_to_nm_scaling: float) -> npt.NDArray[np.bool_] staticmethod

Remove objects larger and smaller than the specified thresholds.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the full mask tensor.

required
area_thresholds tuple

List of area thresholds (in nanometres squared), first is the lower limit for size, second is the upper.

required
pixel_to_nm_scaling float

Scaling of pixels to nanometres.

required

Returns:

Type Description
NDArray

3-D Numpy array with small and large objects removed.

Source code in topostats\grains.py
@staticmethod
def area_thresholding_tensor(
    grain_mask_tensor: npt.NDArray[np.bool_],
    area_thresholds: tuple[float | None, float | None],
    pixel_to_nm_scaling: float,
) -> npt.NDArray[np.bool_]:
    """
    Remove objects larger and smaller than the specified thresholds.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the full mask tensor.
    area_thresholds : tuple
        List of area thresholds (in nanometres squared), first is the lower limit for size, second is the upper.
    pixel_to_nm_scaling : float
        Scaling of pixels to nanometres.

    Returns
    -------
    npt.NDArray
        3-D Numpy array with small and large objects removed.
    """
    lower_size_limit, upper_size_limit = area_thresholds
    if upper_size_limit is None:
        upper_size_limit = grain_mask_tensor.size * pixel_to_nm_scaling**2
    if lower_size_limit is None:
        lower_size_limit = 0

    # Iterate over all classes except background
    for class_index in range(1, grain_mask_tensor.shape[2]):
        class_mask = grain_mask_tensor[:, :, class_index]
        class_mask_labelled = label(class_mask)
        class_mask_regionprops = regionprops(class_mask_labelled)
        for region in class_mask_regionprops:
            region_area = region.area * pixel_to_nm_scaling**2
            if region_area > upper_size_limit or region_area < lower_size_limit:
                grain_mask_tensor[class_mask_labelled == region.label, class_index] = 0

    return Grains.update_background_class(grain_mask_tensor)

assemble_grain_mask_tensor_from_crops(grain_mask_tensor_shape: tuple[int, int, int], grain_crops_and_bounding_boxes: list[dict[str, npt.NDArray]]) -> npt.NDArray staticmethod

Combine individual grain crops into a single grain mask tensor.

Parameters:

Name Type Description Default
grain_mask_tensor_shape tuple

Shape of the grain mask tensor.

required
grain_crops_and_bounding_boxes list

List of dictionaries containing the grain crops and bounding boxes. Structure: [{"grain_tensor": npt.NDArray, "bounding_box": tuple, "padding": int}].

required

Returns:

Type Description
NDArray

3-D Numpy array of the grain mask tensor.

Source code in topostats\grains.py
@staticmethod
def assemble_grain_mask_tensor_from_crops(
    grain_mask_tensor_shape: tuple[int, int, int],
    grain_crops_and_bounding_boxes: list[dict[str, npt.NDArray]],
) -> npt.NDArray:
    """
    Combine individual grain crops into a single grain mask tensor.

    Parameters
    ----------
    grain_mask_tensor_shape : tuple
        Shape of the grain mask tensor.
    grain_crops_and_bounding_boxes : list
        List of dictionaries containing the grain crops and bounding boxes.
        Structure: [{"grain_tensor": npt.NDArray, "bounding_box": tuple, "padding": int}].

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the grain mask tensor.
    """
    # Initialise the grain mask tensor
    grain_mask_tensor = np.zeros(grain_mask_tensor_shape).astype(np.int32)

    # Iterate over the grain crops
    for grain_crop_and_bounding_box in grain_crops_and_bounding_boxes:
        # Get the grain crop and bounding box
        grain_crop = grain_crop_and_bounding_box["grain_tensor"]
        bounding_box = grain_crop_and_bounding_box["bounding_box"]
        padding = grain_crop_and_bounding_box["padding"]

        # Get the bounding box coordinates
        min_row, min_col, max_row, max_col = bounding_box

        # Crop the grain
        cropped_grain = grain_crop[
            padding:-padding,
            padding:-padding,
            :,
        ]

        # Update the grain mask tensor
        grain_mask_tensor[min_row + padding : max_row - padding, min_col + padding : max_col - padding, :] = (
            np.maximum(
                grain_mask_tensor[min_row + padding : max_row - padding, min_col + padding : max_col - padding, :],
                cropped_grain,
            )
        )

    # Update the background class
    grain_mask_tensor = Grains.update_background_class(grain_mask_tensor)

    return grain_mask_tensor.astype(bool)

bbox_size_thresholding_tensor(grain_mask_tensor: npt.NDArray[np.bool_], bbox_size_thresholds: tuple[int | None, int | None]) -> npt.NDArray[np.bool_] staticmethod

Remove objects whose bounding box is smaller than the specified threshold.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray[bool_]

3-D Numpy array of the full mask tensor.

required
bbox_size_thresholds tuple[int | None, int | None]

List of bounding box size thresholds (in pixels), first is the lower limit for size, second is the upper.

required

Returns:

Type Description
NDArray

3-D Numpy array with objects removed that are too small to process.

Source code in topostats\grains.py
@staticmethod
def bbox_size_thresholding_tensor(
    grain_mask_tensor: npt.NDArray[np.bool_], bbox_size_thresholds: tuple[int | None, int | None]
) -> npt.NDArray[np.bool_]:
    """
    Remove objects whose bounding box is smaller than the specified threshold.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray[np.bool_]
        3-D Numpy array of the full mask tensor.
    bbox_size_thresholds : tuple[int | None, int | None]
        List of bounding box size thresholds (in pixels), first is the lower limit for size, second is the upper.

    Returns
    -------
    npt.NDArray
        3-D Numpy array with objects removed that are too small to process.
    """
    lower_size_limit, upper_size_limit = bbox_size_thresholds

    # Iterate over all classes except background
    for class_index in range(1, grain_mask_tensor.shape[2]):
        class_mask = grain_mask_tensor[:, :, class_index]
        class_mask_labelled = label(class_mask)
        class_mask_regionprops = regionprops(class_mask_labelled)
        for region in class_mask_regionprops:
            bbox_width = region.bbox[2] - region.bbox[0]
            bbox_height = region.bbox[3] - region.bbox[1]
            if lower_size_limit is not None:
                if min(bbox_width, bbox_height) < lower_size_limit:
                    grain_mask_tensor[class_mask_labelled == region.label, class_index] = 0
            if upper_size_limit is not None:
                if max(bbox_width, bbox_height) > upper_size_limit:
                    grain_mask_tensor[class_mask_labelled == region.label, class_index] = 0

    return Grains.update_background_class(grain_mask_tensor)

calculate_region_connection_regions(grain_mask_tensor: npt.NDArray, classes: tuple[int, int]) -> tuple[int, npt.NDArray, dict[int, npt.NDArray[int]]] staticmethod

Get a list of connection regions between two classes.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required
classes tuple[int, int]

Tuple pair of classes to calculate the connection regions.

required

Returns:

Type Description
int

Number of connection regions.

NDArray

2-D Numpy array of the intersection labels.

dict

Dictionary of connection points indexed by region label.

Source code in topostats\grains.py
@staticmethod
def calculate_region_connection_regions(
    grain_mask_tensor: npt.NDArray,
    classes: tuple[int, int],
) -> tuple[int, npt.NDArray, dict[int, npt.NDArray[int]]]:
    """
    Get a list of connection regions between two classes.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.
    classes : tuple[int, int]
        Tuple pair of classes to calculate the connection regions.

    Returns
    -------
    int
        Number of connection regions.
    npt.NDArray
        2-D Numpy array of the intersection labels.
    dict
        Dictionary of connection points indexed by region label.
    """
    # Get the binary masks for the classes
    class_a_mask = grain_mask_tensor[:, :, classes[0]]
    class_b_mask = grain_mask_tensor[:, :, classes[1]]

    # Dilate class A mask
    dilated_class_a_mask = dilation(class_a_mask)
    # Get the intersection with the class B mask
    intersection = dilated_class_a_mask & class_b_mask

    # Get number of separate intersection regions
    intersection_labels = label(intersection)
    intersection_regions = regionprops(intersection_labels)
    num_connection_regions = len(intersection_regions)
    # Create a dictionary of the connection points
    intersection_points = {region.label: region.coords for region in intersection_regions}

    return num_connection_regions, intersection_labels, intersection_points

construct_full_mask_from_graincrops(graincrops: dict[int, GrainCrop], image_shape: tuple[int, int, int]) -> npt.NDArray[np.bool_] staticmethod

Construct a full mask tensor from the grain crops.

Parameters:

Name Type Description Default
graincrops dict[int, GrainCrop]

Dictionary of grain crops.

required
image_shape tuple[int, int, int]

Shape of the original image.

required

Returns:

Type Description
NDArray[bool_]

HxWxC Numpy array of the full mask tensor (H = height, W = width, C = class >= 2).

Source code in topostats\grains.py
@staticmethod
def construct_full_mask_from_graincrops(
    graincrops: dict[int, GrainCrop], image_shape: tuple[int, int, int]
) -> npt.NDArray[np.bool_]:
    """
    Construct a full mask tensor from the grain crops.

    Parameters
    ----------
    graincrops : dict[int, GrainCrop]
        Dictionary of grain crops.
    image_shape : tuple[int, int, int]
        Shape of the original image.

    Returns
    -------
    npt.NDArray[np.bool_]
        HxWxC Numpy array of the full mask tensor (H = height, W = width, C = class >= 2).
    """
    # Calculate the number of classes from the first grain crop
    # Check if graincrops is empty
    if not graincrops:
        raise ValueError("No grain crops provided to construct the full mask tensor.")
    num_classes: int = list(graincrops.values())[0].mask.shape[2]
    full_mask_tensor: npt.NDArray[np.bool] = np.zeros((image_shape[0], image_shape[1], num_classes), dtype=np.bool_)
    for _grain_number, graincrop in graincrops.items():
        bounding_box = graincrop.bbox
        crop_tensor = graincrop.mask

        # Add the crop to the full mask tensor without overriding anything else, for all classes
        for class_index in range(crop_tensor.shape[2]):
            full_mask_tensor[
                bounding_box[0] : bounding_box[2],
                bounding_box[1] : bounding_box[3],
                class_index,
            ] += crop_tensor[:, :, class_index]

    # Update background class and return
    return Grains.update_background_class(full_mask_tensor)

convert_classes_to_nearby_classes(grain_mask_tensor: npt.NDArray, classes_to_convert: list[tuple[int, int]] | None, class_touching_threshold: int = 1) -> npt.NDArray staticmethod

Convert all but the largest regions of one class into another class provided the former touches the latter.

Specifically, it takes a list of tuples of two integers (dubbed class A and class B). For each class A, class B pair, it will find the largest region of class A and flag it to be ignored. Then for each non-largest region of class A, it will check if it touches any class B region (within the class_touching_threshold distance). If it does, it will convert the region to class B.

This is useful for situations where you want just one region of class A and the model has a habit of producing small regions of class A interspersed in the class B regions, which should be class B instead.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required
classes_to_convert list

List of tuples of classes to convert. Structure is [(class_a, class_b)].

required
class_touching_threshold int

Number of dilation passes to do to determine class A connectivity with class B.

1

Returns:

Type Description
NDArray

3-D Numpy array of the grain mask tensor with classes converted.

Source code in topostats\grains.py
@staticmethod
def convert_classes_to_nearby_classes(
    grain_mask_tensor: npt.NDArray,
    classes_to_convert: list[tuple[int, int]] | None,
    class_touching_threshold: int = 1,
) -> npt.NDArray:
    """
    Convert all but the largest regions of one class into another class provided the former touches the latter.

    Specifically, it takes a list of tuples of two integers (dubbed class A and class B). For each class A, class B
    pair, it will find the largest region of class A and flag it to be ignored. Then for each non-largest region of
    class A, it will check if it touches any class B region (within the ``class_touching_threshold`` distance). If it
    does, it will convert the region to class B.

    This is useful for situations where you want just one region of class A and the model has a habit of producing
    small regions of class A interspersed in the class B regions, which should be class B instead.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.
    classes_to_convert : list
        List of tuples of classes to convert. Structure is [(class_a, class_b)].
    class_touching_threshold : int
        Number of dilation passes to do to determine class A connectivity with class B.

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the grain mask tensor with classes converted.
    """
    # If no classes to convert, return the original tensor
    if not classes_to_convert:
        return grain_mask_tensor

    # Iterate over class pairs
    for class_a, class_b in classes_to_convert:
        # Get the binary mask for class A and class B
        class_a_mask = grain_mask_tensor[:, :, class_a]
        class_b_mask = grain_mask_tensor[:, :, class_b]

        # Skip if no regions of class A
        if np.max(class_a_mask) == 0:
            continue

        # Find the largest region of class A
        class_a_labelled_regions = Grains.label_regions(class_a_mask)
        class_a_region_properties = Grains.get_region_properties(class_a_labelled_regions)
        class_a_areas = [region.area for region in class_a_region_properties]
        largest_class_a_region = class_a_region_properties[np.argmax(class_a_areas)]

        # For all other regions, check if they touch the class B region
        for region in class_a_region_properties:
            if region.label == largest_class_a_region.label:
                continue
            # Get only the pixels in the region
            region_mask = class_a_labelled_regions == region.label
            # Dilate the region
            dilated_region_mask = region_mask
            for _ in range(class_touching_threshold):
                dilated_region_mask = dilation(dilated_region_mask)
            # Get the intersection with the class B mask
            intersection = dilated_region_mask & class_b_mask
            # If there is any intersection, turn the region into class B
            if np.any(intersection):
                # Add to the class B mask
                class_b_mask = np.where(region_mask, class_b, class_b_mask)
                # Remove from the class A mask
                class_a_mask = np.where(region_mask, 0, class_a_mask)

        # Update the tensor
        grain_mask_tensor[:, :, class_a] = class_a_mask
        grain_mask_tensor[:, :, class_b] = class_b_mask

    return grain_mask_tensor.astype(bool)

convert_classes_when_too_big_or_small(grain_mask_tensor: npt.NDArray, pixel_to_nm_scaling: float, class_conversion_size_thresholds: list[tuple[tuple[int, int, int], tuple[int, int]]] | None) -> npt.NDArray staticmethod

Convert classes when they are too big or too small based on size thresholds.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required
pixel_to_nm_scaling float

Scaling of pixels to nanometres.

required
class_conversion_size_thresholds list

List of class conversion size thresholds. Structure is [(class_index, class_to_convert_to_if_to_small, class_to_convert_to_if_too_big), (lower_threshold, upper_threshold)].

required

Returns:

Type Description
NDArray

3-D Numpy array of the grain mask tensor with classes converted based on size thresholds.

Source code in topostats\grains.py
@staticmethod
def convert_classes_when_too_big_or_small(
    grain_mask_tensor: npt.NDArray,
    pixel_to_nm_scaling: float,
    class_conversion_size_thresholds: list[tuple[tuple[int, int, int], tuple[int, int]]] | None,
) -> npt.NDArray:
    """
    Convert classes when they are too big or too small based on size thresholds.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.
    pixel_to_nm_scaling : float
        Scaling of pixels to nanometres.
    class_conversion_size_thresholds : list
        List of class conversion size thresholds.
        Structure is [(class_index, class_to_convert_to_if_to_small, class_to_convert_to_if_too_big),
        (lower_threshold, upper_threshold)].

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the grain mask tensor with classes converted based on size thresholds.
    """
    if class_conversion_size_thresholds is None:
        return grain_mask_tensor

    new_grain_mask_tensor = np.copy(grain_mask_tensor)
    classes_to_vet = [vetting_criteria[0][0] for vetting_criteria in class_conversion_size_thresholds]
    for class_index in range(1, grain_mask_tensor.shape[2]):
        if class_index not in classes_to_vet:
            continue

        lower_threshold, upper_threshold = [
            vetting_criteria[1]
            for vetting_criteria in class_conversion_size_thresholds
            if vetting_criteria[0][0] == class_index
        ][0]

        class_to_convert_to_if_too_small, class_to_convert_to_if_too_big = [
            vetting_criteria[0][1:]
            for vetting_criteria in class_conversion_size_thresholds
            if vetting_criteria[0][0] == class_index
        ][0]

        # For each region in the class, check its size and convert if needed
        labelled_regions = Grains.label_regions(grain_mask_tensor[:, :, class_index])
        region_properties = Grains.get_region_properties(labelled_regions)
        for region in region_properties:
            region_mask = labelled_regions == region.label
            region_size = np.sum(region_mask) * pixel_to_nm_scaling**2
            if lower_threshold is not None:
                if region_size < lower_threshold:
                    if class_to_convert_to_if_too_small is not None:
                        # Add the region to the class to convert to in the new tensor
                        new_grain_mask_tensor[:, :, class_to_convert_to_if_too_small] = np.where(
                            region_mask,
                            class_to_convert_to_if_too_small,
                            new_grain_mask_tensor[:, :, class_to_convert_to_if_too_small],
                        )
                    # Remove the region from the original class
                    new_grain_mask_tensor[:, :, class_index] = np.where(
                        region_mask,
                        0,
                        new_grain_mask_tensor[:, :, class_index],
                    )
            if upper_threshold is not None:
                if region_size > upper_threshold:
                    if class_to_convert_to_if_too_big is not None:
                        # Add the region to the class to convert to in the new tensor
                        new_grain_mask_tensor[:, :, class_to_convert_to_if_too_big] = np.where(
                            region_mask,
                            class_to_convert_to_if_too_big,
                            new_grain_mask_tensor[:, :, class_to_convert_to_if_too_big],
                        )
                    # Remove the region from the original class
                    new_grain_mask_tensor[:, :, class_index] = np.where(
                        region_mask,
                        0,
                        new_grain_mask_tensor[:, :, class_index],
                    )

    # Update the background class
    new_grain_mask_tensor = Grains.update_background_class(new_grain_mask_tensor)

    return new_grain_mask_tensor.astype(bool)

extract_grains_from_full_image_tensor(image: npt.NDArray[np.float32], full_mask_tensor: npt.NDArray[np.bool_], padding: int, pixel_to_nm_scaling: float, filename: str) -> dict[int, GrainCrop]

Extract grains from the full image mask tensor.

Grains are detected using connected components across all classes in the full mask tensor.

Parameters:

Name Type Description Default
image NDArray[float32]

2-D Numpy array of the image.

required
full_mask_tensor NDArray[bool_]

3-D NxNxC boolean numpy array of all the class masks for the image.

required
padding int

Padding added to the bounding box of the grain before cropping.

required
pixel_to_nm_scaling float

Pixel to nanometre scaling factor.

required
filename str

Filename of the image.

required

Returns:

Type Description
dict[int, GrainCrop]

Dictionary of grain crops.

Source code in topostats\grains.py
def extract_grains_from_full_image_tensor(
    self,
    image: npt.NDArray[np.float32],
    full_mask_tensor: npt.NDArray[np.bool_],
    padding: int,
    pixel_to_nm_scaling: float,
    filename: str,
) -> dict[int, GrainCrop]:
    """
    Extract grains from the full image mask tensor.

    Grains are detected using connected components across all classes in the full mask tensor.

    Parameters
    ----------
    image : npt.NDArray[np.float32]
        2-D Numpy array of the image.
    full_mask_tensor : npt.NDArray[np.bool_]
        3-D NxNxC boolean numpy array of all the class masks for the image.
    padding : int
        Padding added to the bounding box of the grain before cropping.
    pixel_to_nm_scaling : float
        Pixel to nanometre scaling factor.
    filename : str
        Filename of the image.

    Returns
    -------
    dict[int, GrainCrop]
        Dictionary of grain crops.
    """
    # Flatten the mask tensor
    flat_mask = Grains.flatten_multi_class_tensor(full_mask_tensor)
    labelled_flat_full_mask = label(flat_mask)
    flat_regionprops_full_mask = regionprops(labelled_flat_full_mask)
    graincrops = {}
    for grain_number, flat_region in enumerate(flat_regionprops_full_mask):
        # Get a flattened binary mask for the whole grain and no other grains
        flattened_grain_binary_mask = labelled_flat_full_mask == flat_region.label

        # For each class, set all pixels to zero that are not in the current region
        grain_tensor_full_mask = np.zeros_like(full_mask_tensor).astype(bool)
        for class_index in range(1, full_mask_tensor.shape[2]):
            # Set all pixels to zero that are not in the current region's pixels by multiplying by a binary mask
            # for the whole flattened grain mask
            grain_tensor_full_mask[:, :, class_index] = (
                flattened_grain_binary_mask * full_mask_tensor[:, :, class_index]
            ).astype(bool)

        # Crop the tensor
        # Get the bounding box for the region
        flat_bounding_box: tuple[int, int, int, int] = tuple(flat_region.bbox)  # min_row, min_col, max_row, max_col

        # Pad the mask
        padded_flat_bounding_box = pad_bounding_box_cutting_off_at_image_bounds(
            crop_min_row=flat_bounding_box[0],
            crop_min_col=flat_bounding_box[1],
            crop_max_row=flat_bounding_box[2],
            crop_max_col=flat_bounding_box[3],
            image_shape=(full_mask_tensor.shape[0], full_mask_tensor.shape[1]),
            padding=padding,
        )

        # Make the mask square
        square_flat_bounding_box = make_bounding_box_square(
            crop_min_row=padded_flat_bounding_box[0],
            crop_min_col=padded_flat_bounding_box[1],
            crop_max_row=padded_flat_bounding_box[2],
            crop_max_col=padded_flat_bounding_box[3],
            image_shape=(full_mask_tensor.shape[0], full_mask_tensor.shape[1]),
        )

        assert (
            square_flat_bounding_box[0] - square_flat_bounding_box[2]
            == square_flat_bounding_box[1] - square_flat_bounding_box[3]
        )

        # Grab image and mask for the cropped region
        grain_cropped_image = image[
            square_flat_bounding_box[0] : square_flat_bounding_box[2],
            square_flat_bounding_box[1] : square_flat_bounding_box[3],
        ]

        grain_cropped_tensor = grain_tensor_full_mask[
            square_flat_bounding_box[0] : square_flat_bounding_box[2],
            square_flat_bounding_box[1] : square_flat_bounding_box[3],
            :,
        ]

        # Update background class to reflect the removal of any non-connected grains
        grain_cropped_tensor = Grains.update_background_class(grain_mask_tensor=grain_cropped_tensor)

        assert grain_cropped_image.shape[0] == grain_cropped_image.shape[1]
        assert grain_cropped_tensor.shape[0] == grain_cropped_tensor.shape[1]
        # Check that the bounding box is square
        bounding_box_shape = (
            square_flat_bounding_box[2] - square_flat_bounding_box[0],
            square_flat_bounding_box[3] - square_flat_bounding_box[1],
        )
        assert bounding_box_shape[0] == bounding_box_shape[1]
        # Check bounding box shape is same as image shape and first two dimensions of tensor
        assert bounding_box_shape == grain_cropped_image.shape
        assert bounding_box_shape == (grain_cropped_tensor.shape[0], grain_cropped_tensor.shape[1])

        graincrops[grain_number] = GrainCrop(
            image=grain_cropped_image,
            mask=grain_cropped_tensor,
            padding=padding,
            bbox=square_flat_bounding_box,
            pixel_to_nm_scaling=pixel_to_nm_scaling,
            filename=filename,
            height_profiles=None,
            stats=None,
            disordered_trace=None,
            nodes=None,
            ordered_trace=None,
            threshold_method=self.threshold_method,
            thresholds=self.thresholds,
        )

    return graincrops

find_grains() -> None

Find grains.

Source code in topostats\grains.py
def find_grains(self) -> None:
    """Find grains."""
    LOGGER.debug(f"[{self.filename}] : Thresholding method (grains) : {self.threshold_method}")
    assert self.threshold_method is not None, "Threshold method must be specified"  # type safety
    # calculate thresholds based on configuration
    self.thresholds = get_thresholds(
        image=self.image,
        threshold_method=self.threshold_method,
        otsu_threshold_multiplier=self.otsu_threshold_multiplier,
        threshold_std_dev=self.threshold_std_dev,
        absolute=self.threshold_absolute,
    )

    for direction, direction_thresholds in self.thresholds.items():
        LOGGER.debug(f"[{self.filename}] : Finding {direction} grains, threshold: ({direction_thresholds})")
        self.mask_images[direction] = {}

        # iterate over the thresholds for the current direction
        traditional_full_mask_tensor = Grains.multi_class_thresholding(
            image=self.image,
            thresholds=direction_thresholds,
            threshold_direction=direction,
            image_name=self.filename,
        )

        self.mask_images[direction]["thresholded_grains"] = traditional_full_mask_tensor.copy()

        # pre-GrainCrop checks

        # Tidy border - done here and not in vetting to not make vetting dependent on image size argument.
        if self.remove_edge_intersecting_grains:
            traditional_full_mask_tensor = Grains.tidy_border_tensor(grain_mask_tensor=traditional_full_mask_tensor)
        self.mask_images[direction]["tidied_border"] = traditional_full_mask_tensor.copy()

        # Remove objects with area too small to process
        traditional_full_mask_tensor = Grains.area_thresholding_tensor(
            grain_mask_tensor=traditional_full_mask_tensor,
            area_thresholds=(self.minimum_grain_size_px * self.pixel_to_nm_scaling**2, None),
            pixel_to_nm_scaling=self.pixel_to_nm_scaling,
        )
        # Remove objects with bounding box too small to process
        traditional_full_mask_tensor = Grains.bbox_size_thresholding_tensor(
            grain_mask_tensor=traditional_full_mask_tensor,
            bbox_size_thresholds=(self.minimum_bbox_size_px, None),
        )
        self.mask_images[direction]["removed_objects_too_small_to_process"] = traditional_full_mask_tensor.copy()

        # Area threshold using user specified thresholds
        traditional_full_mask_tensor = Grains.area_thresholding_tensor(
            grain_mask_tensor=traditional_full_mask_tensor,
            area_thresholds=self.area_thresholds[direction],
            pixel_to_nm_scaling=self.pixel_to_nm_scaling,
        )

        self.mask_images[direction]["area_thresholded"] = traditional_full_mask_tensor.copy()

        # Extract GrainCrops from the full mask tensor
        traditional_graincrops = self.extract_grains_from_full_image_tensor(
            image=self.image,
            full_mask_tensor=traditional_full_mask_tensor,
            padding=self.grain_crop_padding,
            pixel_to_nm_scaling=self.pixel_to_nm_scaling,
            filename=self.filename,
        )

        # If there are no grains, then later steps will fail, so skip the stages if no grains are found.
        if len(traditional_graincrops) > 0:
            # Grains found

            # Create a tensor out of the grain mask of shape NxNx2, where the two classes are a binary background
            # mask and the second is a binary grain mask. This is because we want to support multiple classes, and
            # so we standardise so that the first layer is background mask, then feature mask 1, then feature mask
            # 2 etc.

            # Optionally run a user-supplied u-net model on the grains to improve the segmentation
            if self.unet_config["model_path"] is not None:
                # Run unet segmentation on only the class 1 layer of the labelled_regions_02. Need to make this configurable
                # later on along with all the other hardcoded class 1s.
                graincrops = Grains.improve_grain_segmentation_unet(
                    filename=self.filename,
                    direction=direction,
                    unet_config=self.unet_config,
                    graincrops=traditional_graincrops,
                )
            else:
                # otherwise use the traditional graincrops
                graincrops = traditional_graincrops
            # Construct full masks from the crops
            full_mask_tensor = Grains.construct_full_mask_from_graincrops(
                graincrops=graincrops,
                image_shape=self.image.shape,
            )

            # Set the unet tensor regardless of if the unet model was run, since the plotting expects it
            # can be changed when we do a plotting overhaul
            self.mask_images[direction]["unet"] = full_mask_tensor.copy()

            # Vet the grains
            if self.vetting_config is not None:
                graincrops_vetted = Grains.vet_grains(
                    graincrops=graincrops,
                    **self.vetting_config,
                )
            else:
                graincrops_vetted = graincrops
            graincrops_vetted = Grains.graincrops_update_background_class(graincrops=graincrops_vetted)

            full_mask_tensor_vetted = Grains.construct_full_mask_from_graincrops(
                graincrops=graincrops_vetted,
                image_shape=self.image.shape,
            )
            self.mask_images[direction]["vetted"] = full_mask_tensor_vetted.copy()

            # Mandatory check to remove any objects in any classes that are too small to process
            graincrops_removed_too_small_to_process = Grains.graincrops_remove_objects_too_small_to_process(
                graincrops=graincrops_vetted,
                min_object_size=self.minimum_grain_size_px,
                min_object_bbox_size=self.minimum_bbox_size_px,
            )
            graincrops_removed_too_small_to_process = Grains.graincrops_update_background_class(
                graincrops=graincrops_removed_too_small_to_process
            )

            # Merge classes as specified by the user
            graincrops_merged_classes = Grains.graincrops_merge_classes(
                graincrops=graincrops_removed_too_small_to_process,
                classes_to_merge=self.classes_to_merge,
            )
            graincrops_merged_classes = Grains.graincrops_update_background_class(
                graincrops=graincrops_merged_classes
            )

            full_mask_tensor_merged_classes = Grains.construct_full_mask_from_graincrops(
                graincrops=graincrops_merged_classes,
                image_shape=self.image.shape,
            )
            self.mask_images[direction]["merged_classes"] = full_mask_tensor_merged_classes.copy()
            self.grain_crops = graincrops_merged_classes
            self.topostats_object.grain_crops = graincrops_merged_classes
            self.topostats_object.full_mask_tensor = full_mask_tensor_merged_classes
        else:
            # No grains found
            self.grain_crops = None
            # self.topostats_object.grain_crops = self.grain_crops
            self.topostats_object.full_mask_tensor = None

flatten_multi_class_tensor(grain_mask_tensor: npt.NDArray) -> npt.NDArray staticmethod

Flatten a multi-class image tensor to a single binary mask.

The returned tensor is of boolean type in case there are multiple hits in the same pixel. We dont want to have 2s, 3s etc because this would cause issues in labelling and cause erroneous grains within grains.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

Multi class grain mask tensor tensor of shape (N, N, C).

required

Returns:

Type Description
NDArray

Combined binary mask of all but the background class (:, :, 0).

Source code in topostats\grains.py
@staticmethod
def flatten_multi_class_tensor(grain_mask_tensor: npt.NDArray) -> npt.NDArray:
    """
    Flatten a multi-class image tensor to a single binary mask.

    The returned tensor is of boolean type in case there are multiple hits in the same pixel. We dont want to have
    2s, 3s etc because this would cause issues in labelling and cause erroneous grains within grains.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        Multi class grain mask tensor tensor of shape (N, N, C).

    Returns
    -------
    npt.NDArray
        Combined binary mask of all but the background class (:, :, 0).
    """
    assert len(grain_mask_tensor.shape) == 3, f"Tensor not 3D: {grain_mask_tensor.shape}"
    return np.sum(grain_mask_tensor[:, :, 1:], axis=-1).astype(bool)

get_individual_grain_crops(grain_mask_tensor: npt.NDArray, padding: int = 1) -> tuple[list[npt.NDArray], list[npt.NDArray], int] staticmethod

Get individual grain crops from an image tensor.

Fetches individual grain crops from an image tensor, but zeros any non-connected grains in the crop region. This is to ensure that other grains do not affect further processing steps.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of image tensor.

required
padding int

Padding to add to the bounding box of the grain before cropping. Default is 1.

1

Returns:

Type Description
list[NDArray]

List of individual grain crops.

list[NDArray]

List of bounding boxes for each grain.

int

Padding used for the bounding boxes.

Source code in topostats\grains.py
@staticmethod
def get_individual_grain_crops(
    grain_mask_tensor: npt.NDArray,
    padding: int = 1,
) -> tuple[list[npt.NDArray], list[npt.NDArray], int]:
    """
    Get individual grain crops from an image tensor.

    Fetches individual grain crops from an image tensor, but zeros any non-connected grains
    in the crop region. This is to ensure that other grains do not affect further processing
    steps.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of image tensor.
    padding : int
        Padding to add to the bounding box of the grain before cropping. Default is 1.

    Returns
    -------
    list[npt.NDArray]
        List of individual grain crops.
    list[npt.NDArray]
        List of bounding boxes for each grain.
    int
        Padding used for the bounding boxes.
    """
    grain_crops = []
    bounding_boxes = []

    # Label the regions
    flattened_multi_class_mask = Grains.flatten_multi_class_tensor(grain_mask_tensor)
    labelled_regions = Grains.label_regions(flattened_multi_class_mask)

    # Iterate over the regions and return the crop, but zero any non-connected grains
    for region in Grains.get_region_properties(labelled_regions):
        binary_labelled_regions = labelled_regions == region.label

        # Zero any non-connected grains
        # For each class, set all pixels to zero that are not in the current region
        this_region_only_grain_tensor = np.copy(grain_mask_tensor)
        # Iterate over the non-background classes
        for class_index in range(1, grain_mask_tensor.shape[2]):
            # Set all pixels to zero that are not in the current region
            this_region_only_grain_tensor[:, :, class_index] = (
                binary_labelled_regions * grain_mask_tensor[:, :, class_index]
            )

        # Update background class to reflect the removal of any non-connected grains
        this_region_only_grain_tensor = Grains.update_background_class(
            grain_mask_tensor=this_region_only_grain_tensor
        )

        # Get the bounding box
        bounding_box = region.bbox

        # Pad the bounding box
        bounding_box = pad_bounding_box_cutting_off_at_image_bounds(
            crop_min_row=bounding_box[0],
            crop_min_col=bounding_box[1],
            crop_max_row=bounding_box[2],
            crop_max_col=bounding_box[3],
            image_shape=(grain_mask_tensor.shape[0], grain_mask_tensor.shape[1]),
            padding=padding,
        )

        # Crop the grain
        grain_crop = this_region_only_grain_tensor[
            bounding_box[0] : bounding_box[2],
            bounding_box[1] : bounding_box[3],
            :,
        ]

        # Add the crop to the list
        grain_crops.append(grain_crop.astype(bool))
        bounding_boxes.append(bounding_box)

    return grain_crops, bounding_boxes, padding

get_multi_class_grain_bounding_boxes(grain_mask_tensor: npt.NDArray) -> dict staticmethod

Get the bounding boxes for each grain in a multi-class image tensor.

Finds the bounding boxes for each grain in a multi-class image tensor. Grains can span multiple classes, so the bounding boxes are found for the combined binary mask of contiguous grains across all classes.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of grain mask tensor.

required

Returns:

Type Description
dict

Dictionary of bounding boxes indexed by grain number.

Source code in topostats\grains.py
@staticmethod
def get_multi_class_grain_bounding_boxes(grain_mask_tensor: npt.NDArray) -> dict:
    """
    Get the bounding boxes for each grain in a multi-class image tensor.

    Finds the bounding boxes for each grain in a multi-class image tensor. Grains can span multiple classes, so the
    bounding boxes are found for the combined binary mask of contiguous grains across all classes.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of grain mask tensor.

    Returns
    -------
    dict
        Dictionary of bounding boxes indexed by grain number.
    """
    flattened_mask = Grains.flatten_multi_class_tensor(grain_mask_tensor)
    labelled_regions = Grains.label_regions(flattened_mask)
    region_properties = Grains.get_region_properties(labelled_regions)
    bounding_boxes = {index: region.bbox for index, region in enumerate(region_properties)}
    return {
        index: pad_bounding_box_cutting_off_at_image_bounds(
            crop_min_row=bbox[0],
            crop_min_col=bbox[1],
            crop_max_row=bbox[2],
            crop_max_col=bbox[3],
            image_shape=(grain_mask_tensor.shape[0], grain_mask_tensor.shape[1]),
            padding=1,
        )
        for index, bbox in bounding_boxes.items()
    }

get_region_properties(image: npt.NDArray, **kwargs) -> list staticmethod

Extract the properties of each region.

Parameters:

Name Type Description Default
image array

Numpy array representing image.

required
**kwargs

Arguments passed to 'skimage.measure.regionprops(**kwargs)'.

{}

Returns:

Type Description
list

List of region property objects.

Source code in topostats\grains.py
@staticmethod
def get_region_properties(image: npt.NDArray, **kwargs) -> list:
    """
    Extract the properties of each region.

    Parameters
    ----------
    image : np.array
        Numpy array representing image.
    **kwargs :
        Arguments passed to 'skimage.measure.regionprops(**kwargs)'.

    Returns
    -------
    list
        List of region property objects.
    """
    return regionprops(image, **kwargs)

graincrops_merge_classes(graincrops: dict[int, GrainCrop], classes_to_merge: list[list[int]] | None) -> dict[int, GrainCrop] staticmethod

Merge classes in the grain crops.

Parameters:

Name Type Description Default
graincrops dict[int, GrainCrop]

Dictionary of grain crops.

required
classes_to_merge list | None

List of tuples for classes to merge, can be any number of classes.

required

Returns:

Type Description
dict[int, GrainCrop]

Dictionary of grain crops with classes merged.

Source code in topostats\grains.py
@staticmethod
def graincrops_merge_classes(
    graincrops: dict[int, GrainCrop],
    classes_to_merge: list[list[int]] | None,
) -> dict[int, GrainCrop]:
    """
    Merge classes in the grain crops.

    Parameters
    ----------
    graincrops : dict[int, GrainCrop]
        Dictionary of grain crops.
    classes_to_merge : list | None
        List of tuples for classes to merge, can be any number of classes.

    Returns
    -------
    dict[int, GrainCrop]
        Dictionary of grain crops with classes merged.
    """
    if classes_to_merge is None:
        return graincrops

    for _grain_number, graincrop in graincrops.items():
        graincrop.mask = Grains.merge_classes(
            grain_mask_tensor=graincrop.mask,
            classes_to_merge=classes_to_merge,
        )

    return graincrops

graincrops_remove_objects_too_small_to_process(graincrops: dict[int, GrainCrop], min_object_size: int, min_object_bbox_size: int) -> dict[int, GrainCrop] staticmethod

Remove objects that are too small to process from each class of the grain crops.

Parameters:

Name Type Description Default
graincrops dict[int, GrainCrop]

Dictionary of grain crops.

required
min_object_size int

Minimum object size to keep (pixels).

required
min_object_bbox_size int

Minimum object bounding box size to keep (pixels^2).

required

Returns:

Type Description
dict[int, GrainCrop]

Dictionary of grain crops with objects too small to process removed.

Source code in topostats\grains.py
@staticmethod
def graincrops_remove_objects_too_small_to_process(
    graincrops: dict[int, GrainCrop],
    min_object_size: int,
    min_object_bbox_size: int,
) -> dict[int, GrainCrop]:
    """
    Remove objects that are too small to process from each class of the grain crops.

    Parameters
    ----------
    graincrops : dict[int, GrainCrop]
        Dictionary of grain crops.
    min_object_size : int
        Minimum object size to keep (pixels).
    min_object_bbox_size : int
        Minimum object bounding box size to keep (pixels^2).

    Returns
    -------
    dict[int, GrainCrop]
        Dictionary of grain crops with objects too small to process removed.
    """
    for _grain_number, graincrop in graincrops.items():
        # Iterate over the classes
        for class_index in range(1, graincrop.mask.shape[2]):
            # Get the binary mask for the class
            class_mask = graincrop.mask[:, :, class_index]

            # Label the regions
            labelled_regions = Grains.label_regions(class_mask)
            region_properties = Grains.get_region_properties(labelled_regions)

            # Iterate over the regions
            for region in region_properties:
                # Get the region mask
                region_mask = labelled_regions == region.label

                # Check the region size
                if (
                    region.area < min_object_size
                    or (region.bbox[2] - region.bbox[0]) < min_object_bbox_size
                    or (region.bbox[3] - region.bbox[1]) < min_object_bbox_size
                ):
                    # Remove the region from the class
                    graincrop.mask[:, :, class_index] = np.where(
                        region_mask,
                        0,
                        graincrop.mask[:, :, class_index],
                    )

        # Update the background class
        graincrop.mask = Grains.update_background_class(graincrop.mask)

    return graincrops

graincrops_update_background_class(graincrops: dict[int, GrainCrop]) -> dict[int, GrainCrop] staticmethod

Update the background class in the grain crops.

Parameters:

Name Type Description Default
graincrops dict[int, GrainCrop]

Dictionary of grain crops.

required

Returns:

Type Description
dict[int, GrainCrop]

Dictionary of grain crops with updated background class.

Source code in topostats\grains.py
@staticmethod
def graincrops_update_background_class(
    graincrops: dict[int, GrainCrop],
) -> dict[int, GrainCrop]:
    """
    Update the background class in the grain crops.

    Parameters
    ----------
    graincrops : dict[int, GrainCrop]
        Dictionary of grain crops.

    Returns
    -------
    dict[int, GrainCrop]
        Dictionary of grain crops with updated background class.
    """
    for _grain_number, graincrop in graincrops.items():
        graincrop.mask = Grains.update_background_class(graincrop.mask)

    return graincrops

improve_grain_segmentation_unet(graincrops: dict[int, GrainCrop], filename: str, direction: str, unet_config: dict[str, str | int | float | tuple[int | None, int, int, int] | None]) -> dict[int, GrainCrop] staticmethod

Use a UNet model to re-segment existing grains to improve their accuracy.

Parameters:

Name Type Description Default
graincrops dict[int, GrainCrop]

Dictionary of grain crops.

required
filename str

File being processed (used in logging).

required
direction str

Direction of threshold for which bounding boxes are being calculated.

required
unet_config dict[str, str | int | float | tuple[int | None, int, int, int] | None]

Configuration for the UNet model. model_path: str Path to the UNet model. grain_crop_padding: int Padding to add to the bounding box of the grain before cropping. upper_norm_bound: float Upper bound for normalising the image. lower_norm_bound: float Lower bound for normalising the image. confidence: float Confidence threshold for the UNet model. Smaller is more generous, larger is more strict.

required

Returns:

Type Description
dict[int, GrainCrop]

Dictionary of (hopefully) improved grain crops.

Source code in topostats\grains.py
@staticmethod
def improve_grain_segmentation_unet(
    graincrops: dict[int, GrainCrop],
    filename: str,
    direction: str,
    unet_config: dict[str, str | int | float | tuple[int | None, int, int, int] | None],
) -> dict[int, GrainCrop]:
    """
    Use a UNet model to re-segment existing grains to improve their accuracy.

    Parameters
    ----------
    graincrops : dict[int, GrainCrop]
        Dictionary of grain crops.
    filename : str
        File being processed (used in logging).
    direction : str
        Direction of threshold for which bounding boxes are being calculated.
    unet_config : dict[str, str | int | float | tuple[int | None, int, int, int] | None]
        Configuration for the UNet model.
        model_path: str
            Path to the UNet model.
        grain_crop_padding: int
            Padding to add to the bounding box of the grain before cropping.
        upper_norm_bound: float
            Upper bound for normalising the image.
        lower_norm_bound: float
            Lower bound for normalising the image.
        confidence: float
            Confidence threshold for the UNet model. Smaller is more generous, larger is more strict.

    Returns
    -------
    dict[int, GrainCrop]
        Dictionary of (hopefully) improved grain crops.
    """
    LOGGER.debug(f"[{filename}] : Running UNet model on {direction} grains")

    # When debugging, you might find that the custom_objects are incorrect. This is entirely based on what the model used
    # for its loss during training and so this will need to be changed a lot.
    # Once the group has gotten used to training models, this can be made configurable, but currently it's too changeable.
    # unet_model = keras.models.load_model(
    #     self.unet_config["model_path"], custom_objects={"dice_loss": dice_loss, "iou_loss": iou_loss}
    # )
    # You may also get an error referencing a "group_1" parameter, this is discussed in this issue:
    # https://github.com/keras-team/keras/issues/19441 which also has an experimental fix that we can try but
    # I haven't tested it yet.

    try:
        unet_model = keras.models.load_model(
            unet_config["model_path"], custom_objects={"mean_iou": mean_iou, "iou_loss": iou_loss}, compile=False
        )
    except Exception as e:
        LOGGER.debug(f"Python executable: {sys.executable}")
        LOGGER.debug(f"Keras version: {keras.__version__}")
        LOGGER.debug(f"Model path: {unet_config['model_path']}")
        raise e

    # unet_model = keras.models.load_model(unet_config["model_path"], custom_objects={"mean_iou": mean_iou})
    LOGGER.debug(f"Output shape of UNet model: {unet_model.output_shape}")

    new_graincrops: dict[int, GrainCrop] = {}
    num_empty_removed_grains = 0
    for grain_number, graincrop in graincrops.items():
        LOGGER.debug(f"Unet predicting mask for grain {grain_number} of {len(graincrops)}")
        # Run the UNet on the region. This is allowed to be a single class
        # as we can add a background class afterwards if needed.
        # Remember that this region is cropped from the original image, so it's not
        # the same size as the original image.
        predicted_mask = predict_unet(
            image=graincrop.image,
            model=unet_model,
            confidence=unet_config["confidence"],
            model_input_shape=unet_model.input_shape,
            upper_norm_bound=unet_config["upper_norm_bound"],
            lower_norm_bound=unet_config["lower_norm_bound"],
        )
        assert len(predicted_mask.shape) == 3
        LOGGER.debug(f"Predicted mask shape: {predicted_mask.shape}")

        if unet_config["remove_disconnected_grains"]:
            # Remove grains that are not connected to the original grain
            original_grain_mask = graincrop.mask
            predicted_mask = Grains.remove_disconnected_grains(
                original_grain_tensor=original_grain_mask,
                predicted_grain_tensor=predicted_mask,
            )

        # Check if all of the non-background classes are empty
        if np.sum(predicted_mask[:, :, 1:]) == 0:
            num_empty_removed_grains += 1
        else:
            # @ns-rse 2025-10-14 - do we need to instantiate a new instance here? I don't think we do as
            #                      we have setter methods so could just update the .mask attribute in
            #                      place (could maybe set it above?)
            # graincrop.mask = predicted_mask
            new_graincrops[grain_number] = GrainCrop(
                image=graincrop.image,
                mask=predicted_mask,
                padding=graincrop.padding,
                bbox=graincrop.bbox,
                pixel_to_nm_scaling=graincrop.pixel_to_nm_scaling,
                filename=graincrop.filename,
                height_profiles=graincrop.height_profiles,
                stats=graincrop.stats,
                disordered_trace=graincrop.disordered_trace,
                nodes=graincrop.nodes,
                ordered_trace=graincrop.ordered_trace,
                threshold_method=graincrop.threshold_method,
                thresholds=graincrop.thresholds,
            )

    LOGGER.debug(f"Number of empty removed grains: {num_empty_removed_grains}")

    return new_graincrops

keep_largest_labelled_region(labelled_image: npt.NDArray[np.int32]) -> npt.NDArray[np.bool_] staticmethod

Keep only the largest region in a labelled image.

Parameters:

Name Type Description Default
labelled_image NDArray

2-D Numpy array of labelled regions.

required

Returns:

Type Description
NDArray

2-D Numpy boolean array of labelled regions with only the largest region.

Source code in topostats\grains.py
@staticmethod
def keep_largest_labelled_region(
    labelled_image: npt.NDArray[np.int32],
) -> npt.NDArray[np.bool_]:
    """
    Keep only the largest region in a labelled image.

    Parameters
    ----------
    labelled_image : npt.NDArray
        2-D Numpy array of labelled regions.

    Returns
    -------
    npt.NDArray
        2-D Numpy boolean array of labelled regions with only the largest region.
    """
    # Check if there are any labelled regions
    if labelled_image.max() == 0:
        return np.zeros_like(labelled_image).astype(np.bool_)
    # Get the sizes of the regions
    sizes = np.array([(labelled_image == label).sum() for label in range(1, labelled_image.max() + 1)])
    # Keep only the largest region
    return np.where(labelled_image == sizes.argmax() + 1, labelled_image, 0).astype(bool)

keep_largest_labelled_region_classes(single_grain_mask_tensor: npt.NDArray, keep_largest_labelled_regions_classes: list[int] | None) -> npt.NDArray staticmethod

Keep only the largest region in specific classes.

Parameters:

Name Type Description Default
single_grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required
keep_largest_labelled_regions_classes list[int]

List of classes to keep only the largest region.

required

Returns:

Type Description
NDArray

3-D Numpy array of the grain mask tensor with only the largest regions in specific classes.

Source code in topostats\grains.py
@staticmethod
def keep_largest_labelled_region_classes(
    single_grain_mask_tensor: npt.NDArray,
    keep_largest_labelled_regions_classes: list[int] | None,
) -> npt.NDArray:
    """
    Keep only the largest region in specific classes.

    Parameters
    ----------
    single_grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.
    keep_largest_labelled_regions_classes : list[int]
        List of classes to keep only the largest region.

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the grain mask tensor with only the largest regions in specific classes.
    """
    if keep_largest_labelled_regions_classes is None:
        return single_grain_mask_tensor

    # Iterate over the classes
    for class_index in keep_largest_labelled_regions_classes:
        # Get the binary mask for the class
        class_mask = single_grain_mask_tensor[:, :, class_index]

        # Skip if no regions
        if np.max(class_mask) == 0:
            continue

        # Label the regions
        labelled_regions = Grains.label_regions(class_mask)
        # Get the region properties
        region_properties = Grains.get_region_properties(labelled_regions)
        # Get the region areas
        region_areas = [region.area for region in region_properties]
        # Keep only the largest region
        largest_region = region_properties[np.argmax(region_areas)]
        class_mask_largest_only = np.where(labelled_regions == largest_region.label, labelled_regions, 0)
        # Update the tensor
        single_grain_mask_tensor[:, :, class_index] = class_mask_largest_only.astype(bool)

    # Update the background class
    return Grains.update_background_class(single_grain_mask_tensor)

label_regions(image: npt.NDArray, background: int = 0) -> npt.NDArray staticmethod

Label regions.

This method is used twice, once prior to removal of small regions and again afterwards which is why an image must be supplied rather than using 'self'.

Parameters:

Name Type Description Default
image NDArray

2-D Numpy array of image.

required
background int

Value used to indicate background of image. Default = 0.

0

Returns:

Type Description
NDArray

2-D Numpy array of image with regions numbered.

Source code in topostats\grains.py
@staticmethod
def label_regions(image: npt.NDArray, background: int = 0) -> npt.NDArray:
    """
    Label regions.

    This method is used twice, once prior to removal of small regions and again afterwards which is why an image
    must be supplied rather than using 'self'.

    Parameters
    ----------
    image : npt.NDArray
        2-D Numpy array of image.
    background : int
        Value used to indicate background of image. Default = 0.

    Returns
    -------
    npt.NDArray
        2-D Numpy array of image with regions numbered.
    """
    return morphology.label(image, background)

merge_classes(grain_mask_tensor: npt.NDArray, classes_to_merge: list[list[int]] | None) -> npt.NDArray staticmethod

Merge classes in a grain mask tensor and add them to the grain tensor.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required
classes_to_merge list | None

List of tuples for classes to merge, can be any number of classes.

required

Returns:

Type Description
NDArray

3-D Numpy array of the grain mask tensor with classes merged.

Source code in topostats\grains.py
@staticmethod
def merge_classes(
    grain_mask_tensor: npt.NDArray,
    classes_to_merge: list[list[int]] | None,
) -> npt.NDArray:
    """
    Merge classes in a grain mask tensor and add them to the grain tensor.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.
    classes_to_merge : list | None
        List of tuples for classes to merge, can be any number of classes.

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the grain mask tensor with classes merged.
    """
    if classes_to_merge is None:
        return grain_mask_tensor
    # For each set of classes to merge:
    for classes in classes_to_merge:
        # Get the binary masks for all the classes
        class_masks = [grain_mask_tensor[:, :, class_index] for class_index in classes]
        # Combine the masks
        combined_mask = np.logical_or.reduce(class_masks)

        # Add new class to the grain tensor with the combined mask
        grain_mask_tensor = np.dstack([grain_mask_tensor, combined_mask])

    return grain_mask_tensor.astype(bool)

multi_class_thresholding(image: npt.NDArray, thresholds: list[float], threshold_direction: str, image_name: str) -> npt.NDArray[np.bool_] staticmethod

Perform multi-class thresholding on an image to obtain a mask tensor.

Parameters:

Name Type Description Default
image NDArray

2-D Numpy array of image.

required
thresholds list[float]

List of thresholds for each class.

required
threshold_direction str

Direction for which the threshold is applied.

required
image_name str

Name of the image being processed (used in logging).

required

Returns:

Type Description
NDArray

WxHxC Numpy array of the mask tensor.

Source code in topostats\grains.py
@staticmethod
def multi_class_thresholding(
    image: npt.NDArray,
    thresholds: list[float],
    threshold_direction: str,
    image_name: str,
) -> npt.NDArray[np.bool_]:
    """
    Perform multi-class thresholding on an image to obtain a mask tensor.

    Parameters
    ----------
    image : npt.NDArray
        2-D Numpy array of image.
    thresholds : list[float]
        List of thresholds for each class.
    threshold_direction : str
        Direction for which the threshold is applied.
    image_name : str
        Name of the image being processed (used in logging).

    Returns
    -------
    npt.NDArray
        WxHxC Numpy array of the mask tensor.
    """
    traditional_full_mask_tensor = np.zeros(
        (image.shape[0], image.shape[1], len(thresholds) + 1), dtype=np.int32
    ).astype(bool)
    for threshold_index, direction_threshold in enumerate(thresholds):
        # mask the grains
        traditional_full_mask_tensor[:, :, threshold_index + 1] = _get_mask(
            image=image,
            thresh=direction_threshold,
            threshold_direction=threshold_direction,
            img_name=image_name,
        ).astype(bool)
    # Update background class in the full mask tensor
    return Grains.update_background_class(traditional_full_mask_tensor)

remove_disconnected_grains(original_grain_tensor: npt.NDArray, predicted_grain_tensor: npt.NDArray) staticmethod

Remove grains that are not connected to the original grains.

Parameters:

Name Type Description Default
original_grain_tensor NDArray

3-D Numpy array of the original grain tensor.

required
predicted_grain_tensor NDArray

3-D Numpy array of the predicted grain tensor.

required

Returns:

Type Description
NDArray

3-D Numpy array of the predicted grain tensor with grains not connected to the original grains removed.

Source code in topostats\grains.py
@staticmethod
def remove_disconnected_grains(
    original_grain_tensor: npt.NDArray,
    predicted_grain_tensor: npt.NDArray,
):
    """
    Remove grains that are not connected to the original grains.

    Parameters
    ----------
    original_grain_tensor : npt.NDArray
        3-D Numpy array of the original grain tensor.
    predicted_grain_tensor : npt.NDArray
        3-D Numpy array of the predicted grain tensor.

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the predicted grain tensor with grains not connected to the original grains removed.
    """
    # flatten the masks and compare connected components
    original_mask_flattened = Grains.flatten_multi_class_tensor(original_grain_tensor)
    predicted_mask_flattened = Grains.flatten_multi_class_tensor(predicted_grain_tensor)
    # Get the connected components of the original grain mask
    original_mask_flattened_labelled = label(original_mask_flattened)
    predicted_mask_flattened_labelled = label(predicted_mask_flattened)
    # for each region of the predicted mask, check if it overlaps with any of the original mask regions
    # (the original mask is expected to only have one region, but just in case future edits don't follow
    # this assumption, I check all regions)
    predicted_mask_regions = regionprops(predicted_mask_flattened_labelled)
    original_mask_regions = regionprops(original_mask_flattened_labelled)
    # if the predicted mask region doesn't overlap with any of the original mask regions, set it to 0
    for predicted_mask_region in predicted_mask_regions:
        predicted_mask_region_mask = predicted_mask_flattened_labelled == predicted_mask_region.label
        overlap = False
        for original_mask_region in original_mask_regions:
            original_mask_region_mask = original_mask_flattened_labelled == original_mask_region.label
            if np.any(predicted_mask_region_mask & original_mask_region_mask):
                # a region in the flattened original mask shares a pixel with the flattened predicted mask
                overlap = True
                break
        if not overlap:
            # zero the region in all channels of the predicted mask
            for channel in range(1, predicted_grain_tensor.shape[-1]):
                predicted_grain_tensor[predicted_mask_region_mask, channel] = 0

    return predicted_grain_tensor

remove_objects_too_small_to_process(image: npt.NDArray, minimum_size_px: int, minimum_bbox_size_px: int) -> npt.NDArray[np.bool_]

Remove objects whose dimensions in pixels are too small to process.

Parameters:

Name Type Description Default
image NDArray

2-D Numpy array of image.

required
minimum_size_px int

Minimum number of pixels for an object.

required
minimum_bbox_size_px int

Limit for the minimum dimension of an object in pixels. Eg: 5 means the object's bounding box must be at least 5x5.

required

Returns:

Type Description
NDArray

2-D Numpy array of image with objects removed that are too small to process.

Source code in topostats\grains.py
def remove_objects_too_small_to_process(
    self, image: npt.NDArray, minimum_size_px: int, minimum_bbox_size_px: int
) -> npt.NDArray[np.bool_]:
    """
    Remove objects whose dimensions in pixels are too small to process.

    Parameters
    ----------
    image : npt.NDArray
        2-D Numpy array of image.
    minimum_size_px : int
        Minimum number of pixels for an object.
    minimum_bbox_size_px : int
        Limit for the minimum dimension of an object in pixels. Eg: 5 means the object's bounding box must be at
        least 5x5.

    Returns
    -------
    npt.NDArray
        2-D Numpy array of image with objects removed that are too small to process.
    """
    labelled_image = label(image)
    region_properties = self.get_region_properties(labelled_image)
    for region in region_properties:
        # If the number of true pixels in the region is less than the minimum number of pixels, remove the region
        if region.area < minimum_size_px:
            labelled_image[labelled_image == region.label] = 0
        bbox_width = region.bbox[2] - region.bbox[0]
        bbox_height = region.bbox[3] - region.bbox[1]
        # If the minimum dimension of the bounding box is less than the minimum dimension, remove the region
        if min(bbox_width, bbox_height) < minimum_bbox_size_px:
            labelled_image[labelled_image == region.label] = 0

    return labelled_image.astype(bool)

tidy_border_tensor(grain_mask_tensor: npt.NDArray[np.bool_]) -> npt.NDArray[np.bool_] staticmethod

Remove whole grains touching the border.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required

Returns:

Type Description
NDArray

3-D Numpy array of the grain mask tensor with grains touching the border removed.

Source code in topostats\grains.py
@staticmethod
def tidy_border_tensor(grain_mask_tensor: npt.NDArray[np.bool_]) -> npt.NDArray[np.bool_]:
    """
    Remove whole grains touching the border.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the grain mask tensor with grains touching the border removed.
    """
    # flattened_grain_mask_tensor = Grains.flatten_multi_class_tensor(grain_mask_tensor)
    flattened_grain_mask_tensor = flatten_multi_class_tensor(grain_mask_tensor)
    # Find the grains that touch the border then remove them from the full mask tensor
    flattened_grain_mask_tensor_labelled = morphology.label(flattened_grain_mask_tensor)
    flattened_grain_mask_tensor_regionprops = regionprops(flattened_grain_mask_tensor_labelled)
    for region in flattened_grain_mask_tensor_regionprops:
        if (
            region.bbox[0] == 0
            or region.bbox[1] == 0
            or region.bbox[2] == flattened_grain_mask_tensor.shape[0]
            or region.bbox[3] == flattened_grain_mask_tensor.shape[1]
        ):
            # Remove the grain from the full mask tensor
            for class_index in range(1, grain_mask_tensor.shape[2]):
                grain_mask_tensor[:, :, class_index][flattened_grain_mask_tensor_labelled == region.label] = 0

    # return Grains.update_background_class(grain_mask_tensor)
    return update_background_class(grain_mask_tensor)

update_background_class(grain_mask_tensor: npt.NDArray) -> npt.NDArray[np.bool_] staticmethod

Update the background class to reflect the other classes.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required

Returns:

Type Description
NDArray

3-D Numpy array of image tensor with updated background class.

Source code in topostats\grains.py
@staticmethod
def update_background_class(
    grain_mask_tensor: npt.NDArray,
) -> npt.NDArray[np.bool_]:
    """
    Update the background class to reflect the other classes.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.

    Returns
    -------
    npt.NDArray
        3-D Numpy array of image tensor with updated background class.
    """
    flattened_mask = Grains.flatten_multi_class_tensor(grain_mask_tensor)
    new_background = np.where(flattened_mask == 0, 1, 0)
    grain_mask_tensor[:, :, 0] = new_background
    return grain_mask_tensor.astype(bool)

vet_class_connection_points(grain_mask_tensor: npt.NDArray, class_connection_point_thresholds: list[tuple[tuple[int, int], tuple[int, int]]] | None) -> bool staticmethod

Vet the number of connection points between regions in specific classes.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required
class_connection_point_thresholds list[tuple[tuple[int, int], tuple[int, int]]] | None

List of tuples of classes and connection point thresholds. Structure is [(class_pair, (lower, upper))].

required

Returns:

Type Description
bool

True if the grain passes the vetting, False if it fails.

Source code in topostats\grains.py
@staticmethod
def vet_class_connection_points(
    grain_mask_tensor: npt.NDArray,
    class_connection_point_thresholds: list[tuple[tuple[int, int], tuple[int, int]]] | None,
) -> bool:
    """
    Vet the number of connection points between regions in specific classes.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.
    class_connection_point_thresholds : list[tuple[tuple[int, int], tuple[int, int]]] | None
        List of tuples of classes and connection point thresholds. Structure is [(class_pair, (lower, upper))].

    Returns
    -------
    bool
        True if the grain passes the vetting, False if it fails.
    """
    if class_connection_point_thresholds is None:
        return True

    # Iterate over the class pairs
    for class_pair, connection_point_thresholds in class_connection_point_thresholds:
        # Get the connection regions
        num_connection_regions, _, _ = Grains.calculate_region_connection_regions(
            grain_mask_tensor=grain_mask_tensor,
            classes=class_pair,
        )
        # Check the number of connection regions against the thresholds
        lower_threshold, upper_threshold = connection_point_thresholds
        if lower_threshold is not None:
            if num_connection_regions < lower_threshold:
                return False
        if upper_threshold is not None:
            if num_connection_regions > upper_threshold:
                return False

    return True

vet_class_sizes_single_grain(single_grain_mask_tensor: npt.NDArray, pixel_to_nm_scaling: float, class_size_thresholds: list[tuple[int, int, int]] | None) -> tuple[npt.NDArray, bool] staticmethod

Remove regions of particular classes based on size thresholds.

Regions of classes that are too large or small may need to be removed for many reasons (eg removing noise erroneously detected by the model or larger-than-expected molecules that are obviously erroneous), this method allows for the removal of these regions based on size thresholds.

Parameters:

Name Type Description Default
single_grain_mask_tensor NDArray

3-D Numpy array of the mask tensor.

required
pixel_to_nm_scaling float

Scaling of pixels to nanometres.

required
class_size_thresholds list[list[int, int, int]] | None

List of class size thresholds. Structure is [(class_index, lower, upper)].

required

Returns:

Type Description
NDArray

3-D Numpy array of the mask tensor with grains removed based on size thresholds.

bool

True if the grain passes the vetting, False if it fails.

Source code in topostats\grains.py
@staticmethod
def vet_class_sizes_single_grain(
    single_grain_mask_tensor: npt.NDArray,
    pixel_to_nm_scaling: float,
    class_size_thresholds: list[tuple[int, int, int]] | None,
) -> tuple[npt.NDArray, bool]:
    """
    Remove regions of particular classes based on size thresholds.

    Regions of classes that are too large or small may need to be removed for many reasons (eg removing noise
    erroneously detected by the model or larger-than-expected molecules that are obviously erroneous), this method
    allows for the removal of these regions based on size thresholds.

    Parameters
    ----------
    single_grain_mask_tensor : npt.NDArray
        3-D Numpy array of the mask tensor.
    pixel_to_nm_scaling : float
        Scaling of pixels to nanometres.
    class_size_thresholds : list[list[int, int, int]] | None
        List of class size thresholds. Structure is [(class_index, lower, upper)].

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the mask tensor with grains removed based on size thresholds.
    bool
        True if the grain passes the vetting, False if it fails.
    """
    if class_size_thresholds is None:
        return single_grain_mask_tensor, True

    # Iterate over the classes and check the sizes
    for class_index in range(1, single_grain_mask_tensor.shape[2]):
        class_size = np.sum(single_grain_mask_tensor[:, :, class_index]) * pixel_to_nm_scaling**2
        # Check the size against the thresholds

        classes_to_vet = [vetting_criteria[0] for vetting_criteria in class_size_thresholds]

        if class_index not in classes_to_vet:
            continue

        lower_threshold, upper_threshold = [
            vetting_criteria[1:] for vetting_criteria in class_size_thresholds if vetting_criteria[0] == class_index
        ][0]

        if lower_threshold is not None:
            if class_size < lower_threshold:
                # Return empty tensor
                empty_crop_tensor = np.zeros_like(single_grain_mask_tensor)
                # Fill the background class with 1s
                empty_crop_tensor[:, :, 0] = 1
                return empty_crop_tensor, False
        if upper_threshold is not None:
            if class_size > upper_threshold:
                # Return empty tensor
                empty_crop_tensor = np.zeros_like(single_grain_mask_tensor)
                # Fill the background class with 1s
                empty_crop_tensor[:, :, 0] = 1
                return empty_crop_tensor, False

    return single_grain_mask_tensor, True

vet_grains(graincrops: dict[int, GrainCrop], whole_grain_size_thresholds: tuple[float, float] | None, class_conversion_size_thresholds: list[tuple[tuple[int, int, int], tuple[int, int]]] | None, class_size_thresholds: list[tuple[int, int, int]] | None, class_region_number_thresholds: list[tuple[int, int, int]] | None, nearby_conversion_classes_to_convert: list[tuple[int, int]] | None, class_touching_threshold: int, keep_largest_labelled_regions_classes: list[int] | None, class_connection_point_thresholds: list[tuple[tuple[int, int], tuple[int, int]]] | None) -> dict[int, GrainCrop] staticmethod

Vet grains in a grain mask tensor based on a variety of criteria.

Parameters:

Name Type Description Default
graincrops dict[int, GrainCrop]

Dictionary of grain crops.

required
whole_grain_size_thresholds tuple

Tuple of whole grain size thresholds. Structure is (lower, upper).

required
class_conversion_size_thresholds list

List of class conversion size thresholds. Structure is [(class_index, class_to_convert_to_if_too_small, class_to_convert_to_if_too_big), (lower_threshold, upper_threshold)].

required
class_size_thresholds list

List of class size thresholds. Structure is [(class_index, lower, upper)].

required
class_region_number_thresholds list

List of class region number thresholds. Structure is [(class_index, lower, upper)].

required
nearby_conversion_classes_to_convert list

List of tuples of classes to convert. Structure is [(class_a, class_b)].

required
class_touching_threshold int

Number of dilation passes to do to determine class A connectivity with class B.

required
keep_largest_labelled_regions_classes list

List of classes to keep only the largest region.

required
class_connection_point_thresholds list

List of tuples of classes and connection point thresholds. Structure is [(class_pair, (lower, upper))].

required

Returns:

Type Description
dict[int, GrainCrop]

Dictionary of grain crops that passed the vetting.

Source code in topostats\grains.py
@staticmethod
def vet_grains(
    graincrops: dict[int, GrainCrop],
    whole_grain_size_thresholds: tuple[float, float] | None,
    class_conversion_size_thresholds: list[tuple[tuple[int, int, int], tuple[int, int]]] | None,
    class_size_thresholds: list[tuple[int, int, int]] | None,
    class_region_number_thresholds: list[tuple[int, int, int]] | None,
    nearby_conversion_classes_to_convert: list[tuple[int, int]] | None,
    class_touching_threshold: int,
    keep_largest_labelled_regions_classes: list[int] | None,
    class_connection_point_thresholds: list[tuple[tuple[int, int], tuple[int, int]]] | None,
) -> dict[int, GrainCrop]:
    """
    Vet grains in a grain mask tensor based on a variety of criteria.

    Parameters
    ----------
    graincrops : dict[int, GrainCrop]
        Dictionary of grain crops.
    whole_grain_size_thresholds : tuple
        Tuple of whole grain size thresholds. Structure is (lower, upper).
    class_conversion_size_thresholds : list
        List of class conversion size thresholds. Structure is [(class_index, class_to_convert_to_if_too_small,
        class_to_convert_to_if_too_big), (lower_threshold, upper_threshold)].
    class_size_thresholds : list
        List of class size thresholds. Structure is [(class_index, lower, upper)].
    class_region_number_thresholds : list
        List of class region number thresholds. Structure is [(class_index, lower, upper)].
    nearby_conversion_classes_to_convert : list
        List of tuples of classes to convert. Structure is [(class_a, class_b)].
    class_touching_threshold : int
        Number of dilation passes to do to determine class A connectivity with class B.
    keep_largest_labelled_regions_classes : list
        List of classes to keep only the largest region.
    class_connection_point_thresholds : list
        List of tuples of classes and connection point thresholds. Structure is [(class_pair, (lower, upper))].

    Returns
    -------
    dict[int, GrainCrop]
        Dictionary of grain crops that passed the vetting.
    """
    passed_graincrops: dict[int, GrainCrop] = {}

    # Iterate over the grain crops
    for grain_number, graincrop in graincrops.items():
        single_grain_mask_tensor = graincrop.mask
        pixel_to_nm_scaling = graincrop.pixel_to_nm_scaling

        # Vet whole grain size
        if not Grains.vet_whole_grain_size(
            grain_mask_tensor=single_grain_mask_tensor,
            pixel_to_nm_scaling=pixel_to_nm_scaling,
            whole_grain_size_thresholds=whole_grain_size_thresholds,
        ):
            continue

        # Convert small / big areas to other classes
        single_grain_mask_tensor = Grains.convert_classes_when_too_big_or_small(
            grain_mask_tensor=single_grain_mask_tensor,
            pixel_to_nm_scaling=pixel_to_nm_scaling,
            class_conversion_size_thresholds=class_conversion_size_thresholds,
        )

        # Vet number of regions (foreground and background)
        _, passed = Grains.vet_numbers_of_regions_single_grain(
            grain_mask_tensor=single_grain_mask_tensor,
            class_region_number_thresholds=class_region_number_thresholds,
        )
        if not passed:
            continue

        # Vet size of regions (foreground and background)
        _, passed = Grains.vet_class_sizes_single_grain(
            single_grain_mask_tensor=single_grain_mask_tensor,
            pixel_to_nm_scaling=pixel_to_nm_scaling,
            class_size_thresholds=class_size_thresholds,
        )
        if not passed:
            continue

        # Turn all but largest region of class A into class B provided that the class A region touched a class B
        # region
        converted_single_grain_mask_tensor = Grains.convert_classes_to_nearby_classes(
            grain_mask_tensor=single_grain_mask_tensor,
            classes_to_convert=nearby_conversion_classes_to_convert,
            class_touching_threshold=class_touching_threshold,
        )

        # Remove all but largest region in specific classes
        largest_only_single_grain_mask_tensor = Grains.keep_largest_labelled_region_classes(
            single_grain_mask_tensor=converted_single_grain_mask_tensor,
            keep_largest_labelled_regions_classes=keep_largest_labelled_regions_classes,
        )

        # Vet number of connection points between regions in specific classes
        if not Grains.vet_class_connection_points(
            grain_mask_tensor=largest_only_single_grain_mask_tensor,
            class_connection_point_thresholds=class_connection_point_thresholds,
        ):
            continue

        # @ns-rse 2025-10-14 - do we need to instantiate a new instance here? I don't think we do as
        #                      we have setter methods so could just update the .mask attribute in
        #                      place (could perhaps set directly above?)
        # graincrop.mask = largest_only_single_grain_mask_tensor
        # If passed all vetting steps, add to the dictionary of passed grain crops
        passed_graincrops[grain_number] = GrainCrop(
            image=graincrop.image,
            mask=largest_only_single_grain_mask_tensor,
            padding=graincrop.padding,
            bbox=graincrop.bbox,
            pixel_to_nm_scaling=graincrop.pixel_to_nm_scaling,
            filename=graincrop.filename,
            height_profiles=graincrop.height_profiles,
            stats=graincrop.stats,
            disordered_trace=graincrop.disordered_trace,
            nodes=graincrop.nodes,
            ordered_trace=graincrop.ordered_trace,
            threshold_method=graincrop.threshold_method,
            thresholds=graincrop.thresholds,
        )

    return passed_graincrops

vet_numbers_of_regions_single_grain(grain_mask_tensor: npt.NDArray, class_region_number_thresholds: list[tuple[int, int, int]] | None) -> tuple[npt.NDArray, bool] staticmethod

Check if the number of regions of different classes for a single grain is within thresholds.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor, should be of only one grain.

required
class_region_number_thresholds list[list[int, int, int]]

List of class region number thresholds. Structure is [(class_index, lower, upper)].

required

Returns:

Type Description
NDArray

3-D Numpy array of the grain mask tensor with grains removed based on region number thresholds.

bool

True if the grain passes the vetting, False if it fails.

Source code in topostats\grains.py
@staticmethod
def vet_numbers_of_regions_single_grain(
    grain_mask_tensor: npt.NDArray,
    class_region_number_thresholds: list[tuple[int, int, int]] | None,
) -> tuple[npt.NDArray, bool]:
    """
    Check if the number of regions of different classes for a single grain is within thresholds.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor, should be of only one grain.
    class_region_number_thresholds : list[list[int, int, int]]
        List of class region number thresholds. Structure is [(class_index, lower, upper)].

    Returns
    -------
    npt.NDArray
        3-D Numpy array of the grain mask tensor with grains removed based on region number thresholds.
    bool
        True if the grain passes the vetting, False if it fails.
    """
    if class_region_number_thresholds is None:
        return grain_mask_tensor, True

    # Iterate over the classes and check the number of regions
    for class_index in range(1, grain_mask_tensor.shape[2]):
        # Get the number of regions
        class_labelled_regions = Grains.label_regions(grain_mask_tensor[:, :, class_index])
        number_of_regions = np.unique(class_labelled_regions).shape[0] - 1
        # Check the number of regions against the thresholds, skip if no thresholds provided
        # Get the classes we are trying to vet (the first element of each tuple)
        classes_to_vet = [vetting_criteria[0] for vetting_criteria in class_region_number_thresholds]

        if class_index not in classes_to_vet:
            continue

        lower_threshold, upper_threshold = [
            vetting_criteria[1:]
            for vetting_criteria in class_region_number_thresholds
            if vetting_criteria[0] == class_index
        ][0]

        # Check the number of regions against the thresholds
        if lower_threshold is not None:
            if number_of_regions < lower_threshold:
                # Return empty tensor
                empty_crop_tensor = np.zeros_like(grain_mask_tensor)
                # Fill the background class with 1s
                empty_crop_tensor[:, :, 0] = 1
                return empty_crop_tensor, False
        if upper_threshold is not None:
            if number_of_regions > upper_threshold:
                # Return empty tensor
                empty_crop_tensor = np.zeros_like(grain_mask_tensor)
                # Fill the background class with 1s
                empty_crop_tensor[:, :, 0] = 1
                return empty_crop_tensor, False

    return grain_mask_tensor, True

vet_whole_grain_size(grain_mask_tensor: npt.NDArray, pixel_to_nm_scaling: float, whole_grain_size_thresholds: tuple[float, float] | None) -> bool staticmethod

Vet the size of the whole grain based on size thresholds.

Parameters:

Name Type Description Default
grain_mask_tensor NDArray

3-D Numpy array of the grain mask tensor.

required
pixel_to_nm_scaling float

Scaling of pixels to nanometres.

required
whole_grain_size_thresholds tuple

Tuple of whole grain size thresholds. Structure is (lower, upper).

required

Returns:

Type Description
bool

True if the grain size is within the area thresholds, False if it fails.

Source code in topostats\grains.py
@staticmethod
def vet_whole_grain_size(
    grain_mask_tensor: npt.NDArray,
    pixel_to_nm_scaling: float,
    whole_grain_size_thresholds: tuple[float, float] | None,
) -> bool:
    """
    Vet the size of the whole grain based on size thresholds.

    Parameters
    ----------
    grain_mask_tensor : npt.NDArray
        3-D Numpy array of the grain mask tensor.
    pixel_to_nm_scaling : float
        Scaling of pixels to nanometres.
    whole_grain_size_thresholds : tuple
        Tuple of whole grain size thresholds. Structure is (lower, upper).

    Returns
    -------
    bool
        True if the grain size is within the area thresholds, False if it fails.
    """
    if whole_grain_size_thresholds is None:
        return True

    whole_grain_size_nm = (
        Grains.flatten_multi_class_tensor(grain_mask_tensor).astype(bool).sum() * pixel_to_nm_scaling**2
    )

    lower_threshold, upper_threshold = whole_grain_size_thresholds
    if lower_threshold is not None:
        if whole_grain_size_nm < lower_threshold:
            return False
    if upper_threshold is not None:
        if whole_grain_size_nm > upper_threshold:
            return False

    return True

validate_full_mask_tensor_shape(array: npt.NDArray[np.bool_]) -> npt.NDArray[np.bool_]

Validate the shape of the full mask tensor.

Parameters:

Name Type Description Default
array NDArray

Numpy array to validate.

required

Returns:

Type Description
NDArray

Numpy array if valid.

Source code in topostats\grains.py
def validate_full_mask_tensor_shape(array: npt.NDArray[np.bool_]) -> npt.NDArray[np.bool_]:
    """
    Validate the shape of the full mask tensor.

    Parameters
    ----------
    array : npt.NDArray
        Numpy array to validate.

    Returns
    -------
    npt.NDArray
        Numpy array if valid.
    """
    if len(array.shape) != 3 or array.shape[2] < 2:
        raise ValueError(f"Full mask tensor must be WxHxC with C >= 2 but has shape {array.shape}")
    return array