grainmorph 0.2.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.
Files changed (38) hide show
  1. grainmorph-0.2.0/LICENSE +21 -0
  2. grainmorph-0.2.0/PKG-INFO +208 -0
  3. grainmorph-0.2.0/README.md +188 -0
  4. grainmorph-0.2.0/pyproject.toml +38 -0
  5. grainmorph-0.2.0/setup.cfg +4 -0
  6. grainmorph-0.2.0/src/grainmorph/__init__.py +5 -0
  7. grainmorph-0.2.0/src/grainmorph/analyzer.py +49 -0
  8. grainmorph-0.2.0/src/grainmorph/fitting.py +79 -0
  9. grainmorph-0.2.0/src/grainmorph/mask_ops.py +128 -0
  10. grainmorph-0.2.0/src/grainmorph/metrics.py +112 -0
  11. grainmorph-0.2.0/src/grainmorph/schema.py +50 -0
  12. grainmorph-0.2.0/src/grainmorph/utils/__init__.py +29 -0
  13. grainmorph-0.2.0/src/grainmorph/utils/create_mask.py +115 -0
  14. grainmorph-0.2.0/src/grainmorph/utils/geometry.py +23 -0
  15. grainmorph-0.2.0/src/grainmorph/utils/parametric_mask.py +199 -0
  16. grainmorph-0.2.0/src/grainmorph/utils/plot.py +99 -0
  17. grainmorph-0.2.0/src/grainmorph/validation.py +44 -0
  18. grainmorph-0.2.0/src/grainmorph/wadell/__init__.py +3 -0
  19. grainmorph-0.2.0/src/grainmorph/wadell/boundary.py +14 -0
  20. grainmorph-0.2.0/src/grainmorph/wadell/corner.py +163 -0
  21. grainmorph-0.2.0/src/grainmorph/wadell/discretize.py +66 -0
  22. grainmorph-0.2.0/src/grainmorph/wadell/roundness.py +61 -0
  23. grainmorph-0.2.0/src/grainmorph/wadell/smoothing.py +41 -0
  24. grainmorph-0.2.0/src/grainmorph.egg-info/PKG-INFO +208 -0
  25. grainmorph-0.2.0/src/grainmorph.egg-info/SOURCES.txt +36 -0
  26. grainmorph-0.2.0/src/grainmorph.egg-info/dependency_links.txt +1 -0
  27. grainmorph-0.2.0/src/grainmorph.egg-info/requires.txt +7 -0
  28. grainmorph-0.2.0/src/grainmorph.egg-info/top_level.txt +1 -0
  29. grainmorph-0.2.0/tests/test_analyzer.py +203 -0
  30. grainmorph-0.2.0/tests/test_corner.py +128 -0
  31. grainmorph-0.2.0/tests/test_discretize.py +24 -0
  32. grainmorph-0.2.0/tests/test_fitting.py +75 -0
  33. grainmorph-0.2.0/tests/test_generation.py +137 -0
  34. grainmorph-0.2.0/tests/test_mask_ops.py +37 -0
  35. grainmorph-0.2.0/tests/test_metrics.py +45 -0
  36. grainmorph-0.2.0/tests/test_plot.py +34 -0
  37. grainmorph-0.2.0/tests/test_smoothing.py +46 -0
  38. grainmorph-0.2.0/tests/test_validation.py +21 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GrainMorph Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: grainmorph
