woundscan 0.1.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,26 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Muhammad Allam Rafi and Cindy Rizky Afrilia
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.
22
+
23
+ Scope: this license covers the Python package under src/woundscan and its
24
+ package tests and documentation. Model weights, datasets, photographs,
25
+ third-party browser libraries, and other repository assets are excluded.
26
+ Their original rights and restrictions continue to apply.
@@ -0,0 +1,11 @@
1
+ include LICENSE
2
+ include docs/PYPI_README.md
3
+ include tests/*.py
4
+ prune app
5
+ prune data
6
+ prune models
7
+ prune webtest
8
+ prune train
9
+ prune docs/figures
10
+ prune contoh
11
+ global-exclude *.onnx *.pt *.jpg *.png *.wasm *.log
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: woundscan
3
+ Version: 0.1.0
4
+ Summary: Composable calibrated wound-mask measurement and optional ONNX segmentation for research
5
+ Author: Muhammad Allam Rafi, Cindy Rizky Afrilia
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sharing-123/WoundScan
8
+ Project-URL: Repository, https://github.com/sharing-123/WoundScan
9
+ Project-URL: Issues, https://github.com/sharing-123/WoundScan/issues
10
+ Project-URL: Documentation, https://github.com/sharing-123/WoundScan/blob/main/docs/PYPI_README.md
11
+ Project-URL: OSF registration, https://doi.org/10.17605/OSF.IO/KV3SP
12
+ Project-URL: Zenodo archive, https://doi.org/10.5281/zenodo.24412818
13
+ Keywords: wound,segmentation,medical-imaging,calibration,research
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
18
+ Classifier: Intended Audience :: Science/Research
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy>=1.23
23
+ Provides-Extra: inference
24
+ Requires-Dist: onnxruntime>=1.17; extra == "inference"
25
+ Requires-Dist: opencv-python-headless>=4.8; extra == "inference"
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest>=8; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # WoundScan for Python
31
+
32
+ Calibrated binary-mask measurements and local ONNX segmentation for research pipelines.
33
+
34
+ Install with `pip install woundscan`. Requires Python 3.10 or later.
35
+
36
+ [Source](https://github.com/sharing-123/WoundScan) | [Issues](https://github.com/sharing-123/WoundScan/issues) | [OSF](https://doi.org/10.17605/OSF.IO/KV3SP) | [Zenodo](https://doi.org/10.5281/zenodo.24412818)
37
+
38
+ ## Measure any binary mask
39
+
40
+ ```python
41
+ import json
42
+ import numpy as np
43
+ from woundscan import measure_mask, reference_scale
44
+
45
+ mask = np.zeros((100, 100), dtype=bool)
46
+ mask[20:40, 30:60] = True
47
+ scale = reference_scale(reference_pixels=100, reference_mm=10)
48
+ result = measure_mask(mask, scale, height_cm=170, weight_kg=70)
49
+ print(result.area_mm2) # 6.0
50
+ print(result.perimeter_mm) # 10.0
51
+ print(json.dumps(result.to_dict(), indent=2))
52
+ ```
53
+
54
+ The API accepts masks from any segmentation model or manual annotation pipeline.
55
+ Measurements use millimetres and square millimetres. Mosteller body surface area
56
+ uses height in centimetres and weight in kilograms. Supply both to calculate
57
+ `tbsa_percent`, otherwise it is `None`. A reference must lie in the wound plane.
58
+ Curved surfaces, perspective and calibration uncertainty affect accuracy.
59
+
60
+ ## Optional segmentation
61
+
62
+ Install with `pip install "woundscan[inference]"`.
63
+
64
+ ```python
65
+ import cv2
66
+ from woundscan import Segmenter, measure_mask
67
+
68
+ model = Segmenter("/path/to/wound_seg.onnx")
69
+ bgr = cv2.imread("/path/to/image.png")
70
+ if bgr is None:
71
+ raise ValueError("Image could not be loaded")
72
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
73
+ probability = model.predict(rgb)
74
+ mask = model.segment(rgb, threshold=0.5)
75
+ result = measure_mask(mask, mm_per_pixel=0.1)
76
+ ```
77
+
78
+ Supply a model you have permission to use. No weights or network downloads are
79
+ included. Inference uses ONNX Runtime CPU, with float32 RGB input [1,3,256,256]
80
+ in [0,1] and probability output [1,1,256,256]. The recipe follows the repository
81
+ Python evaluation script, averaging original, horizontal and vertical flips.
82
+ Set `tta=False` for a single pass. Invalid probabilities and logits are rejected.
83
+
84
+ ## API
85
+
86
+ | Function | Result |
87
+ | --- | --- |
88
+ | reference_scale(reference_pixels, reference_mm) | Millimetres per pixel |
89
+ | body_surface_area(height_cm, weight_kg) | Mosteller BSA in square metres |
90
+ | measure_mask(mask, mm_per_pixel, height_cm=None, weight_kg=None) | Immutable Measurement; height and weight are keyword-only |
91
+ | Measurement.to_dict() | JSON-compatible dictionary |
92
+ | Segmenter(model_path).predict(rgb, tta=True) | Original-resolution probability array; tta is keyword-only |
93
+ | Segmenter(model_path).segment(rgb, threshold=0.5, tta=True) | Boolean mask; threshold and tta are keyword-only |
94
+
95
+ Functions compose with notebooks, batch processing and APIs. Import starts no
96
+ server, downloads no models and performs no inference. Model loading occurs only
97
+ when a Segmenter is constructed.
98
+
99
+ ## Scope and evidence
100
+
101
+ Version 0.1 provides measurement and optional inference. Browser reconstructive
102
+ planning, tissue analysis, donor mapping and interactive editing remain in the
103
+ GitHub application and are not exported by this Python API.
104
+
105
+ Area counts foreground pixel cells across all components. Perimeter counts
106
+ exposed pixel edges, including holes. This lattice perimeter is orientation
107
+ dependent and differs from the browser's smoothed subpixel contour algorithm.
108
+ Inference does not apply browser smoothing, component removal or hole filling.
109
+ Final masks can therefore differ from browser masks.
110
+
111
+ The repository model evaluation reported Dice 0.827 on 200 validation images and
112
+ 0.793 on 160 external images. These describe that evaluation, not a guarantee
113
+ for this package or new photographs. Small punctures and thin abrasions were
114
+ important failure modes. The software is a research prototype without clinical
115
+ validation and must not replace clinical judgement.
116
+
117
+ ## Licensing and model rights
118
+
119
+ The Python package, tests and package documentation use MIT. Wheels and source
120
+ archives exclude model weights, photographs, datasets and browser libraries.
121
+ Repository weights were trained on restricted noncommercial datasets and data
122
+ without a documented redistribution license. Obtain appropriate permissions or
123
+ train with suitably licensed data. MIT does not relicense these assets. PyPI
124
+ hosting does not certify scientific accuracy or clinical suitability.
125
+
126
+ ## Development
127
+
128
+ Clone the repository and create a virtual environment, then run:
129
+
130
+ ```bash
131
+ pip install -e ".[test,inference]" build twine
132
+ pytest
133
+ python -m build
134
+ python -m twine check dist/*
135
+ ```
136
+
137
+ Tests cover known geometry, units, input validation and inference transforms.
138
+ Default measurement tests require no model weights. Bug reports should include
139
+ package versions and a minimal example without identifying patient information.
140
+
141
+ Authors: Muhammad Allam Rafi and Cindy Rizky Afrilia.
@@ -0,0 +1,135 @@
1
+ <p align="center">
2
+ <img src="docs/banner.svg" width="100%" alt="WoundScan, an animated isometric view of a wound photograph, its calibrated segmentation, and the surgical marking plan">
3
+ </p>
4
+
5
+ <p align="center">
6
+ <img src="https://img.shields.io/badge/OSF%20DOI-to%20be%20assigned-lightgrey?style=flat-square" alt="OSF DOI placeholder">
7
+ <img src="https://img.shields.io/badge/Zenodo%20DOI-to%20be%20assigned-lightgrey?style=flat-square" alt="Zenodo DOI placeholder">
8
+ <img src="https://img.shields.io/badge/runs-offline%20in%20the%20browser-0b1b30?style=flat-square" alt="Runs offline in the browser">
9
+ <img src="https://img.shields.io/badge/status-research%20prototype-0b1b30?style=flat-square" alt="Research prototype">
10
+ </p>
11
+
12
+ # WoundScan
13
+
14
+ <p align="center"><em>Calibrated Wound Segmentation and Reconstructive Surgical Planning from Clinical Photographs: A Bioinformatic and Deep Learning Study</em></p>
15
+
16
+ <p align="center">Muhammad Allam Rafi<sup>1</sup>, Cindy Rizky Afrilia<sup>2</sup><br><sup>1</sup>Faculty of Medicine, Universitas Indonesia, Jakarta, Indonesia<br><sup>2</sup>Faculty of Medicine, Universitas Kristen Krida Wacana, Jakarta, Indonesia</p>
17
+
18
+ <p align="center">OSF DOI 10.17605/OSF.IO/XXXXX<br>Zenodo DOI 10.5281/zenodo.XXXXXXX</p>
19
+
20
+ ## Abstract
21
+
22
+ Introduction. Wounds are still assessed mostly by eye, and manual area estimates differ between observers. Emergency departments and outpatient clinics rarely have a tool that turns a single photograph into a calibrated measurement and an operative plan. We describe WoundScan, an open research tool that combines deep learning segmentation, camera geometry, and rule based reconstructive planning.
23
+
24
+ Methods. A U-Net with a MobileNetV2 encoder was trained on 810 expert annotated foot ulcer images and, in a second round, on 800 further images from the WoundSeg collection whose coarse masks were sharpened with seeded GrabCut and colour based edge peeling. Pixel size comes from a reference object, the patient's palm, or camera distance. Area, perimeter, and percent total body surface area then follow from the Mosteller body surface area. A planning module proposes fusiform excision, linear closure, advancement and V to Y flaps, Z plasty, and skin grafts, and ranks donor sites with Lund and Browder regional fractions.
25
+
26
+ Results and Discussion. On 200 validation images the model reached a Dice coefficient of 0.827 with a median area error of 11.5 percent, and on 160 external Medetec images it reached 0.793. The geometry routines reproduced analytic areas within 0.07 percent. In 31 public photographs the model segmented dehiscence, diabetic ulcers, large pressure injuries, and blistered burns reliably, but it missed small punctures and thin abrasions. Region cropping and promptable segmentation did not improve accuracy. Absolute size depends on calibration, which adds a length error between two and ten percent.
27
+
28
+ Conclusion. Calibrated single photograph measurement and structured reconstructive planning are feasible in a browser without any server upload. Prospective clinical validation is required before use in patient care.
29
+
30
+ Keywords. Wound segmentation, Medical image analysis, Reconstructive surgery, Deep learning
31
+
32
+ <p align="center">
33
+ <img src="docs/figures/fig1_application_marking_view.jpg" width="100%" alt="Figure 1. Browser interface in marking view for a sacral pressure injury. The left panel shows the calibrated segmentation, the dimensions, and the V to Y flap marking, and the right panel lists the ranked flap options with their size limits.">
34
+ </p>
35
+ <p align="center"><sub><em>Figure 1. Browser interface in marking view for a sacral pressure injury. The left panel shows the calibrated segmentation, the dimensions, and the V to Y flap marking, and the right panel lists the ranked flap options with their size limits.</em></sub></p>
36
+
37
+ ## Methods
38
+
39
+ The application is a static website. All computation happens in the browser through onnxruntime-web, so photographs of patients never leave the device. The segmentation network is a U-Net whose encoder is a MobileNetV2 pretrained on ImageNet. It receives a 256 by 256 image, carries a full resolution skip connection from the input to sharpen boundaries, and is exported to ONNX at about ten megabytes. At inference the probability map is averaged over the original image and its horizontal and vertical flips, then resampled to the working resolution of the photograph, which is capped at 1400 pixels on the long side.
40
+
41
+ Training used two data sources. The Foot Ulcer Segmentation Challenge collection supplied 810 training and 200 validation images with careful expert masks. The WoundSeg collection supplied 2686 images across eight wound types, but visual inspection showed that many masks were blocky and some covered peri wound skin. We therefore refined them with GrabCut, using the eroded coarse mask and confident model pixels as foreground seeds, and then removed edge pixels whose CIELAB colour matched the surrounding skin. This kept 1987 images. The first round trained on the foot ulcer images for 16 epochs. The second round continued for 7 epochs on the foot ulcer images, counted twice, together with 800 refined WoundSeg images. Optimisation used AdamW with a one cycle schedule and a loss that summed binary cross entropy and Dice loss. All training ran on a CPU.
42
+
43
+ A photograph carries no absolute scale, so the program does not report centimetres until the user supplies one. The user may mark two points on an object of known length, outline the patient's palm, which is taken as 0.8 percent of body surface area, or enter the camera distance and the 35 mm equivalent focal length. The expected length error is about two percent for a reference object, eight percent for camera distance, and ten percent for the palm, and the area error is roughly twice these values. Boundary uncertainty is estimated by sweeping the probability threshold and is combined with the calibration error in quadrature. Percent total body surface area equals the wound area divided by the Mosteller body surface area. A rough estimate of tissue composition is obtained from CIELAB colour relative to the peri wound skin, and it is meant as a screening aid and not as a histological result.
44
+
45
+ The planning module works from the calibrated mask. For closure it solves, by bisection, the smallest fusiform ellipse with a chosen length to width ratio and a 30 degree apex angle that contains the whole defect, and it places an odd number of interrupted sutures with equal spacing and numbers them in the order of the rule of halves. Flaps, Z plasty with the usual theoretical gains of 25, 50, 75, 100, and 120 percent for angles of 30, 45, 60, 75, and 90 degrees, and skin graft templates are drawn as geometric markings. A reconstructive decision step then chooses between primary closure, graft, and flap from the state of the wound bed, exposed structures, osteomyelitis, prior irradiation, anatomical region, and size. For grafts it compares the donor area needed with the area available, which is estimated from the body surface area, Lund and Browder regional fractions, and a usable fraction for each donor. For flaps it ranks 22 local, regional, and free candidates by region, defect size, and patient factors such as diabetes, peripheral arterial disease, and smoking. The donor map draws a front and back mannequin at the patient's height with Drillis and Contini segment proportions, the wound, and the numbered donor sites with their dimensions. A simulated postoperative image is produced by filling the planned region from surrounding skin and drawing the closure line, and it is only an illustration.
46
+
47
+ <p align="center">
48
+ <img src="docs/figures/fig2_skin_graft_and_donor_plan.jpg" width="100%" alt="Figure 2. Planning sheet for a large dehiscence wound closed with a split thickness skin graft. The sheet combines the annotated photograph, the graft template with mesh pattern, a simulated result, the quantitative table, and the ranked donor sites on a mannequin drawn to the height of the patient. The scale is assumed for illustration.">
49
+ </p>
50
+ <p align="center"><sub><em>Figure 2. Planning sheet for a large dehiscence wound closed with a split thickness skin graft. The sheet combines the annotated photograph, the graft template with mesh pattern, a simulated result, the quantitative table, and the ranked donor sites on a mannequin drawn to the height of the patient. The scale is assumed for illustration.</em></sub></p>
51
+
52
+ <p align="center">
53
+ <img src="docs/figures/fig3_vy_flap_plan.jpg" width="100%" alt="Figure 3. Planning sheet for a V to Y advancement flap on a sacral pressure injury, showing the flap base, the incision lines, the direction of advancement, and the estimated number of sutures.">
54
+ </p>
55
+ <p align="center"><sub><em>Figure 3. Planning sheet for a V to Y advancement flap on a sacral pressure injury, showing the flap base, the incision lines, the direction of advancement, and the estimated number of sutures.</em></sub></p>
56
+
57
+ <p align="center">
58
+ <img src="docs/figures/fig4_free_flap_and_donor_map_plan.jpg" width="100%" alt="Figure 4. Planning sheet for a wide leg defect with exposed bone. The decision step selects a flap, the ranked list places a gastrocnemius muscle flap first for the proximal third of the leg, and a free anterolateral thigh flap from the opposite side appears among the later options.">
59
+ </p>
60
+ <p align="center"><sub><em>Figure 4. Planning sheet for a wide leg defect with exposed bone. The decision step selects a flap, the ranked list places a gastrocnemius muscle flap first for the proximal third of the leg, and a free anterolateral thigh flap from the opposite side appears among the later options.</em></sub></p>
61
+
62
+ ## Validation and limitations
63
+
64
+ On the 200 foot ulcer validation images the final model reached a Dice coefficient of 0.827 and an intersection over union of 0.744, with a median relative area error of 11.5 percent. The first round alone gave 0.803. Because these images also chose the best epoch, the figures are somewhat optimistic. On 160 Medetec images that the model had never seen, the Dice coefficient was 0.793 and the median area error was 23.9 percent. The geometry code was checked against shapes with known formulas. Areas agreed within 0.07 percent, perimeters of smooth shapes within 0.2 percent, and the perimeter of a rectangle with sharp corners within 0.93 percent. An automated stress test built 484 surgical plans, 30 planning sheets, and 146 random clinical combinations without a failure.
65
+
66
+ We also tested three ideas that seemed likely to help and did not. Running the network again on a crop around the first detection lowered the Dice coefficient from 0.859 to 0.794 on 95 validation images. Refining the mask with MobileSAM and a box prompt was accepted by our consistency rule for only 4 of the 95 images and did not improve the score. Averaging predictions at 256, 320, and 384 pixels changed the Dice coefficient from 0.8606 to 0.8616, which does not justify the extra computation, and an input of 512 pixels failed at 0.668 because it lies far from the training scale.
67
+
68
+ A qualitative test used 31 photographs from Wikimedia Commons that cover burns, bites, abrasions, lacerations, ulcers, pressure injuries, and dehiscence. Segmentation was reliable for dehiscence, diabetic foot ulcers, large pressure injuries including black eschar, linear lacerations, and blistered burns. It failed for small puncture wounds, thin diffuse abrasions, and an ulcerating carcinoma, and it produced false positives on photographs that contained no wound. The training data are dominated by chronic wounds, and there is no public collection with burn depth labels, so acute wounds and burns remain the weakest area. A brush and a tap tool allow the user to correct the mask.
69
+
70
+ <p align="center">
71
+ <img src="docs/figures/fig5_segmentation_examples.jpg" width="100%" alt="Figure 5. Automatic segmentation on public photographs that were not used for training. The cyan outline marks the predicted wound area.">
72
+ </p>
73
+ <p align="center"><sub><em>Figure 5. Automatic segmentation on public photographs that were not used for training. The cyan outline marks the predicted wound area.</em></sub></p>
74
+
75
+ The clinical content, which covers dosing, thresholds, closure limits, flap size ranges, and donor dimensions, was written from general surgical and wound care literature and has not been checked line by line against the source guidelines. Skin laxity, perforator anatomy, vascular status, and the direction of relaxed skin tension lines cannot be measured from a two dimensional photograph, so every marking is a proposal that the surgeon must confirm on the patient. Malignancy cannot be decided from a photograph, and the program only raises suspicion and suggests biopsy. WoundScan is a research prototype and not a medical device.
76
+
77
+ ## Software and reproducibility
78
+
79
+ The static site lives in the app folder. To run it locally, start the bundled server and open the address in a browser. The server sends no cache headers, which keeps the development copy current.
80
+
81
+ ```bash
82
+ python serve.py
83
+ ```
84
+
85
+ On Windows the file run_windows.bat does the same. To publish the site, import the repository in Vercel with the framework preset set to Other and an empty build command, because vercel.json already points to the app folder. Training and evaluation scripts are in the train folder and need the public datasets placed in a data folder. The three stages run in sequence.
86
+
87
+ ```bash
88
+ python train/train.py round1 16
89
+ python train/train.py refine
90
+ python train/train.py round2 7
91
+ ```
92
+
93
+ Persistent identifiers for the protocol and the archived release will be added at the top of this page once the OSF project and the Zenodo record are created.
94
+
95
+ ## Data and licensing
96
+
97
+ The released weights were trained on WoundSeg, which is licensed CC BY NC 4.0, and on the Foot Ulcer Segmentation Challenge images, which carry no written licence. The weights should therefore be treated as research and non commercial material, and clinical or commercial use needs permission from the dataset owners or retraining on local data. The burn dataset EBIS is available only on academic request and is not included. Wikimedia Commons photographs used for the qualitative test are not redistributed, and their sources are listed in webtest/sources.tsv. Photographs shown in the figures come from Wikimedia Commons and are credited in docs/figures/CREDITS.md. The repository contains no patient data. A software licence has not yet been attached.
98
+
99
+ ## Citation
100
+
101
+ ```bibtex
102
+ @software{rafi_woundscan,
103
+ author = {Rafi, Muhammad Allam and Afrilia, Cindy Rizky},
104
+ title = {Calibrated Wound Segmentation and Reconstructive Surgical Planning from Clinical Photographs: A Bioinformatic and Deep Learning Study},
105
+ year = {2026},
106
+ doi = {10.5281/zenodo.XXXXXXX},
107
+ note = {OSF 10.17605/OSF.IO/XXXXX}
108
+ }
109
+ ```
110
+
111
+ ## References
112
+
113
+ Wang C, Anisuzzaman DM, Williamson V, Dhar MK, Rostami B, Niezgoda J, Gopalakrishnan S, Yu Z. Fully automatic wound segmentation with deep convolutional neural networks. Scientific Reports. 2020. 10, 21897. doi 10.1038/s41598-020-78799-w
114
+
115
+ Oota SR, Rowtula V, Mohammed S, Liu M, Gupta M. WSNet, towards an effective method for wound image segmentation. IEEE/CVF Winter Conference on Applications of Computer Vision. 2023. 3234 to 3243.
116
+
117
+ Curti N, Merli Y, Zengarini C, Giampieri E, Merlotti A, Dall'Olio D, Marcelli E, Bianchi T, Castellani G. Effectiveness of semi supervised active learning in automated wound image segmentation. International Journal of Molecular Sciences. 2023. 24, 706.
118
+
119
+ Ronneberger O, Fischer P, Brox T. U-Net, convolutional networks for biomedical image segmentation. Medical Image Computing and Computer Assisted Intervention. 2015.
120
+
121
+ Sandler M, Howard A, Zhu M, Zhmoginov A, Chen LC. MobileNetV2, inverted residuals and linear bottlenecks. IEEE Conference on Computer Vision and Pattern Recognition. 2018.
122
+
123
+ Rother C, Kolmogorov V, Blake A. GrabCut, interactive foreground extraction using iterated graph cuts. ACM Transactions on Graphics. 2004. 23, 309 to 314.
124
+
125
+ Mosteller RD. Simplified calculation of body surface area. New England Journal of Medicine. 1987. 317, 1098.
126
+
127
+ Lund CC, Browder NC. The estimation of areas of burns. Surgery, Gynecology and Obstetrics. 1944. 79, 352 to 358.
128
+
129
+ Drillis R, Contini R. Body segment parameters. Office of Vocational Rehabilitation, New York University. 1966.
130
+
131
+ Janis JE, Kwon RK, Attinger CE. The new reconstructive ladder, modifications to the traditional model. Plastic and Reconstructive Surgery. 2011. 127.
132
+
133
+ ## Python package
134
+
135
+ See the [Python installation and integration guide](docs/PYPI_README.md) for the importable API, examples, tests and development instructions.
@@ -0,0 +1,112 @@
1
+ # WoundScan for Python
2
+
3
+ Calibrated binary-mask measurements and local ONNX segmentation for research pipelines.
4
+
5
+ Install with `pip install woundscan`. Requires Python 3.10 or later.
6
+
7
+ [Source](https://github.com/sharing-123/WoundScan) | [Issues](https://github.com/sharing-123/WoundScan/issues) | [OSF](https://doi.org/10.17605/OSF.IO/KV3SP) | [Zenodo](https://doi.org/10.5281/zenodo.24412818)
8
+
9
+ ## Measure any binary mask
10
+
11
+ ```python
12
+ import json
13
+ import numpy as np
14
+ from woundscan import measure_mask, reference_scale
15
+
16
+ mask = np.zeros((100, 100), dtype=bool)
17
+ mask[20:40, 30:60] = True
18
+ scale = reference_scale(reference_pixels=100, reference_mm=10)
19
+ result = measure_mask(mask, scale, height_cm=170, weight_kg=70)
20
+ print(result.area_mm2) # 6.0
21
+ print(result.perimeter_mm) # 10.0
22
+ print(json.dumps(result.to_dict(), indent=2))
23
+ ```
24
+
25
+ The API accepts masks from any segmentation model or manual annotation pipeline.
26
+ Measurements use millimetres and square millimetres. Mosteller body surface area
27
+ uses height in centimetres and weight in kilograms. Supply both to calculate
28
+ `tbsa_percent`, otherwise it is `None`. A reference must lie in the wound plane.
29
+ Curved surfaces, perspective and calibration uncertainty affect accuracy.
30
+
31
+ ## Optional segmentation
32
+
33
+ Install with `pip install "woundscan[inference]"`.
34
+
35
+ ```python
36
+ import cv2
37
+ from woundscan import Segmenter, measure_mask
38
+
39
+ model = Segmenter("/path/to/wound_seg.onnx")
40
+ bgr = cv2.imread("/path/to/image.png")
41
+ if bgr is None:
42
+ raise ValueError("Image could not be loaded")
43
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
44
+ probability = model.predict(rgb)
45
+ mask = model.segment(rgb, threshold=0.5)
46
+ result = measure_mask(mask, mm_per_pixel=0.1)
47
+ ```
48
+
49
+ Supply a model you have permission to use. No weights or network downloads are
50
+ included. Inference uses ONNX Runtime CPU, with float32 RGB input [1,3,256,256]
51
+ in [0,1] and probability output [1,1,256,256]. The recipe follows the repository
52
+ Python evaluation script, averaging original, horizontal and vertical flips.
53
+ Set `tta=False` for a single pass. Invalid probabilities and logits are rejected.
54
+
55
+ ## API
56
+
57
+ | Function | Result |
58
+ | --- | --- |
59
+ | reference_scale(reference_pixels, reference_mm) | Millimetres per pixel |
60
+ | body_surface_area(height_cm, weight_kg) | Mosteller BSA in square metres |
61
+ | measure_mask(mask, mm_per_pixel, height_cm=None, weight_kg=None) | Immutable Measurement; height and weight are keyword-only |
62
+ | Measurement.to_dict() | JSON-compatible dictionary |
63
+ | Segmenter(model_path).predict(rgb, tta=True) | Original-resolution probability array; tta is keyword-only |
64
+ | Segmenter(model_path).segment(rgb, threshold=0.5, tta=True) | Boolean mask; threshold and tta are keyword-only |
65
+
66
+ Functions compose with notebooks, batch processing and APIs. Import starts no
67
+ server, downloads no models and performs no inference. Model loading occurs only
68
+ when a Segmenter is constructed.
69
+
70
+ ## Scope and evidence
71
+
72
+ Version 0.1 provides measurement and optional inference. Browser reconstructive
73
+ planning, tissue analysis, donor mapping and interactive editing remain in the
74
+ GitHub application and are not exported by this Python API.
75
+
76
+ Area counts foreground pixel cells across all components. Perimeter counts
77
+ exposed pixel edges, including holes. This lattice perimeter is orientation
78
+ dependent and differs from the browser's smoothed subpixel contour algorithm.
79
+ Inference does not apply browser smoothing, component removal or hole filling.
80
+ Final masks can therefore differ from browser masks.
81
+
82
+ The repository model evaluation reported Dice 0.827 on 200 validation images and
83
+ 0.793 on 160 external images. These describe that evaluation, not a guarantee
84
+ for this package or new photographs. Small punctures and thin abrasions were
85
+ important failure modes. The software is a research prototype without clinical
86
+ validation and must not replace clinical judgement.
87
+
88
+ ## Licensing and model rights
89
+
90
+ The Python package, tests and package documentation use MIT. Wheels and source
91
+ archives exclude model weights, photographs, datasets and browser libraries.
92
+ Repository weights were trained on restricted noncommercial datasets and data
93
+ without a documented redistribution license. Obtain appropriate permissions or
94
+ train with suitably licensed data. MIT does not relicense these assets. PyPI
95
+ hosting does not certify scientific accuracy or clinical suitability.
96
+
97
+ ## Development
98
+
99
+ Clone the repository and create a virtual environment, then run:
100
+
101
+ ```bash
102
+ pip install -e ".[test,inference]" build twine
103
+ pytest
104
+ python -m build
105
+ python -m twine check dist/*
106
+ ```
107
+
108
+ Tests cover known geometry, units, input validation and inference transforms.
109
+ Default measurement tests require no model weights. Bug reports should include
110
+ package versions and a minimal example without identifying patient information.
111
+
112
+ Authors: Muhammad Allam Rafi and Cindy Rizky Afrilia.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "woundscan"
7
+ version = "0.1.0"
8
+ description = "Composable calibrated wound-mask measurement and optional ONNX segmentation for research"
9
+ readme = "docs/PYPI_README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Muhammad Allam Rafi"}, {name = "Cindy Rizky Afrilia"}]
14
+ dependencies = ["numpy>=1.23"]
15
+ keywords = ["wound", "segmentation", "medical-imaging", "calibration", "research"]
16
+ classifiers = ["Development Status :: 3 - Alpha", "Programming Language :: Python :: 3", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Image Processing", "Intended Audience :: Science/Research"]
17
+
18
+ [project.optional-dependencies]
19
+ inference = ["onnxruntime>=1.17", "opencv-python-headless>=4.8"]
20
+ test = ["pytest>=8"]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/sharing-123/WoundScan"
24
+ Repository = "https://github.com/sharing-123/WoundScan"
25
+ Issues = "https://github.com/sharing-123/WoundScan/issues"
26
+ Documentation = "https://github.com/sharing-123/WoundScan/blob/main/docs/PYPI_README.md"
27
+ "OSF registration" = "https://doi.org/10.17605/OSF.IO/KV3SP"
28
+ "Zenodo archive" = "https://doi.org/10.5281/zenodo.24412818"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
32
+
33
+ [tool.pytest.ini_options]
34
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Composable wound measurement tools. Research use; no clinical validation."""
2
+ from .measurement import Measurement, measure_mask, reference_scale, body_surface_area
3
+ from .inference import Segmenter
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["Measurement", "measure_mask", "reference_scale", "body_surface_area", "Segmenter"]
@@ -0,0 +1,57 @@
1
+ """Optional ONNX inference matching the repository's Python evaluation recipe."""
2
+ from pathlib import Path
3
+ import numpy as np
4
+
5
+
6
+ class Segmenter:
7
+ """Load a caller-supplied WoundScan-compatible ONNX probability model.
8
+
9
+ Contract: float32 RGB [1,3,256,256] in [0,1], output [1,1,256,256]
10
+ probabilities. No weights or network downloads are included in this package.
11
+ """
12
+ def __init__(self, model_path):
13
+ path = Path(model_path)
14
+ if not path.is_file():
15
+ raise FileNotFoundError(path)
16
+ try:
17
+ import cv2
18
+ import onnxruntime as ort
19
+ except ImportError as exc:
20
+ raise ImportError('Install optional inference support: pip install "woundscan[inference]"') from exc
21
+ self._cv2 = cv2
22
+ self._session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
23
+ inputs = self._session.get_inputs()
24
+ if len(inputs) != 1 or inputs[0].shape != [1, 3, 256, 256] or inputs[0].type != "tensor(float)":
25
+ raise ValueError("Model must accept one float32 tensor of shape [1,3,256,256]")
26
+ self._input = inputs[0].name
27
+
28
+ def predict(self, rgb, *, tta=True) -> np.ndarray:
29
+ """Return H x W float32 probabilities from an H x W x 3 uint8 RGB image.
30
+
31
+ TTA averages original, horizontal-flip and vertical-flip probabilities.
32
+ No browser mask smoothing, component filtering or hole filling is applied.
33
+ """
34
+ image = np.asarray(rgb)
35
+ if image.ndim != 3 or image.shape[2] != 3 or not image.size or image.dtype != np.uint8:
36
+ raise ValueError("rgb must be a nonempty H x W x 3 uint8 array")
37
+ cv2 = self._cv2
38
+ x = cv2.resize(image, (256, 256), interpolation=cv2.INTER_AREA).astype(np.float32) / 255
39
+ x = x.transpose(2, 0, 1)[None]
40
+ def run(a):
41
+ result = self._session.run(None, {self._input: np.ascontiguousarray(a)})[0]
42
+ if result.shape != (1, 1, 256, 256):
43
+ raise ValueError("Model output must have shape [1,1,256,256]")
44
+ p = result[0, 0]
45
+ if not np.isfinite(p).all() or p.min() < 0 or p.max() > 1:
46
+ raise ValueError("Model output must contain probabilities in [0,1]")
47
+ return p
48
+ p = run(x)
49
+ if tta:
50
+ p = (p + run(x[..., ::-1])[:, ::-1] + run(x[:, :, ::-1])[::-1]) / 3
51
+ return cv2.resize(p, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_LINEAR)
52
+
53
+ def segment(self, rgb, *, threshold=0.5, tta=True) -> np.ndarray:
54
+ """Return a boolean mask using strict probability > threshold."""
55
+ if not np.isfinite(threshold) or not 0 <= threshold <= 1:
56
+ raise ValueError("threshold must be finite and between 0 and 1")
57
+ return self.predict(rgb, tta=tta) > threshold
@@ -0,0 +1,59 @@
1
+ """Calibrated pixel-cell geometry with explicit units."""
2
+ from dataclasses import asdict, dataclass
3
+ import math
4
+ import numpy as np
5
+
6
+
7
+ def _positive(value, name):
8
+ try:
9
+ value = float(value)
10
+ except (TypeError, ValueError):
11
+ raise ValueError(f"{name} must be a positive finite number") from None
12
+ if not math.isfinite(value) or value <= 0:
13
+ raise ValueError(f"{name} must be a positive finite number")
14
+ return value
15
+
16
+
17
+ def reference_scale(reference_pixels: float, reference_mm: float) -> float:
18
+ """Return millimetres per pixel from a coplanar reference length."""
19
+ return _positive(reference_mm, "reference_mm") / _positive(reference_pixels, "reference_pixels")
20
+
21
+
22
+ def body_surface_area(height_cm: float, weight_kg: float) -> float:
23
+ """Mosteller body surface area, in square metres."""
24
+ return math.sqrt(_positive(height_cm, "height_cm") * _positive(weight_kg, "weight_kg") / 3600)
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Measurement:
29
+ """Pixel-cell area/perimeter, including holes and disconnected components."""
30
+ area_mm2: float
31
+ perimeter_mm: float
32
+ foreground_pixels: int
33
+ mm_per_pixel: float
34
+ tbsa_percent: float | None = None
35
+
36
+ def to_dict(self) -> dict:
37
+ """Return JSON-serializable scalar values."""
38
+ return asdict(self)
39
+
40
+
41
+ def measure_mask(mask, mm_per_pixel: float, *, height_cm=None, weight_kg=None) -> Measurement:
42
+ """Measure a nonempty 2D boolean or binary 0/1 mask.
43
+
44
+ Perimeter counts exposed pixel edges, NOT a smooth subpixel contour.
45
+ This lattice perimeter is orientation dependent and differs from the browser
46
+ contour method. Empty foreground is allowed and measures zero.
47
+ """
48
+ scale = _positive(mm_per_pixel, "mm_per_pixel")
49
+ a = np.asarray(mask)
50
+ if a.ndim != 2 or not a.size or a.dtype.kind not in "buif" or not np.isin(a, [0, 1]).all():
51
+ raise ValueError("mask must be a nonempty 2D array containing only 0 and 1")
52
+ a = np.pad(a.astype(np.int8), 1)
53
+ count = int(a.sum())
54
+ edges = int(np.abs(np.diff(a, axis=0)).sum() + np.abs(np.diff(a, axis=1)).sum())
55
+ if (height_cm is None) != (weight_kg is None):
56
+ raise ValueError("height_cm and weight_kg must be supplied together")
57
+ area = count * scale**2
58
+ tbsa = None if height_cm is None else 100 * area / (body_surface_area(height_cm, weight_kg) * 1_000_000)
59
+ return Measurement(area, edges * scale, count, scale, tbsa)
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: woundscan
3
+ Version: 0.1.0
4
+ Summary: Composable calibrated wound-mask measurement and optional ONNX segmentation for research
5
+ Author: Muhammad Allam Rafi, Cindy Rizky Afrilia
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sharing-123/WoundScan
8
+ Project-URL: Repository, https://github.com/sharing-123/WoundScan
9
+ Project-URL: Issues, https://github.com/sharing-123/WoundScan/issues
10
+ Project-URL: Documentation, https://github.com/sharing-123/WoundScan/blob/main/docs/PYPI_README.md
11
+ Project-URL: OSF registration, https://doi.org/10.17605/OSF.IO/KV3SP
12
+ Project-URL: Zenodo archive, https://doi.org/10.5281/zenodo.24412818
13
+ Keywords: wound,segmentation,medical-imaging,calibration,research
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
18
+ Classifier: Intended Audience :: Science/Research
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy>=1.23
23
+ Provides-Extra: inference
24
+ Requires-Dist: onnxruntime>=1.17; extra == "inference"
25
+ Requires-Dist: opencv-python-headless>=4.8; extra == "inference"
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest>=8; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # WoundScan for Python
31
+
32
+ Calibrated binary-mask measurements and local ONNX segmentation for research pipelines.
33
+
34
+ Install with `pip install woundscan`. Requires Python 3.10 or later.
35
+
36
+ [Source](https://github.com/sharing-123/WoundScan) | [Issues](https://github.com/sharing-123/WoundScan/issues) | [OSF](https://doi.org/10.17605/OSF.IO/KV3SP) | [Zenodo](https://doi.org/10.5281/zenodo.24412818)
37
+
38
+ ## Measure any binary mask
39
+
40
+ ```python
41
+ import json
42
+ import numpy as np
43
+ from woundscan import measure_mask, reference_scale
44
+
45
+ mask = np.zeros((100, 100), dtype=bool)
46
+ mask[20:40, 30:60] = True
47
+ scale = reference_scale(reference_pixels=100, reference_mm=10)
48
+ result = measure_mask(mask, scale, height_cm=170, weight_kg=70)
49
+ print(result.area_mm2) # 6.0
50
+ print(result.perimeter_mm) # 10.0
51
+ print(json.dumps(result.to_dict(), indent=2))
52
+ ```
53
+
54
+ The API accepts masks from any segmentation model or manual annotation pipeline.
55
+ Measurements use millimetres and square millimetres. Mosteller body surface area
56
+ uses height in centimetres and weight in kilograms. Supply both to calculate
57
+ `tbsa_percent`, otherwise it is `None`. A reference must lie in the wound plane.
58
+ Curved surfaces, perspective and calibration uncertainty affect accuracy.
59
+
60
+ ## Optional segmentation
61
+
62
+ Install with `pip install "woundscan[inference]"`.
63
+
64
+ ```python
65
+ import cv2
66
+ from woundscan import Segmenter, measure_mask
67
+
68
+ model = Segmenter("/path/to/wound_seg.onnx")
69
+ bgr = cv2.imread("/path/to/image.png")
70
+ if bgr is None:
71
+ raise ValueError("Image could not be loaded")
72
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
73
+ probability = model.predict(rgb)
74
+ mask = model.segment(rgb, threshold=0.5)
75
+ result = measure_mask(mask, mm_per_pixel=0.1)
76
+ ```
77
+
78
+ Supply a model you have permission to use. No weights or network downloads are
79
+ included. Inference uses ONNX Runtime CPU, with float32 RGB input [1,3,256,256]
80
+ in [0,1] and probability output [1,1,256,256]. The recipe follows the repository
81
+ Python evaluation script, averaging original, horizontal and vertical flips.
82
+ Set `tta=False` for a single pass. Invalid probabilities and logits are rejected.
83
+
84
+ ## API
85
+
86
+ | Function | Result |
87
+ | --- | --- |
88
+ | reference_scale(reference_pixels, reference_mm) | Millimetres per pixel |
89
+ | body_surface_area(height_cm, weight_kg) | Mosteller BSA in square metres |
90
+ | measure_mask(mask, mm_per_pixel, height_cm=None, weight_kg=None) | Immutable Measurement; height and weight are keyword-only |
91
+ | Measurement.to_dict() | JSON-compatible dictionary |
92
+ | Segmenter(model_path).predict(rgb, tta=True) | Original-resolution probability array; tta is keyword-only |
93
+ | Segmenter(model_path).segment(rgb, threshold=0.5, tta=True) | Boolean mask; threshold and tta are keyword-only |
94
+
95
+ Functions compose with notebooks, batch processing and APIs. Import starts no
96
+ server, downloads no models and performs no inference. Model loading occurs only
97
+ when a Segmenter is constructed.
98
+
99
+ ## Scope and evidence
100
+
101
+ Version 0.1 provides measurement and optional inference. Browser reconstructive
102
+ planning, tissue analysis, donor mapping and interactive editing remain in the
103
+ GitHub application and are not exported by this Python API.
104
+
105
+ Area counts foreground pixel cells across all components. Perimeter counts
106
+ exposed pixel edges, including holes. This lattice perimeter is orientation
107
+ dependent and differs from the browser's smoothed subpixel contour algorithm.
108
+ Inference does not apply browser smoothing, component removal or hole filling.
109
+ Final masks can therefore differ from browser masks.
110
+
111
+ The repository model evaluation reported Dice 0.827 on 200 validation images and
112
+ 0.793 on 160 external images. These describe that evaluation, not a guarantee
113
+ for this package or new photographs. Small punctures and thin abrasions were
114
+ important failure modes. The software is a research prototype without clinical
115
+ validation and must not replace clinical judgement.
116
+
117
+ ## Licensing and model rights
118
+
119
+ The Python package, tests and package documentation use MIT. Wheels and source
120
+ archives exclude model weights, photographs, datasets and browser libraries.
121
+ Repository weights were trained on restricted noncommercial datasets and data
122
+ without a documented redistribution license. Obtain appropriate permissions or
123
+ train with suitably licensed data. MIT does not relicense these assets. PyPI
124
+ hosting does not certify scientific accuracy or clinical suitability.
125
+
126
+ ## Development
127
+
128
+ Clone the repository and create a virtual environment, then run:
129
+
130
+ ```bash
131
+ pip install -e ".[test,inference]" build twine
132
+ pytest
133
+ python -m build
134
+ python -m twine check dist/*
135
+ ```
136
+
137
+ Tests cover known geometry, units, input validation and inference transforms.
138
+ Default measurement tests require no model weights. Bug reports should include
139
+ package versions and a minimal example without identifying patient information.
140
+
141
+ Authors: Muhammad Allam Rafi and Cindy Rizky Afrilia.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ docs/PYPI_README.md
6
+ src/woundscan/__init__.py
7
+ src/woundscan/inference.py
8
+ src/woundscan/measurement.py
9
+ src/woundscan.egg-info/PKG-INFO
10
+ src/woundscan.egg-info/SOURCES.txt
11
+ src/woundscan.egg-info/dependency_links.txt
12
+ src/woundscan.egg-info/requires.txt
13
+ src/woundscan.egg-info/top_level.txt
14
+ tests/test_api.py
@@ -0,0 +1,8 @@
1
+ numpy>=1.23
2
+
3
+ [inference]
4
+ onnxruntime>=1.17
5
+ opencv-python-headless>=4.8
6
+
7
+ [test]
8
+ pytest>=8
@@ -0,0 +1 @@
1
+ woundscan
@@ -0,0 +1,78 @@
1
+ import math
2
+ import numpy as np
3
+ import pytest
4
+ from woundscan import measure_mask, reference_scale, body_surface_area, Segmenter
5
+
6
+
7
+ def test_rectangle():
8
+ m = np.zeros((20,30), dtype=bool)
9
+ m[2:12,5:25] = True
10
+ result = measure_mask(m, .5, height_cm=180, weight_kg=80)
11
+ assert result.area_mm2 == 50
12
+ assert result.perimeter_mm == 30
13
+ assert result.tbsa_percent == pytest.approx(.0025)
14
+ assert result.to_dict()['foreground_pixels'] == 200
15
+
16
+
17
+ def test_holes_and_empty():
18
+ m = np.ones((3,3), dtype=int); m[1,1] = 0
19
+ assert measure_mask(m,1).perimeter_mm == 16
20
+ assert measure_mask(m,1).area_mm2 == 8
21
+ assert measure_mask(np.zeros((2,3)),1).area_mm2 == 0
22
+
23
+
24
+ def test_units():
25
+ assert reference_scale(100,10) == .1
26
+ assert body_surface_area(180,80) == 2
27
+
28
+
29
+ @pytest.mark.parametrize('bad',[0,-1,math.nan,math.inf])
30
+ def test_bad_scale(bad):
31
+ with pytest.raises(ValueError): measure_mask([[1]],bad)
32
+
33
+
34
+ @pytest.mark.parametrize('bad',[[],[1,0],[[0,2]],[[math.nan]],[[.5]], [['bad']]])
35
+ def test_bad_mask(bad):
36
+ with pytest.raises(ValueError): measure_mask(bad,1)
37
+
38
+
39
+ def test_pair():
40
+ with pytest.raises(ValueError): measure_mask([[1]],1,height_cm=170)
41
+
42
+
43
+ def test_missing_model():
44
+ with pytest.raises(FileNotFoundError): Segmenter('nonexistent.onnx')
45
+
46
+
47
+ def test_inference_transforms():
48
+ cv2=pytest.importorskip('cv2')
49
+ class Session:
50
+ def run(self,outputs,feed): return [feed['x'][:,:1]]
51
+ model=Segmenter.__new__(Segmenter)
52
+ model._session,model._input,model._cv2=Session(),'x',cv2
53
+ rgb=np.zeros((256,256,3),dtype=np.uint8)
54
+ rgb[:,:,0]=np.arange(256,dtype=np.uint8)[None,:]
55
+ expected=rgb[:,:,0].astype(np.float32)/255
56
+ np.testing.assert_allclose(model.predict(rgb),expected,atol=1e-7)
57
+ np.testing.assert_array_equal(model.segment(rgb),expected>.5)
58
+ with pytest.raises(ValueError): model.predict(rgb.astype(float))
59
+
60
+
61
+ def test_geometry_invariants():
62
+ rng=np.random.default_rng(73)
63
+ for _ in range(50):
64
+ m=rng.integers(0,2,(13,17))
65
+ original=measure_mask(m,.2)
66
+ for transformed in [m.T,np.flipud(m),np.fliplr(m),np.pad(m,4)]:
67
+ result=measure_mask(transformed,.2)
68
+ assert result.area_mm2 == original.area_mm2
69
+ assert result.perimeter_mm == original.perimeter_mm
70
+ scaled=measure_mask(m,.4)
71
+ assert scaled.area_mm2 == pytest.approx(original.area_mm2*4)
72
+ assert scaled.perimeter_mm == pytest.approx(original.perimeter_mm*2)
73
+
74
+
75
+ @pytest.mark.parametrize("bad", [np.array([[1+0j]]), np.array([[1]], dtype=object)])
76
+ def test_non_numeric_mask_types(bad):
77
+ with pytest.raises(ValueError):
78
+ measure_mask(bad, 1)