File size: 13,642 Bytes
b0c2f3b
b21f8dc
 
 
 
b0c2f3b
b21f8dc
 
b0c2f3b
b21f8dc
873d3e7
b0c2f3b
 
b21f8dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae887fc
 
 
b21f8dc
 
ae887fc
 
 
 
 
 
 
 
 
b21f8dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
---
title: Fiberpose
emoji: 🧡
colorFrom: blue
colorTo: green
sdk: gradio
sdk_version: 6.32.0
python_version: "3.12"
app_file: app.py
license: gpl-3.0
short_description: Fiber segmentation and morphometry for microscopy images
---

# Fiberpose

**Fiberpose** is a research software package for segmentation and quantitative morphometry of fibrous microstructures. Instead of relying on threshold-based binarization, Fiberpose predicts a neural distance-transform field from microscopy images and uses it as a geometric representation for centerline extraction, instance segmentation, diameter measurement, orientation analysis, and pore statistics.

It is designed for fibrous materials where conventional thresholding becomes fragile: dense networks, weak contrast, uneven illumination, touching fibers, and overlapping structures.

![Fiberpose desktop GUI: instance segmentation with diameter measurements, diameter and orientation histograms](docs/gui.png)

**Try it in the browser:** [Fiberpose on Hugging Face Spaces](https://huggingface.co/spaces/vikba/fiberpose) β€” no installation needed.

> Status: research-preview software under active development. Validate outputs on your own data before using them for publication or production decisions.

---

## Key features

- **Neural distance-transform prediction** from raw microscopy images.
- **Fiber centerline extraction** using ridge detection on the predicted distance-transform field.
- **Instance segmentation** of fiber fragments using marker-controlled watershed or radial expansion modes.
- **Morphometric analysis** of fiber diameter, orientation, orientation index, porosity, and pore-size distributions.
- **Interactive desktop GUI** for loading images, inspecting intermediate maps, adjusting parameters, visualizing overlays, and exporting results.
- **Batch-oriented CLI** for reproducible processing of folders and image stacks.
- **Publication-oriented exports**: distance-transform maps, labels, overlays, diameter/orientation overlays, measurement tables, summaries, and manifests.

---

## Method overview

Fiberpose follows a simple geometric pipeline:

1. A neural network predicts a continuous distance-transform field from the input image.
2. Centerlines are extracted as ridges of this field.
3. Fiber instances are separated using centerline markers and distance-transform geometry.
4. Measurements are sampled along centerlines:
   - local radius is one pixel plus the mean distance-transform value sampled one pixel away on each side,
   - local orientation is estimated from the distance field gradients,
   - pore sizes are estimated from the distance transform of the void space.

This makes the distance-transform field the central representation connecting neural inference, segmentation, and quantitative analysis.

---

## Installation

Fiberpose requires Python 3.10 or newer. A fresh conda or virtual environment is recommended.

```bash
git clone https://github.com/vikba/Fiberpose.git
cd Fiberpose

conda create -n fiberpose python=3.11 -y
conda activate fiberpose

pip install -e ".[gui]"
```

This installs Fiberpose in editable mode: changes to the code in `src/fiberpose/` take effect without reinstalling. Use `pip install -e .` (without `[gui]`) for the CLI and Python API only, without Qt dependencies.

### GPU note

Fiberpose runtime inference uses ONNX Runtime. GPU acceleration is available only if your installed ONNX Runtime build exposes `CUDAExecutionProvider`. If CUDA is unavailable, Fiberpose automatically falls back to CPU execution.

GPU inference needs an NVIDIA GPU with CUDA on Linux or Windows; it is not available on macOS. After installing Fiberpose, replace the CPU build of ONNX Runtime with the GPU build (the two cannot be installed side by side):

```bash
pip uninstall -y onnxruntime
pip install onnxruntime-gpu
```

Running `pip install -e .` again reinstalls the CPU build, so repeat these two commands afterwards.

---

## Pretrained model

The default model, `R108_dt_fg.onnx`, ships with the repository in `checkpoints/`, so a source checkout works offline. Fiberpose looks for models, by file name, in this order:

1. the folder set in the `FIBERPOSE_MODELS_DIR` environment variable;
2. `checkpoints/` in the repository, when running from a source checkout;
3. the per-user cache (for example `~/Library/Caches/fiberpose/models` on macOS).

To use your own ONNX model, place it in one of these folders and select it in the GUI, or set `model_path` in the configuration to its file name or absolute path.

---

## Running Fiberpose

The `fiberpose` command launches both GUI and CLI modes. `python -m fiberpose` is equivalent.

### GUI mode

```bash
fiberpose
```

or explicitly:

```bash
fiberpose --gui
```

The GUI supports:

- single image, folder, and stack loading;
- raw image, distance-transform, gradient-magnitude, Laplacian, centerline, segmentation, overlay, pore, diameter, and orientation views;
- model selection and CPU/GPU toggle;
- scalebar calibration;
- DT profile plotting;
- batch processing;
- export of masks, overlays, and CSV tables.

### CLI mode

Run segmentation on an image, folder, or stack:

```bash
fiberpose --cli --input /path/to/image_or_folder_or_stack
```

Run the full measurement pipeline:

```bash
fiberpose --cli --input /path/to/image_or_folder_or_stack --measurements
```

Write outputs to a selected directory:

```bash
fiberpose --cli --input /path/to/image_or_folder_or_stack --output /path/to/output
```

Use a custom config:

```bash
fiberpose --cli --input /path/to/image_or_folder_or_stack --config /path/to/config.json
```

Export only measurement CSV files:

```bash
fiberpose --cli --input /path/to/image_or_folder_or_stack --measurements --save-kind csv
```

### CLI arguments

| Argument | Description |
|---|---|
| `--gui` | Force GUI mode. |
| `--cli` | Run command-line processing mode. |
| `--input <path>` | Input image, folder, or stack. Required in CLI mode. |
| `--config <path>` | Path to a JSON configuration file. Default: the user configuration file (see Configuration below). |
| `--output <dir>` | Output directory for exported files. |
| `--measurements` | Run full measurement pipeline. Without this flag, CLI runs segmentation-only. |
| `--invert` | Invert image intensities before inference. Useful when fibers are dark on a bright background. |
| `--save-kind results\|csv` | Export full result artifacts or only CSV measurement tables. Default: `results`. |
| `--version` | Print the Fiberpose version and exit. |

### CLI exit codes

| Code | Meaning |
|---|---|
| `0` | Processing finished without failures. |
| `1` | Processing finished, but one or more frames failed during processing or export. |
| `2` | Invalid arguments, missing input/config/model, or startup/runtime error. |

### Web interface

A hosted version runs at <https://huggingface.co/spaces/vikba/fiberpose>. To run it locally, from the repository folder:

```bash
pip install -e ".[web]"
fiberpose --web            # http://localhost:7860
```

The same page runs in Docker (`docker build -t fiberpose . && docker run -p 7860:7860 fiberpose`)
and as a Hugging Face Gradio Space; `.github/workflows/deploy.yml` publishes both on a version tag.

### Python API

```python
import imageio.v3 as iio
import fiberpose

image = iio.imread("fibers.tif")
result = fiberpose.analyze(image, pixel_size=0.1, unit="um")

print(result.summary["diam_mean"], result.summary["orientation_index"])
result.labels               # instance labels (0 = background)
result.distance_transform   # predicted distance-transform field
result.diameters            # per-sample diameters in `unit`
```

Pass a `fiberpose.AppConfig` as the second argument to change model or analysis parameters.

---

## Supported inputs

Fiberpose can process common microscopy image formats, including:

```text
.tif, .tiff, .png, .jpg, .jpeg, .bmp, .webp
```

Folders are processed as batches. Multi-page TIFF files and image stacks are treated as stack inputs.

---

## Outputs

Depending on the selected export options, Fiberpose can save:

| Output | Description |
|---|---|
| `*_dt` | Predicted distance-transform map. |
| `*_labels` | Instance label visualization. |
| `*_overlay` | Segmentation overlay on the original image. |
| `*_diameters` | Diameter measurement overlay. |
| `*_orientations` | Orientation measurement overlay. |
| `*_outline` | Segmentation outline image. |
| `*_samples.csv` | Per-sample measurement table. |
| `*_summary.csv` | Batch-level summary table. |
| `manifest.json` | Export manifest with written files, skipped outputs, and errors. |

CSV exports include fiber diameter statistics, orientation metrics, porosity, and sample counts when the full measurement pipeline is enabled.

---

## Configuration

Your settings are stored in a per-user configuration file, created from the bundled defaults on first run:

| OS | Location |
|---|---|
| macOS | `~/Library/Application Support/fiberpose/config.json` |
| Linux | `~/.config/fiberpose/config.json` |
| Windows | `%LOCALAPPDATA%\fiberpose\config.json` |

The GUI saves its settings there when it closes. Delete the file to restore the defaults.

The configuration controls model path, device preference, image scaling, ridge detection parameters, segmentation mode, centerline filtering, measurement spacing, and export options.

You can edit configuration values in the GUI through the configuration editor or pass a config file directly to the CLI:

```bash
fiberpose --cli --input /path/to/data --config /path/to/config.json
```

---

## Project structure

```text
Fiberpose/
β”œβ”€β”€ pyproject.toml             # Package metadata, dependencies, `fiberpose` command
β”œβ”€β”€ README.md
β”œβ”€β”€ PIPELINE.md                # Runtime pipeline details
β”œβ”€β”€ LICENSE
β”œβ”€β”€ app.py                     # Entry point of the Hugging Face Space
β”œβ”€β”€ requirements.txt           # Dependencies of the Hugging Face Space
β”œβ”€β”€ Dockerfile                 # Web interface as a container
β”œβ”€β”€ checkpoints/               # Pretrained model (R108_dt_fg.onnx)
β”œβ”€β”€ docs/                      # README images
└── src/fiberpose/
    β”œβ”€β”€ cli.py                 # GUI/CLI/web launcher (`fiberpose` command)
    β”œβ”€β”€ api.py                 # Public Python API: analyze()
    β”œβ”€β”€ models.py              # Model lookup, download, and cache
    β”œβ”€β”€ paths.py               # Bundled resources and user config locations
    β”œβ”€β”€ web/                   # Gradio web interface (`fiberpose --web`)
    β”œβ”€β”€ gui/                   # PyQt desktop interface (`fiberpose --gui`)
    β”œβ”€β”€ cli_runner.py          # Batch CLI processing
    β”œβ”€β”€ pipeline.py            # Pipeline orchestration
    β”œβ”€β”€ analysis.py            # Stateless prediction, segmentation, and measurement functions
    β”œβ”€β”€ render.py              # Display/export images of a frame (overlays, views)
    β”œβ”€β”€ raster.py              # Vectorized disk rasterization helpers
    β”œβ”€β”€ ridge_detector.py      # Ridge/centerline detector
    β”œβ”€β”€ ml.py                  # ONNX Runtime inference wrapper
    β”œβ”€β”€ domain.py              # Data models and configuration
    β”œβ”€β”€ io_export.py           # Export services
    β”œβ”€β”€ utils.py               # Numeric and image helper functions
    └── resources/
        β”œβ”€β”€ config.json        # Default configuration
        β”œβ”€β”€ fiber_tool.ui      # Qt GUI layout
        β”œβ”€β”€ test.png           # Example image
        └── example_*.png      # More examples for the web interface
```

---

## Troubleshooting

### Model file not found

The default model is expected in `checkpoints/` of the source checkout. If Fiberpose runs from elsewhere, copy `R108_dt_fg.onnx` into a folder and point `FIBERPOSE_MODELS_DIR` at it. For a custom model, check that `model_path` in your configuration is a file name in the models folder or an absolute path.

### GPU is not used

Confirm that ONNX Runtime sees CUDA:

```python
import onnxruntime as ort
print(ort.get_available_providers())
```

If `CUDAExecutionProvider` is missing, install the correct ONNX Runtime GPU package for your platform.

### Segmentation is inverted or poor

Try the `--invert` CLI flag or the invert option in the GUI if your fibers are dark on a bright background.

### Measurements are missing

Run the full analysis pipeline, not segmentation-only:

```bash
fiberpose --cli --input /path/to/data --measurements
```

---

## Citation

If you use Fiberpose in scientific work, please cite the preprint:

> V. A. Balashov, D. S. Antonenko. *Fiberpose: state-of-the-art fiber morphometry and instance segmentation with a distance-transform neural network.* arXiv:2611.22953 (2026). <https://doi.org/10.48550/arXiv.2611.22953>

```bibtex
@misc{balashov2026fiberpose,
  title         = {Fiberpose: state-of-the-art fiber morphometry and instance segmentation with a distance-transform neural network},
  author        = {Balashov, Viktor A. and Antonenko, Daniil S.},
  year          = {2026},
  eprint        = {2611.22953},
  archivePrefix = {arXiv},
  primaryClass  = {cs.CV},
  doi           = {10.48550/arXiv.2611.22953},
  url           = {https://doi.org/10.48550/arXiv.2611.22953}
}
```

---

## License

Fiberpose is free software licensed under the GNU General Public License,
version 3 only (`GPL-3.0-only`). See `LICENSE` for details.

---

## Disclaimer

Fiberpose is research software for microscopy image analysis. It is not a medical device and should not be used for clinical diagnosis or treatment decisions.