3
+ Version: 0.2.0
4
+ Summary: Particle shape analysis and visualization library.
5
+ Author: GrainMorph Contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/phykn/grainmorph
8
+ Project-URL: Repository, https://github.com/phykn/grainmorph
9
+ Project-URL: Issues, https://github.com/phykn/grainmorph/issues
10
+ Requires-Python: >=3.12
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: numpy
14
+ Requires-Dist: opencv-python
15
+ Requires-Dist: matplotlib
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest; extra == "dev"
18
+ Requires-Dist: ruff; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # GrainMorph
22
+
23
+ GrainMorph analyzes a single 2D binary particle mask and returns geometric shape metrics.
24
+
25
+ | Metric | Meaning |
26
+ |---|---|
27
+ | Wadell roundness | Corner curvature-based roundness |
28
+ | Circularity | `4 * pi * area / perimeter^2` |
29
+ | Sphericity | Inscribed circle radius divided by enclosing circle radius |
30
+ | Aspect ratio | Fitted ellipse major axis divided by minor axis |
31
+
32
+ Roundness, circularity, and sphericity are clipped to `0..1`. Aspect ratio is `>= 1`.
33
+
34
+ ## Installation
35
+
36
+ GrainMorph requires Python `3.12+`.
37
+
38
+ ```bash
39
+ pip install grainmorph
40
+ ```
41
+
42
+ For local development:
43
+
44
+ ```bash
45
+ pip install -e ".[dev]"
46
+ ```
47
+
48
+ Run the tests and code checks with the same Python environment:
49
+
50
+ ```bash
51
+ python -m pytest -q
52
+ python -m ruff check --isolated .
53
+ python -m ruff format --isolated --check src tests
54
+ ```
55
+
56
+ ## Quick Start
57
+
58
+ ```python
59
+ import grainmorph as pm
60
+
61
+ mask = pm.utils.create_circle_mask((256, 256), (128, 128), 60)
62
+ results = pm.analyze_mask(mask)
63
+
64
+ if results is None:
65
+ raise ValueError("mask has no foreground pixels")
66
+
67
+ print(results["roundness"]["val"])
68
+ print(results["circularity"]["val"])
69
+ print(results["sphericity"]["val"])
70
+ print(results["aspect_ratio"]["val"])
71
+ ```
72
+
73
+ Visualize the results:
74
+
75
+ ```python
76
+ pm.utils.plot_analysis_results(mask, results)
77
+ ```
78
+
79
+ ## API
80
+
81
+ ```python
82
+ pm.analyze_mask(
83
+ mask,
84
+ use_aspect_ratio=True,
85
+ use_roundness=True,
86
+ use_circularity=True,
87
+ use_sphericity=True,
88
+ roundness_params=None,
89
+ eps=0.001,
90
+ target_dim=384,
91
+ )
92
+ ```
93
+
94
+ | Parameter | Description |
95
+ |---|---|
96
+ | `mask` | 2D `numpy.ndarray` with `bool` or `{0, 1}` values |
97
+ | `use_*` | Toggle individual metrics on/off |
98
+ | `roundness_params` | Optional dict to override Wadell roundness parameters |
99
+ | `eps` | Tolerance for geometric computations |
100
+ | `target_dim` | Particle bounds larger than this are downscaled for speed, then coordinates are restored |
101
+
102
+ `roundness_params` accepts these Wadell options. Defaults are defined in
103
+ `wadell/roundness.py` and also apply to synthetic particle calibration:
104
+
105
+ | Option | Default | Stage |
106
+ |---|---|---|
107
+ | `max_dev_thresh` | `0.3` | Boundary discretization |
108
+ | `circle_fit_thresh` | `0.98` | Corner circle fitting |
109
+ | `alpha_ratio` | `0.05` | Boundary smoothing |
110
+ | `beta_ratio` | `0.001` | Boundary smoothing |
111
+
112
+ Returns `None` for an empty mask. Otherwise, returns an `AnalysisResult` dict. Disabled metrics are omitted; enabled metrics are present and may be `None` when the geometry cannot be measured.
113
+
114
+ ## Result Shape
115
+
116
+ ```python
117
+ {
118
+ "roundness": {"val": float} | None,
119
+ "circularity": {"val": float} | None,
120
+ "sphericity": {
121
+ "val": float,
122
+ "inscribed": {"x": float, "y": float, "r": float},
123
+ "enclosing": {"x": float, "y": float, "r": float},
124
+ } | None,
125
+ "aspect_ratio": {
126
+ "val": float,
127
+ "ellipse": {
128
+ "major": float, "minor": float,
129
+ "x": float, "y": float, "angle": float,
130
+ "w": float, "h": float, "bbox": list[list[float]],
131
+ },
132
+ } | None,
133
+ }
134
+ ```
135
+
136
+ ## Input Rules
137
+
138
+ - `mask` must be a 2D `numpy.ndarray`
139
+ - Allowed values are `bool` or numeric `{0, 1}`
140
+ - Floating masks must not contain `NaN` or `inf`
141
+ - Empty mask returns `None`
142
+ - The largest 4-connected foreground component is selected and holes are filled
143
+ - Surrounding zero padding does not change the measured shape
144
+ - Downscaling is skipped if its output would have a one-pixel axis
145
+ - Shape, center, and rectangle corner arguments use image order: `(height, width)` and `(y, x)`
146
+ - Triangle vertices use Cartesian order `(x, y)`, matching polygon coordinates
147
+
148
+ ## Project Layout
149
+
150
+ - `analyzer.py`: public analysis workflow and metric selection
151
+ - `validation.py`: public input normalization and analysis-option validation
152
+ - `mask_ops.py`: component selection, contours, and `PreparedMask` crop/resize transforms with result-coordinate restoration
153
+ - `metrics.py`: metric formulas and public result payloads
154
+ - `fitting.py`: circle and ellipse fitting plus oriented bounding boxes
155
+ - `wadell/roundness.py`: roundness options and the boundary-to-radius workflow
156
+ - `wadell/boundary.py` and `smoothing.py`: closed boundary extraction and periodic smoothing
157
+ - `wadell/discretize.py`: boundary approximation with `(x, y)` point arrays
158
+ - `wadell/corner.py`: convex corner selection, circle fitting, and accepted corner radii
159
+ - `utils/`: basic mask construction, parametric particle calibration and reporting, and visualization
160
+
161
+ ## Utilities
162
+
163
+ Mask constructors:
164
+
165
+ - `pm.utils.create_circle_mask(...)`
166
+ - `pm.utils.create_ellipse_mask(...)`
167
+ - `pm.utils.create_rectangle_mask(...)`
168
+ - `pm.utils.create_square_mask(...)`
169
+ - `pm.utils.create_triangle_mask(...)`
170
+ - `pm.utils.create_pentagon_mask(...)`
171
+ - `pm.utils.create_star_mask(...)`
172
+ - `pm.utils.create_particle_mask(...)`
173
+
174
+ For example, a triangle in a non-square image uses `(x, y)` vertices:
175
+
176
+ ```python
177
+ mask = pm.utils.create_triangle_mask((20, 60), (30, 2), (40, 2), (30, 8))
178
+ ```
179
+
180
+ `create_particle_mask` attempts to reach the requested roundness by calibrating
181
+ surface roughness. Set `seed` for reproducible masks and `return_info=True` to
182
+ receive `(mask, info)`. The report measures the returned mask, including any
183
+ clipping at the image bounds; `target_met` compares its roundness error with
184
+ `report_tol`. A zero-radius particle reports roundness `0.0`.
185
+
186
+ Visualization:
187
+
188
+ - `pm.utils.plot_analysis_results(mask, results)`
189
+
190
+ ## Changes in 0.2.0
191
+
192
+ - Renamed the package from `partimorph` to `grainmorph`: install with `pip install grainmorph` and import with `import grainmorph`. The API is otherwise unchanged from 0.1.9.
193
+
194
+ ## Changes in 0.1.9
195
+
196
+ - Wadell roundness is several times faster: corner circle fits are vectorized and boundary discretization does less per-step work. Results are unchanged.
197
+ - `create_particle_mask` calibrates roughness with 12 bisection steps by default instead of 20, about 1.5x faster. Generated masks can differ slightly; on a 108-case grid the roundness error changed by at most 0.012 and its mean was unchanged.
198
+ - Component selection, hole filling, and the Crofton perimeter now use OpenCV and NumPy, so `scipy` and `scikit-image` are no longer dependencies. Results are unchanged.
199
+
200
+ ## Changes in 0.1.8
201
+
202
+ - Corrected the fitted ellipse overlay orientation for rotated particles.
203
+ - Unified inscribed-circle fitting used by sphericity and Wadell roundness.
204
+ - Simplified ellipse fitting and bounding-box coordinate transforms while preserving the public API and analysis results.
205
+
206
+ ## License
207
+
208
+ MIT
@@ -0,0 +1,188 @@
1
+ # GrainMorph
2
+
3
+ GrainMorph analyzes a single 2D binary particle mask and returns geometric shape metrics.
4
+
5
+ | Metric | Meaning |
6
+ |---|---|
7
+ | Wadell roundness | Corner curvature-based roundness |
8
+ | Circularity | `4 * pi * area / perimeter^2` |
9
+ | Sphericity | Inscribed circle radius divided by enclosing circle radius |
10
+ | Aspect ratio | Fitted ellipse major axis divided by minor axis |
11
+
12
+ Roundness, circularity, and sphericity are clipped to `0..1`. Aspect ratio is `>= 1`.
13
+
14
+ ## Installation
15
+
16
+ GrainMorph requires Python `3.12+`.
17
+
18
+ ```bash
19
+ pip install grainmorph
20
+ ```
21
+
22
+ For local development:
23
+
24
+ ```bash
25
+ pip install -e ".[dev]"
26
+ ```
27
+
28
+ Run the tests and code checks with the same Python environment:
29
+
30
+ ```bash
31
+ python -m pytest -q
32
+ python -m ruff check --isolated .
33
+ python -m ruff format --isolated --check src tests
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ```python
39
+ import grainmorph as pm
40
+
41
+ mask = pm.utils.create_circle_mask((256, 256), (128, 128), 60)
42
+ results = pm.analyze_mask(mask)
43
+
44
+ if results is None:
45
+ raise ValueError("mask has no foreground pixels")
46
+
47
+ print(results["roundness"]["val"])
48
+ print(results["circularity"]["val"])
49
+ print(results["sphericity"]["val"])
50
+ print(results["aspect_ratio"]["val"])
51
+ ```
52
+
53
+ Visualize the results:
54
+
55
+ ```python
56
+ pm.utils.plot_analysis_results(mask, results)
57
+ ```
58
+
59
+ ## API
60
+
61
+ ```python
62
+ pm.analyze_mask(
63
+ mask,
64
+ use_aspect_ratio=True,
65
+ use_roundness=True,
66
+ use_circularity=True,
67
+ use_sphericity=True,
68
+ roundness_params=None,
69
+ eps=0.001,
70
+ target_dim=384,
71
+ )
72
+ ```
73
+
74
+ | Parameter | Description |
75
+ |---|---|
76
+ | `mask` | 2D `numpy.ndarray` with `bool` or `{0, 1}` values |
77
+ | `use_*` | Toggle individual metrics on/off |
78
+ | `roundness_params` | Optional dict to override Wadell roundness parameters |
79
+ | `eps` | Tolerance for geometric computations |
80
+ | `target_dim` | Particle bounds larger than this are downscaled for speed, then coordinates are restored |
81
+
82
+ `roundness_params` accepts these Wadell options. Defaults are defined in
83
+ `wadell/roundness.py` and also apply to synthetic particle calibration:
84
+
85
+ | Option | Default | Stage |
86
+ |---|---|---|
87
+ | `max_dev_thresh` | `0.3` | Boundary discretization |
88
+ | `circle_fit_thresh` | `0.98` | Corner circle fitting |
89
+ | `alpha_ratio` | `0.05` | Boundary smoothing |
90
+ | `beta_ratio` | `0.001` | Boundary smoothing |
91
+
92
+ Returns `None` for an empty mask. Otherwise, returns an `AnalysisResult` dict. Disabled metrics are omitted; enabled metrics are present and may be `None` when the geometry cannot be measured.
93
+
94
+ ## Result Shape
95
+
96
+ ```python
97
+ {
98
+ "roundness": {"val": float} | None,
99
+ "circularity": {"val": float} | None,
100
+ "sphericity": {
101
+ "val": float,
102
+ "inscribed": {"x": float, "y": float, "r": float},
103
+ "enclosing": {"x": float, "y": float, "r": float},
104
+ } | None,
105
+ "aspect_ratio": {
106
+ "val": float,
107
+ "ellipse": {
108
+ "major": float, "minor": float,
109
+ "x": float, "y": float, "angle": float,
110
+ "w": float, "h": float, "bbox": list[list[float]],
111
+ },
112
+ } | None,
113
+ }
114
+ ```
115
+
116
+ ## Input Rules
117
+
118
+ - `mask` must be a 2D `numpy.ndarray`
119
+ - Allowed values are `bool` or numeric `{0, 1}`
120
+ - Floating masks must not contain `NaN` or `inf`
121
+ - Empty mask returns `None`
122
+ - The largest 4-connected foreground component is selected and holes are filled
123
+ - Surrounding zero padding does not change the measured shape
124
+ - Downscaling is skipped if its output would have a one-pixel axis
125
+ - Shape, center, and rectangle corner arguments use image order: `(height, width)` and `(y, x)`
126
+ - Triangle vertices use Cartesian order `(x, y)`, matching polygon coordinates
127
+
128
+ ## Project Layout
129
+
130
+ - `analyzer.py`: public analysis workflow and metric selection
131
+ - `validation.py`: public input normalization and analysis-option validation
132
+ - `mask_ops.py`: component selection, contours, and `PreparedMask` crop/resize transforms with result-coordinate restoration
133
+ - `metrics.py`: metric formulas and public result payloads
134
+ - `fitting.py`: circle and ellipse fitting plus oriented bounding boxes
135
+ - `wadell/roundness.py`: roundness options and the boundary-to-radius workflow
136
+ - `wadell/boundary.py` and `smoothing.py`: closed boundary extraction and periodic smoothing
137
+ - `wadell/discretize.py`: boundary approximation with `(x, y)` point arrays
138
+ - `wadell/corner.py`: convex corner selection, circle fitting, and accepted corner radii
139
+ - `utils/`: basic mask construction, parametric particle calibration and reporting, and visualization
140
+
141
+ ## Utilities
142
+
143
+ Mask constructors:
144
+
145
+ - `pm.utils.create_circle_mask(...)`
146
+ - `pm.utils.create_ellipse_mask(...)`
147
+ - `pm.utils.create_rectangle_mask(...)`
148
+ - `pm.utils.create_square_mask(...)`
149
+ - `pm.utils.create_triangle_mask(...)`
150
+ - `pm.utils.create_pentagon_mask(...)`
151
+ - `pm.utils.create_star_mask(...)`
152
+ - `pm.utils.create_particle_mask(...)`
153
+
154
+ For example, a triangle in a non-square image uses `(x, y)` vertices:
155
+
156
+ ```python
157
+ mask = pm.utils.create_triangle_mask((20, 60), (30, 2), (40, 2), (30, 8))
158
+ ```
159
+
160
+ `create_particle_mask` attempts to reach the requested roundness by calibrating
161
+ surface roughness. Set `seed` for reproducible masks and `return_info=True` to
162
+ receive `(mask, info)`. The report measures the returned mask, including any
163
+ clipping at the image bounds; `target_met` compares its roundness error with
164
+ `report_tol`. A zero-radius particle reports roundness `0.0`.
165
+
166
+ Visualization:
167
+
168
+ - `pm.utils.plot_analysis_results(mask, results)`
169
+
170
+ ## Changes in 0.2.0
171
+
172
+ - Renamed the package from `partimorph` to `grainmorph`: install with `pip install grainmorph` and import with `import grainmorph`. The API is otherwise unchanged from 0.1.9.
173
+
174
+ ## Changes in 0.1.9
175
+
176
+ - Wadell roundness is several times faster: corner circle fits are vectorized and boundary discretization does less per-step work. Results are unchanged.
177
+ - `create_particle_mask` calibrates roughness with 12 bisection steps by default instead of 20, about 1.5x faster. Generated masks can differ slightly; on a 108-case grid the roundness error changed by at most 0.012 and its mean was unchanged.
178
+ - Component selection, hole filling, and the Crofton perimeter now use OpenCV and NumPy, so `scipy` and `scikit-image` are no longer dependencies. Results are unchanged.
179
+
180
+ ## Changes in 0.1.8
181
+
182
+ - Corrected the fitted ellipse overlay orientation for rotated particles.
183
+ - Unified inscribed-circle fitting used by sphericity and Wadell roundness.
184
+ - Simplified ellipse fitting and bounding-box coordinate transforms while preserving the public API and analysis results.
185
+
186
+ ## License
187
+
188
+ MIT
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "grainmorph"
7
+ version = "0.2.0"
8
+ authors = [
9
+ { name = "GrainMorph Contributors" }
10
+ ]
11
+ description = "Particle shape analysis and visualization library."
12
+ readme = "README.md"
13
+ requires-python = ">=3.12"
14
+ license = "MIT"
15
+ license-files = ["LICENSE"]
16
+ dependencies = [
17
+ "numpy",
18
+ "opencv-python",
19
+ "matplotlib",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ dev = [
24
+ "pytest",
25
+ "ruff",
26
+ ]
27
+
28
+ [tool.pytest.ini_options]
29
+ pythonpath = ["src"]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/phykn/grainmorph"
33
+ Repository = "https://github.com/phykn/grainmorph"
34
+ Issues = "https://github.com/phykn/grainmorph/issues"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+ include = ["grainmorph*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ from . import utils
2
+ from .analyzer import analyze_mask
3
+
4
+ __version__ = "0.2.0"
5
+ __all__ = ["analyze_mask", "utils"]
@@ -0,0 +1,49 @@
1
+ import numpy as np
2
+
3
+ from .mask_ops import prepare_mask
4
+ from .metrics import (
5
+ compute_aspect_ratio,
6
+ compute_circularity,
7
+ compute_roundness,
8
+ compute_sphericity,
9
+ )
10
+ from .schema import AnalysisResult
11
+ from .validation import to_binary, validate_analysis_params
12
+
13
+
14
+ def analyze_mask(
15
+ mask: np.ndarray,
16
+ *,
17
+ use_aspect_ratio: bool = True,
18
+ use_roundness: bool = True,
19
+ use_circularity: bool = True,
20
+ use_sphericity: bool = True,
21
+ roundness_params: dict[str, float] | None = None,
22
+ eps: float = 0.001,
23
+ target_dim: int = 384,
24
+ ) -> AnalysisResult | None:
25
+ eps, target_dim = validate_analysis_params(eps, target_dim)
26
+
27
+ mask_binary = to_binary(mask)
28
+ if not np.any(mask_binary):
29
+ return None
30
+
31
+ if not (use_aspect_ratio or use_roundness or use_circularity or use_sphericity):
32
+ return {}
33
+
34
+ prepared = prepare_mask(mask_binary, target_dim=target_dim)
35
+ final_mask = prepared.mask
36
+
37
+ results: AnalysisResult = {}
38
+ if use_aspect_ratio:
39
+ results["aspect_ratio"] = compute_aspect_ratio(final_mask, eps=eps)
40
+ if use_roundness:
41
+ results["roundness"] = compute_roundness(final_mask, **(roundness_params or {}))
42
+ if use_circularity:
43
+ results["circularity"] = compute_circularity(final_mask, eps=eps)
44
+ if use_sphericity:
45
+ results["sphericity"] = compute_sphericity(final_mask, eps=eps)
46
+
47
+ prepared.restore_results(results)
48
+
49
+ return results
@@ -0,0 +1,79 @@
1
+ import cv2
2
+ import numpy as np
3
+
4
+ from .mask_ops import crop_mask, get_contours
5
+ from .schema import Bbox, CircleData, EllipseData, Mask, Points
6
+
7
+
8
+ def find_inscribed_circle(mask: Mask) -> CircleData | None:
9
+ cropped_mask, pad_x0, pad_y0 = crop_mask(mask, pad=1)
10
+
11
+ if cropped_mask.size == 0:
12
+ return None
13
+
14
+ distance_transform = cv2.distanceTransform(
15
+ cropped_mask.astype(np.uint8, copy=False), cv2.DIST_L2, cv2.DIST_MASK_PRECISE
16
+ )
17
+
18
+ max_idx = np.argmax(distance_transform)
19
+ crop_center_y, crop_center_x = np.unravel_index(max_idx, distance_transform.shape)
20
+
21
+ center_x = float(int(crop_center_x) + pad_x0)
22
+ center_y = float(int(crop_center_y) + pad_y0)
23
+ radius = float(distance_transform[crop_center_y, crop_center_x])
24
+
25
+ return {"x": center_x, "y": center_y, "r": radius}
26
+
27
+
28
+ def find_enclosing_circle(mask: Mask) -> CircleData | None:
29
+ contours = get_contours(mask)
30
+ if not contours:
31
+ return None
32
+
33
+ points = np.concatenate(contours)
34
+ hull = cv2.convexHull(points)
35
+
36
+ (center_x, center_y), radius = cv2.minEnclosingCircle(hull)
37
+
38
+ return {"x": float(center_x), "y": float(center_y), "r": float(radius)}
39
+
40
+
41
+ def fit_ellipse(mask: Mask) -> EllipseData | None:
42
+ contours = get_contours(mask)
43
+ if not contours:
44
+ return None
45
+
46
+ points: Points = np.concatenate(contours).reshape(-1, 2).astype(np.float32)
47
+ if len(points) < 5:
48
+ rect = cv2.minAreaRect(points)
49
+ (center_x, center_y), (width, height), angle = rect
50
+
51
+ if width <= 1e-06 or height <= 1e-06:
52
+ return None
53
+
54
+ bbox = cv2.boxPoints(rect).tolist()
55
+ else:
56
+ (center_x, center_y), (width, height), angle = cv2.fitEllipse(points)
57
+ bbox = _oriented_bbox_from_angle(points, angle)
58
+
59
+ return {
60
+ "major": float(max(width, height)),
61
+ "minor": float(min(width, height)),
62
+ "x": float(center_x),
63
+ "y": float(center_y),
64
+ "angle": float(angle),
65
+ "w": float(width),
66
+ "h": float(height),
67
+ "bbox": bbox,
68
+ }
69
+
70
+
71
+ def _oriented_bbox_from_angle(points: Points, angle: float) -> Bbox:
72
+ radians = np.deg2rad(angle)
73
+ cos_a, sin_a = np.cos(radians), np.sin(radians)
74
+ axes = np.array([[cos_a, -sin_a], [sin_a, cos_a]])
75
+ projected = points @ axes
76
+ min_x, min_y = projected.min(axis=0)
77
+ max_x, max_y = projected.max(axis=0)
78
+ corners = np.array([[min_x, min_y], [max_x, min_y], [max_x, max_y], [min_x, max_y]])
79
+ return (corners @ axes.T).tolist()