pymeshmetrics 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,163 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
163
+ output/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,23 @@
1
+ """Deprecated alias for the ``meshmetrics`` package.
2
+
3
+ Kept as a single module (not a package directory) so it can coexist with
4
+ ``meshmetrics/`` on case-insensitive filesystems (Windows, macOS).
5
+ """
6
+
7
+ import sys
8
+ import warnings
9
+
10
+ import meshmetrics
11
+ from meshmetrics.metrics import * # noqa: F401,F403 (names the old package exposed)
12
+ from meshmetrics import * # noqa: F401,F403
13
+ from meshmetrics import metrics, utils
14
+
15
+ warnings.warn(
16
+ "`import MeshMetrics` is deprecated, use `import meshmetrics` instead.",
17
+ DeprecationWarning,
18
+ stacklevel=2,
19
+ )
20
+
21
+ # keep `from MeshMetrics.utils import ...` / `MeshMetrics.metrics` working
22
+ sys.modules[__name__ + ".metrics"] = metrics
23
+ sys.modules[__name__ + ".utils"] = utils
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.5
2
+ Name: pymeshmetrics
3
+ Version: 1.0.0
4
+ Summary: Library to compute distance-based performance metrics for image segmentation tasks.
5
+ Project-URL: Homepage, https://github.com/gasperpodobnik/meshmetrics
6
+ Project-URL: Paper, https://doi.org/10.48550/arXiv.2509.05670
7
+ Author: Gasper Podobnik, Tomaz Vrtovec
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.9
11
+ Requires-Dist: numpy
12
+ Requires-Dist: simpleitk
13
+ Requires-Dist: simpleitkutilities
14
+ Requires-Dist: vtk>=9.3
15
+ Provides-Extra: all
16
+ Requires-Dist: meshio; extra == 'all'
17
+ Requires-Dist: trimesh; extra == 'all'
18
+ Provides-Extra: meshio
19
+ Requires-Dist: meshio; extra == 'meshio'
20
+ Provides-Extra: trimesh
21
+ Requires-Dist: trimesh; extra == 'trimesh'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # MeshMetrics
25
+ > Official Python-based implementation of `MeshMetrics` from [_MeshMetrics: A Precise Implementation of Distance-Based Image Segmentation Metrics_](https://doi.org/10.48550/arXiv.2509.05670), motivated by the implementation pitfalls identified in [_Understanding Implementation Pitfalls of Distance-Based Metrics for Image Segmentation_](https://doi.org/10.48550/arXiv.2410.02630) and [_HDilemma: Are Open-Source Hausdorff Distance Implementations Equivalent?_](https://link.springer.com/chapter/10.1007/978-3-031-72114-4_30)
26
+
27
+ ## About
28
+ `MeshMetrics` is a precise, mesh-based implementation of widely used distance-based metrics for evaluating image segmentation tasks. By leveraging mesh representations of segmentation, `MeshMetrics` ensures precision in distance and boundary element size calculations. For a detailed description and a comparison with other open-source tools supporting distance-based metric calculations, see [our paper](https://doi.org/10.48550/arXiv.2509.05670).
29
+
30
+ The library supports both 2D and 3D data and works seamlessly with multiple segmentation formats (`numpy.ndarray`, `SimpleITK.Image`, `vtk.vtkPolyData`, `trimesh.Trimesh`, and `meshio.Mesh`). It also allows mixing representations between reference and predicted segmentations - for example, one input can be a mask image (`SimpleITK.Image`), while the other is a surface mesh (`vtk.vtkPolyData`/`trimesh.Trimesh`/`meshio.Mesh`). See the *Advanced usage* section in [`examples.ipynb`](examples.ipynb) for more details.
31
+
32
+ Available distance-based metrics:
33
+ - **Hausdorff distance** (HD) with $p$-th **percentile variants** (HD<sub>p</sub>)
34
+ - **Mean average surface distance** (MASD)
35
+ - **Average symmetric surface distance** (ASSD)
36
+ - **Normalized surface distance** (NSD)
37
+ - **Boundary intersection over union** (BIoU)
38
+
39
+ For convenience, `MeshMetrics` also includes implementations of the **Dice similarity coefficient** (DSC) and **intersection over union** (IoU).
40
+
41
+ ![overview](./data/paper_overview.png)
42
+
43
+ If you use `MeshMetrics` in your work, please cite:
44
+ ```
45
+ Podobnik, G., & Vrtovec, T. (2025). MeshMetrics: A Precise Implementation of Distance-Based Image Segmentation Metrics. arXiv preprint arXiv:2509.05670.
46
+ Podobnik, G., & Vrtovec, T. (2025). Understanding Implementation Pitfalls of Distance-Based Metrics for Image Segmentation. arXiv preprint arXiv:2410.02630.
47
+ ```
48
+
49
+ ## Installation
50
+ ### System Dependencies
51
+ This package requires `libxrender1` to be installed on your system. Install it via:
52
+ ```bash
53
+ sudo apt update && sudo apt install -y libxrender1
54
+ ```
55
+
56
+ ### Install `meshmetrics` package
57
+ Install from [PyPI](https://pypi.org/project/pymeshmetrics/) with pip, or add it to your project with [uv](https://docs.astral.sh/uv/):
58
+ ```bash
59
+ pip install pymeshmetrics
60
+ uv add pymeshmetrics
61
+ ```
62
+ The package is published as `pymeshmetrics` and imported as `meshmetrics`:
63
+ ```python
64
+ import meshmetrics
65
+ ```
66
+ Optional support for `trimesh` and `meshio` inputs is available via extras: `pip install "pymeshmetrics[all]"` (or `[trimesh]` / `[meshio]`).
67
+
68
+ To install the latest development version from GitHub:
69
+ ```bash
70
+ pip install git+https://github.com/gasperpodobnik/meshmetrics.git
71
+ ```
72
+
73
+ ### Development
74
+ Clone the repository and create the environment (including dev tools and all extras):
75
+ ```bash
76
+ git clone https://github.com/gasperpodobnik/meshmetrics.git
77
+ cd meshmetrics
78
+ uv sync --all-extras
79
+ uv run pytest
80
+ ```
81
+
82
+ ## Usage
83
+ ### Quick start
84
+ Compute all metrics for a pair of segmentations in one call:
85
+ ```python
86
+ import SimpleITK as sitk
87
+ from meshmetrics import compute_metrics
88
+
89
+ ref_sitk = sitk.ReadImage("data/example_3d_ref_mask.nii.gz")
90
+ pred_sitk = sitk.ReadImage("data/example_3d_pred_mask.nii.gz")
91
+
92
+ results = compute_metrics(ref_sitk, pred_sitk, taus=(2.0, 5.0))
93
+ # {'ref_is_empty': False, 'pred_is_empty': False, 'HD_100': ..., 'HD_95': ..., 'MASD': ..., 'ASSD': ...,
94
+ # 'NSD_2.0': ..., 'NSD_5.0': ..., 'BIoU_2.0': ..., 'BIoU_5.0': ..., 'DSC': ..., 'IoU': ...}
95
+ ```
96
+ `taus` are the tolerances (in physical units) for NSD and BIoU; they are application-specific, so NSD and BIoU are only computed when `taus` are given. Use `percentiles` to choose the HD variants (default `(100, 95)`) and `metrics` to select a subset, e.g. `metrics=["hd", "nsd"]`. Inputs can be any of the supported types (see below); numpy arrays and pairs of meshes also need `spacing`.
97
+
98
+ ### Step-by-step
99
+ Simple usage example of `MeshMetrics` for 3D segmentation masks is shown below.
100
+ See [`examples.ipynb`](examples.ipynb) notebook for more examples.
101
+
102
+ ```python
103
+ from pathlib import Path
104
+ import SimpleITK as sitk
105
+ from meshmetrics import DistanceMetrics
106
+
107
+ data_dir = Path("data")
108
+
109
+ # read binary segmentation masks
110
+ ref_sitk = sitk.ReadImage(str(data_dir / "example_3d_ref_mask.nii.gz"))
111
+ pred_sitk = sitk.ReadImage(str(data_dir / "example_3d_pred_mask.nii.gz"))
112
+
113
+ # Set parameters
114
+ percentile = 95 # percentile for HD
115
+ tau = 2.0 # tolerance for NSD and BIoU
116
+
117
+ # Initialize distance metrics class and set inputs
118
+ dist_metrics = DistanceMetrics()
119
+ dist_metrics.set_input(ref=ref_sitk, pred=pred_sitk)
120
+
121
+ # store flags indicating empty masks
122
+ results = {
123
+ "ref_is_empty": dist_metrics.ref_is_empty,
124
+ "pred_is_empty": dist_metrics.pred_is_empty,
125
+ }
126
+ # Hausdorff distance (HD), by default, HD percentile is set to 100 (equivalent to HD)
127
+ results["HD_100"] = dist_metrics.hd()
128
+ # p-th percentile HD (HD_p)
129
+ results[f"HD_{percentile}"] = dist_metrics.hd(percentile=percentile)
130
+ # Mean average surface distance (MASD)
131
+ results["MASD"] = dist_metrics.masd()
132
+ # Average symmetric surface distance (ASSD)
133
+ results["ASSD"] = dist_metrics.assd()
134
+ # Normalized surface distance (NSD) with tau
135
+ results[f"NSD_{tau}"] = dist_metrics.nsd(tau=tau)
136
+ # Boundary intersection over union (BIoU) with tau
137
+ results[f"BIoU_{tau}"] = dist_metrics.biou(tau=tau)
138
+
139
+ # print metric values
140
+ units = {"HD": "mm", "MASD": "mm", "ASSD": "mm", "NSD": "%", "BIoU": "%"}
141
+ for k, v in results.items():
142
+ unit = units.get(k.split("_")[0], "")
143
+ f = 100.0 if unit == "%" else 1.0
144
+ print(f"{k}: {v*f:.2f} {unit}")
145
+
146
+ # ----------------------------------------
147
+ # If using `numpy.ndarray` representations, note that the spacing must be
148
+ # reordered when converting a `SimpleITK.Image` object to a `numpy.ndarray`
149
+ ref_np = sitk.GetArrayFromImage(ref_sitk).astype(bool)
150
+ pred_np = sitk.GetArrayFromImage(pred_sitk).astype(bool)
151
+
152
+ # spacing should resemble the order of numpy array axes
153
+ spacing = ref_sitk.GetSpacing()[::-1]
154
+
155
+ dist_metrics = DistanceMetrics()
156
+ dist_metrics.set_input(ref=ref_np, pred=pred_np, spacing=spacing)
157
+ # ... follow the same procedure as before
158
+ ```
@@ -0,0 +1,135 @@
1
+ # MeshMetrics
2
+ > Official Python-based implementation of `MeshMetrics` from [_MeshMetrics: A Precise Implementation of Distance-Based Image Segmentation Metrics_](https://doi.org/10.48550/arXiv.2509.05670), motivated by the implementation pitfalls identified in [_Understanding Implementation Pitfalls of Distance-Based Metrics for Image Segmentation_](https://doi.org/10.48550/arXiv.2410.02630) and [_HDilemma: Are Open-Source Hausdorff Distance Implementations Equivalent?_](https://link.springer.com/chapter/10.1007/978-3-031-72114-4_30)
3
+
4
+ ## About
5
+ `MeshMetrics` is a precise, mesh-based implementation of widely used distance-based metrics for evaluating image segmentation tasks. By leveraging mesh representations of segmentation, `MeshMetrics` ensures precision in distance and boundary element size calculations. For a detailed description and a comparison with other open-source tools supporting distance-based metric calculations, see [our paper](https://doi.org/10.48550/arXiv.2509.05670).
6
+
7
+ The library supports both 2D and 3D data and works seamlessly with multiple segmentation formats (`numpy.ndarray`, `SimpleITK.Image`, `vtk.vtkPolyData`, `trimesh.Trimesh`, and `meshio.Mesh`). It also allows mixing representations between reference and predicted segmentations - for example, one input can be a mask image (`SimpleITK.Image`), while the other is a surface mesh (`vtk.vtkPolyData`/`trimesh.Trimesh`/`meshio.Mesh`). See the *Advanced usage* section in [`examples.ipynb`](examples.ipynb) for more details.
8
+
9
+ Available distance-based metrics:
10
+ - **Hausdorff distance** (HD) with $p$-th **percentile variants** (HD<sub>p</sub>)
11
+ - **Mean average surface distance** (MASD)
12
+ - **Average symmetric surface distance** (ASSD)
13
+ - **Normalized surface distance** (NSD)
14
+ - **Boundary intersection over union** (BIoU)
15
+
16
+ For convenience, `MeshMetrics` also includes implementations of the **Dice similarity coefficient** (DSC) and **intersection over union** (IoU).
17
+
18
+ ![overview](./data/paper_overview.png)
19
+
20
+ If you use `MeshMetrics` in your work, please cite:
21
+ ```
22
+ Podobnik, G., & Vrtovec, T. (2025). MeshMetrics: A Precise Implementation of Distance-Based Image Segmentation Metrics. arXiv preprint arXiv:2509.05670.
23
+ Podobnik, G., & Vrtovec, T. (2025). Understanding Implementation Pitfalls of Distance-Based Metrics for Image Segmentation. arXiv preprint arXiv:2410.02630.
24
+ ```
25
+
26
+ ## Installation
27
+ ### System Dependencies
28
+ This package requires `libxrender1` to be installed on your system. Install it via:
29
+ ```bash
30
+ sudo apt update && sudo apt install -y libxrender1
31
+ ```
32
+
33
+ ### Install `meshmetrics` package
34
+ Install from [PyPI](https://pypi.org/project/pymeshmetrics/) with pip, or add it to your project with [uv](https://docs.astral.sh/uv/):
35
+ ```bash
36
+ pip install pymeshmetrics
37
+ uv add pymeshmetrics
38
+ ```
39
+ The package is published as `pymeshmetrics` and imported as `meshmetrics`:
40
+ ```python
41
+ import meshmetrics
42
+ ```
43
+ Optional support for `trimesh` and `meshio` inputs is available via extras: `pip install "pymeshmetrics[all]"` (or `[trimesh]` / `[meshio]`).
44
+
45
+ To install the latest development version from GitHub:
46
+ ```bash
47
+ pip install git+https://github.com/gasperpodobnik/meshmetrics.git
48
+ ```
49
+
50
+ ### Development
51
+ Clone the repository and create the environment (including dev tools and all extras):
52
+ ```bash
53
+ git clone https://github.com/gasperpodobnik/meshmetrics.git
54
+ cd meshmetrics
55
+ uv sync --all-extras
56
+ uv run pytest
57
+ ```
58
+
59
+ ## Usage
60
+ ### Quick start
61
+ Compute all metrics for a pair of segmentations in one call:
62
+ ```python
63
+ import SimpleITK as sitk
64
+ from meshmetrics import compute_metrics
65
+
66
+ ref_sitk = sitk.ReadImage("data/example_3d_ref_mask.nii.gz")
67
+ pred_sitk = sitk.ReadImage("data/example_3d_pred_mask.nii.gz")
68
+
69
+ results = compute_metrics(ref_sitk, pred_sitk, taus=(2.0, 5.0))
70
+ # {'ref_is_empty': False, 'pred_is_empty': False, 'HD_100': ..., 'HD_95': ..., 'MASD': ..., 'ASSD': ...,
71
+ # 'NSD_2.0': ..., 'NSD_5.0': ..., 'BIoU_2.0': ..., 'BIoU_5.0': ..., 'DSC': ..., 'IoU': ...}
72
+ ```
73
+ `taus` are the tolerances (in physical units) for NSD and BIoU; they are application-specific, so NSD and BIoU are only computed when `taus` are given. Use `percentiles` to choose the HD variants (default `(100, 95)`) and `metrics` to select a subset, e.g. `metrics=["hd", "nsd"]`. Inputs can be any of the supported types (see below); numpy arrays and pairs of meshes also need `spacing`.
74
+
75
+ ### Step-by-step
76
+ Simple usage example of `MeshMetrics` for 3D segmentation masks is shown below.
77
+ See [`examples.ipynb`](examples.ipynb) notebook for more examples.
78
+
79
+ ```python
80
+ from pathlib import Path
81
+ import SimpleITK as sitk
82
+ from meshmetrics import DistanceMetrics
83
+
84
+ data_dir = Path("data")
85
+
86
+ # read binary segmentation masks
87
+ ref_sitk = sitk.ReadImage(str(data_dir / "example_3d_ref_mask.nii.gz"))
88
+ pred_sitk = sitk.ReadImage(str(data_dir / "example_3d_pred_mask.nii.gz"))
89
+
90
+ # Set parameters
91
+ percentile = 95 # percentile for HD
92
+ tau = 2.0 # tolerance for NSD and BIoU
93
+
94
+ # Initialize distance metrics class and set inputs
95
+ dist_metrics = DistanceMetrics()
96
+ dist_metrics.set_input(ref=ref_sitk, pred=pred_sitk)
97
+
98
+ # store flags indicating empty masks
99
+ results = {
100
+ "ref_is_empty": dist_metrics.ref_is_empty,
101
+ "pred_is_empty": dist_metrics.pred_is_empty,
102
+ }
103
+ # Hausdorff distance (HD), by default, HD percentile is set to 100 (equivalent to HD)
104
+ results["HD_100"] = dist_metrics.hd()
105
+ # p-th percentile HD (HD_p)
106
+ results[f"HD_{percentile}"] = dist_metrics.hd(percentile=percentile)
107
+ # Mean average surface distance (MASD)
108
+ results["MASD"] = dist_metrics.masd()
109
+ # Average symmetric surface distance (ASSD)
110
+ results["ASSD"] = dist_metrics.assd()
111
+ # Normalized surface distance (NSD) with tau
112
+ results[f"NSD_{tau}"] = dist_metrics.nsd(tau=tau)
113
+ # Boundary intersection over union (BIoU) with tau
114
+ results[f"BIoU_{tau}"] = dist_metrics.biou(tau=tau)
115
+
116
+ # print metric values
117
+ units = {"HD": "mm", "MASD": "mm", "ASSD": "mm", "NSD": "%", "BIoU": "%"}
118
+ for k, v in results.items():
119
+ unit = units.get(k.split("_")[0], "")
120
+ f = 100.0 if unit == "%" else 1.0
121
+ print(f"{k}: {v*f:.2f} {unit}")
122
+
123
+ # ----------------------------------------
124
+ # If using `numpy.ndarray` representations, note that the spacing must be
125
+ # reordered when converting a `SimpleITK.Image` object to a `numpy.ndarray`
126
+ ref_np = sitk.GetArrayFromImage(ref_sitk).astype(bool)
127
+ pred_np = sitk.GetArrayFromImage(pred_sitk).astype(bool)
128
+
129
+ # spacing should resemble the order of numpy array axes
130
+ spacing = ref_sitk.GetSpacing()[::-1]
131
+
132
+ dist_metrics = DistanceMetrics()
133
+ dist_metrics.set_input(ref=ref_np, pred=pred_np, spacing=spacing)
134
+ # ... follow the same procedure as before
135
+ ```