vikba commited on
Commit
beb4f15
·
verified ·
1 Parent(s): f667944

Upload folder using huggingface_hub

Browse files
.dockerignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ *
2
+ !src
3
+ !checkpoints/R108_dt_fg.onnx
4
+ !pyproject.toml
5
+ !README.md
6
+ !LICENSE
7
+ **/__pycache__
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ src/fiberpose/resources/test.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ .pytest_cache/
9
+
10
+ # OS and editors
11
+ .DS_Store
12
+ .vscode/
13
+ .idea/
14
+
15
+ # Local models, data and tests (not part of the public repository)
16
+ checkpoints/
17
+ *.onnx
18
+ *.onnx.data
19
+ validation/
20
+ manuscript/
21
+ profiling_results/
22
+ out/
23
+ tests/
24
+ train/
25
+
26
+ # Local tooling and notes
27
+ .agents/
28
+ .codex
29
+ webapp/
30
+ TODO.md
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # One image for a VPS and for a Hugging Face Docker Space (which runs as uid 1000).
2
+ FROM python:3.12-slim
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ WORKDIR /app
6
+ ENV PATH=/home/user/.local/bin:$PATH \
7
+ FIBERPOSE_MODELS_DIR=/app/checkpoints \
8
+ GRADIO_SERVER_NAME=0.0.0.0 \
9
+ GRADIO_SERVER_PORT=7860
10
+ COPY --chown=user . .
11
+ RUN pip install --no-cache-dir ".[web]"
12
+ # Analyse the example once so the numba kernels are compiled and cached in the image.
13
+ RUN python -c "import imageio.v3 as iio, fiberpose; from fiberpose.paths import EXAMPLE_IMAGE_PATH as p; fiberpose.analyze(iio.imread(p))"
14
+ EXPOSE 7860
15
+ CMD ["fiberpose", "--web"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
PIPELINE.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fiberpose Pipeline
2
+
3
+ ## Scope
4
+ - Documents runtime behavior in `src/fiberpose/cli.py`, `src/fiberpose/gui/main_window.py`, `src/fiberpose/pipeline.py`, and `src/fiberpose/analysis.py`.
5
+ - Covers GUI and CLI startup, segmentation, measurement, and batch execution/export.
6
+
7
+ ## Runtime Modes and Flags
8
+ - `segmentation_mode=watershed` makes `analysis.segment(...)` run a gradient-masked watershed (`watershed_grad_threshold`).
9
+ - `segmentation_mode=radial_expansion` makes `analysis.segment(...)` rasterize the expanded ridge fragments.
10
+ - `merge_expansion_factor` controls overlap-based ridge-fragment merging (default `0.7`).
11
+ - `segmentation_expansion_factor` controls radial label expansion (default `1.0`).
12
+ - `strict_centerlines` affects the measurement-centerline filtering stage.
13
+ - `keep_segments_without_measurement_centerlines` keeps segmentation fragments even when no measurement centerline survives filtering.
14
+ - `scale factor` (`cb_scale`) rescales input for prediction/segmentation and rescales thresholds/measurements back to original units.
15
+ - `pores view` changes overlay/histogram to pore circles and pore diameter distribution.
16
+
17
+ ## Core Runtime Data
18
+ - `ImageBatch`: ordered list of frames plus metadata (`filenames`, `z_indices`, `source_type`).
19
+ - `Frame`: per-slice state container (`orig_img`, prediction outputs, segmentation outputs, measurement outputs). It is the only owner of per-image state; `analysis` functions are stateless and `PipelineController` keeps only the loaded model.
20
+ - `BatchResult`: `frame_results: list[Frame]`.
21
+ - `dt`: model output distance transform (`float32`).
22
+ - `foreground_prob`: optional foreground probability (`float32`) from `nout == 2` checkpoints.
23
+ - `dt_u8`, `dt_normalized`, `gx`, `gy`, `laplacian`: cached prediction products.
24
+ - `fragments`: `list[FiberFragment]` that own a label; each carries its segmentation and measurement centerlines.
25
+ - `labels_2d`: `uint16` segmentation labels.
26
+ - `samples_table`, `thickness_units`, `angles_samples_deg`, `porosity`, `pores`, `pore_diams_units`: measurement outputs.
27
+
28
+ ## Entry Flow
29
+ 1. `fiberpose.cli.main()` (the `fiberpose` command) dispatches mode:
30
+ - GUI default (`fiberpose` or `fiberpose --gui`)
31
+ - CLI (`fiberpose --cli --input <path> ...`)
32
+ 2. GUI path:
33
+ - `MainWindow.open_source(...)` loads input into `ImageBatch`.
34
+ - User action calls `segment()` or `analyze_fibers()`.
35
+ - If `_image_batch` exists and not already in callbacks, GUI routes through `_run_batch_analysis(...)`.
36
+ 3. CLI path:
37
+ - `CliRunner` loads config and source via `ImageBatch.from_source(...)`.
38
+ - It instantiates `PipelineController(model_path, device)`, processes each frame, builds `BatchResult`, and exports.
39
+
40
+ ## Batch Execution Flow
41
+ 1. `_run_batch_analysis(...)` configures `BatchCallbacks` and calls `BatchService.run_batch(...)`.
42
+ 2. `BatchService.run_batch(...)` loops frames and invokes the provided per-frame callback.
43
+ 3. Per-frame callback in `_run_batch_analysis(...)`:
44
+ - create or hydrate `current_frame` with `Frame.empty(...)` or a `snapshot()` of the cached frame result
45
+ - run `_run_current_frame_pipeline(...)`, which calls `ensure_segmentation` or `ensure_measurements` (`_is_batch_processing=True` keeps `segment()` / `analyze_fibers()` from re-dispatching a batch)
46
+ - capture result with `current_frame.snapshot(frame_id=..., z_index=...)`
47
+ 4. Collected outputs become `BatchResult(frame_results=[...])`.
48
+ 5. GUI stores `_batch_result` and rehydrates selected slice with `_apply_frame_result(...)`.
49
+ 6. CLI uses the same controller stages (`ensure_segmentation` / `ensure_measurements`) and writes exports via `BatchResult.save_all(...)`.
50
+
51
+ ## Per-Frame Segmentation Flow
52
+ 1. `ensure_prediction`: if the frame has no prediction for the current signature, resolve the scaled processing image and run `analysis.predict(model, image)`:
53
+ - pads to the model stride, runs `OnnxFiberposeModel.predict(...)` -> `(dt, foreground_prob)`; `nout != 2` uses the last channel as DT and has no foreground
54
+ - smooths DT, computes gradients/laplacian; stored via `Frame.set_prediction_outputs(...)`
55
+ 2. If the frame's segmentation signature (prediction signature + `segmentation_params(config)`) matches, stop.
56
+ 3. Otherwise `clear_segmentation()` and run `analysis.segment(dt, dt_u8, gx, gy, foreground_prob, **segmentation_params)`:
57
+ - `RidgeDetector.detect_ridges(...)` (raw ridge lines)
58
+ - `_group_detected_polylines_into_segmentation_fragments(...)` merges ridges whose `merge_expansion_factor * DT` disks overlap
59
+ - `_filter_measurement_centerlines(...)` derives measurement centerlines; the shortest fraction is dropped
60
+ - `_filter_fragments_by_grad_quality(...)` drops fragments with unreliable DT gradients
61
+ - watershed thresholds the DT gradient magnitude, unions two 3x3 dilations of the centerline markers, then applies erode -> dilate; radial_expansion rasterizes the expanded fragments
62
+ - foreground, when available, prunes labels; only fragments that keep a label are returned
63
+ 4. Store the labels and fragments via `set_segmentation_outputs(...)`. The pipeline draws no images.
64
+
65
+ ## Per-Frame Measurement Flow
66
+ 1. GUI `analyze_fibers()` or CLI measurement mode ensures prediction + segmentation are ready.
67
+ 2. Calls `analysis.sample_centerlines(dt, gx, gy, frame.fragments, spacing_px, frame.scale_factor)` returning measurement and drawing samples.
68
+ 3. Builds thickness arrays/sample table and orientation stats in `PipelineController`.
69
+ 4. Computes porosity and pore sampling:
70
+ - `analysis.void_mask_and_pore_dt(dt_u8, thr_u8)`
71
+ - `analysis.sample_inscribed_circles(...)`
72
+ 5. Stores outputs in `Frame` via `set_measurement_outputs(...)`.
73
+ 6. GUI shows the selected view and histograms:
74
+ - thickness histogram always
75
+ - angles histogram or pore size histogram depending on pores view
76
+
77
+ ## Stack Input
78
+ Stack input normalization in `ImageBatch._normalize_stack(...)`:
79
+ - `HxW` -> single frame
80
+ - `HxWxC` -> single frame
81
+ - `ZxHxW` -> grayscale stack
82
+ - `ZxHxWxC` -> color stack
83
+
84
+ ## Class Roles
85
+ - `cli.py`: top-level GUI/CLI dispatch and argument parsing (`fiberpose` command).
86
+ - `analyze()` (`api.py`): public single-image entry point wrapping `PipelineController`.
87
+ - `MainWindow` (`gui/main_window.py`): GUI orchestration, UI state, view updates, and user-triggered batch runs.
88
+ - `CliRunner` (`cli_runner.py`): CLI orchestration for batch processing/export.
89
+ - `PipelineController` (`pipeline.py`): shared processing engine; owns the lazily loaded model and caches each stage on `Frame` by signature.
90
+ - `BatchService` (`pipeline.py`): frame iteration orchestration using callbacks.
91
+ - `analysis.py`: stateless prediction, centerline extraction, segmentation, pore and measurement functions.
92
+ - `render(frame, view)` (`render.py`): builds every displayed or exported image from frame data on demand and caches it in `Frame.views` until a stage is recomputed.
93
+ - `ImageBatch` / `Frame` / `BatchResult` (`domain.py`): runtime data transport/state.
94
+ - `RidgeDetector`: ridge/junction extraction backend.
README.md CHANGED
@@ -1,15 +1,342 @@
1
  ---
2
  title: Fiberpose
3
- emoji: ⚡
4
- colorFrom: gray
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 6.32.0
8
- python_version: '3.12'
9
- app_file: app.py
10
- pinned: false
11
- license: apache-2.0
12
- short_description: Framework for fiber morphometry
13
- ---
14
-
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Fiberpose
3
+ emoji: 🧵
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ license: gpl-3.0
9
+ ---
10
+
11
+ # Fiberpose
12
+
13
+ **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.
14
+
15
+ It is designed for fibrous materials where conventional thresholding becomes fragile: dense networks, weak contrast, uneven illumination, touching fibers, and overlapping structures.
16
+
17
+ > Status: research-preview software under active development. Validate outputs on your own data before using them for publication or production decisions.
18
+
19
+ ---
20
+
21
+ ## Key features
22
+
23
+ - **Neural distance-transform prediction** from raw microscopy images.
24
+ - **Fiber centerline extraction** using ridge detection on the predicted distance-transform field.
25
+ - **Instance segmentation** of fiber fragments using marker-controlled watershed or radial expansion modes.
26
+ - **Morphometric analysis** of fiber diameter, orientation, orientation index, porosity, and pore-size distributions.
27
+ - **Interactive desktop GUI** for loading images, inspecting intermediate maps, adjusting parameters, visualizing overlays, and exporting results.
28
+ - **Batch-oriented CLI** for reproducible processing of folders and image stacks.
29
+ - **Publication-oriented exports**: distance-transform maps, labels, overlays, diameter/orientation overlays, measurement tables, summaries, and manifests.
30
+
31
+ ---
32
+
33
+ ## Method overview
34
+
35
+ Fiberpose follows a simple geometric pipeline:
36
+
37
+ 1. A neural network predicts a continuous distance-transform field from the input image.
38
+ 2. Centerlines are extracted as ridges of this field.
39
+ 3. Fiber instances are separated using centerline markers and distance-transform geometry.
40
+ 4. Measurements are sampled along centerlines:
41
+ - local radius is one pixel plus the mean distance-transform value sampled one pixel away on each side,
42
+ - local orientation is estimated from the distance field gradients,
43
+ - pore sizes are estimated from the distance transform of the void space.
44
+
45
+ This makes the distance-transform field the central representation connecting neural inference, segmentation, and quantitative analysis.
46
+
47
+ ---
48
+
49
+ ## Installation
50
+
51
+ Fiberpose requires Python 3.10 or newer. A fresh conda or virtual environment is recommended.
52
+
53
+ ```bash
54
+ git clone https://github.com/vikba/Fiberpose.git
55
+ cd Fiberpose
56
+
57
+ conda create -n fiberpose python=3.11 -y
58
+ conda activate fiberpose
59
+
60
+ pip install -e ".[gui]"
61
+ ```
62
+
63
+ 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.
64
+
65
+ ### GPU note
66
+
67
+ 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.
68
+
69
+ 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):
70
+
71
+ ```bash
72
+ pip uninstall -y onnxruntime
73
+ pip install onnxruntime-gpu
74
+ ```
75
+
76
+ Running `pip install -e .` again reinstalls the CPU build, so repeat these two commands afterwards.
77
+
78
+ ---
79
+
80
+ ## Pretrained model
81
+
82
+ The default model, `R108_dt_fg.onnx`, is downloaded automatically on first use and cached locally. Fiberpose looks for models, by file name, in this order:
83
+
84
+ 1. the folder set in the `FIBERPOSE_MODELS_DIR` environment variable;
85
+ 2. `checkpoints/` in the repository, when running from a source checkout;
86
+ 3. the per-user cache (for example `~/Library/Caches/fiberpose/models` on macOS).
87
+
88
+ 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.
89
+
90
+ ---
91
+
92
+ ## Running Fiberpose
93
+
94
+ The `fiberpose` command launches both GUI and CLI modes. `python -m fiberpose` is equivalent.
95
+
96
+ ### GUI mode
97
+
98
+ ```bash
99
+ fiberpose
100
+ ```
101
+
102
+ or explicitly:
103
+
104
+ ```bash
105
+ fiberpose --gui
106
+ ```
107
+
108
+ The GUI supports:
109
+
110
+ - single image, folder, and stack loading;
111
+ - raw image, distance-transform, gradient-magnitude, Laplacian, centerline, segmentation, overlay, pore, diameter, and orientation views;
112
+ - model selection and CPU/GPU toggle;
113
+ - scalebar calibration;
114
+ - DT profile plotting;
115
+ - batch processing;
116
+ - export of masks, overlays, and CSV tables.
117
+
118
+ ### CLI mode
119
+
120
+ Run segmentation on an image, folder, or stack:
121
+
122
+ ```bash
123
+ fiberpose --cli --input /path/to/image_or_folder_or_stack
124
+ ```
125
+
126
+ Run the full measurement pipeline:
127
+
128
+ ```bash
129
+ fiberpose --cli --input /path/to/image_or_folder_or_stack --measurements
130
+ ```
131
+
132
+ Write outputs to a selected directory:
133
+
134
+ ```bash
135
+ fiberpose --cli --input /path/to/image_or_folder_or_stack --output /path/to/output
136
+ ```
137
+
138
+ Use a custom config:
139
+
140
+ ```bash
141
+ fiberpose --cli --input /path/to/image_or_folder_or_stack --config /path/to/config.json
142
+ ```
143
+
144
+ Export only measurement CSV files:
145
+
146
+ ```bash
147
+ fiberpose --cli --input /path/to/image_or_folder_or_stack --measurements --save-kind csv
148
+ ```
149
+
150
+ ### CLI arguments
151
+
152
+ | Argument | Description |
153
+ |---|---|
154
+ | `--gui` | Force GUI mode. |
155
+ | `--cli` | Run command-line processing mode. |
156
+ | `--input <path>` | Input image, folder, or stack. Required in CLI mode. |
157
+ | `--config <path>` | Path to a JSON configuration file. Default: the user configuration file (see Configuration below). |
158
+ | `--output <dir>` | Output directory for exported files. |
159
+ | `--measurements` | Run full measurement pipeline. Without this flag, CLI runs segmentation-only. |
160
+ | `--invert` | Invert image intensities before inference. Useful when fibers are dark on a bright background. |
161
+ | `--save-kind results\|csv` | Export full result artifacts or only CSV measurement tables. Default: `results`. |
162
+ | `--version` | Print the Fiberpose version and exit. |
163
+
164
+ ### CLI exit codes
165
+
166
+ | Code | Meaning |
167
+ |---|---|
168
+ | `0` | Processing finished without failures. |
169
+ | `1` | Processing finished, but one or more frames failed during processing or export. |
170
+ | `2` | Invalid arguments, missing input/config/model, or startup/runtime error. |
171
+
172
+ ### Web interface
173
+
174
+ ```bash
175
+ pip install "fiberpose[web]"
176
+ fiberpose --web # http://localhost:7860
177
+ ```
178
+
179
+ The same page runs in Docker (`docker build -t fiberpose . && docker run -p 7860:7860 fiberpose`)
180
+ and as a Hugging Face Docker Space; `.github/workflows/deploy.yml` publishes both on a version tag.
181
+
182
+ ### Python API
183
+
184
+ ```python
185
+ import imageio.v3 as iio
186
+ import fiberpose
187
+
188
+ image = iio.imread("fibers.tif")
189
+ result = fiberpose.analyze(image, pixel_size=0.1, unit="um")
190
+
191
+ print(result.summary["diam_mean"], result.summary["orientation_index"])
192
+ result.labels # instance labels (0 = background)
193
+ result.distance_transform # predicted distance-transform field
194
+ result.diameters # per-sample diameters in `unit`
195
+ ```
196
+
197
+ Pass a `fiberpose.AppConfig` as the second argument to change model or analysis parameters.
198
+
199
+ ---
200
+
201
+ ## Supported inputs
202
+
203
+ Fiberpose can process common microscopy image formats, including:
204
+
205
+ ```text
206
+ .tif, .tiff, .png, .jpg, .jpeg, .bmp, .webp
207
+ ```
208
+
209
+ Folders are processed as batches. Multi-page TIFF files and image stacks are treated as stack inputs.
210
+
211
+ ---
212
+
213
+ ## Outputs
214
+
215
+ Depending on the selected export options, Fiberpose can save:
216
+
217
+ | Output | Description |
218
+ |---|---|
219
+ | `*_dt` | Predicted distance-transform map. |
220
+ | `*_labels` | Instance label visualization. |
221
+ | `*_overlay` | Segmentation overlay on the original image. |
222
+ | `*_diameters` | Diameter measurement overlay. |
223
+ | `*_orientations` | Orientation measurement overlay. |
224
+ | `*_outline` | Segmentation outline image. |
225
+ | `*_samples.csv` | Per-sample measurement table. |
226
+ | `*_summary.csv` | Batch-level summary table. |
227
+ | `manifest.json` | Export manifest with written files, skipped outputs, and errors. |
228
+
229
+ CSV exports include fiber diameter statistics, orientation metrics, porosity, and sample counts when the full measurement pipeline is enabled.
230
+
231
+ ---
232
+
233
+ ## Configuration
234
+
235
+ Your settings are stored in a per-user configuration file, created from the bundled defaults on first run:
236
+
237
+ | OS | Location |
238
+ |---|---|
239
+ | macOS | `~/Library/Application Support/fiberpose/config.json` |
240
+ | Linux | `~/.config/fiberpose/config.json` |
241
+ | Windows | `%LOCALAPPDATA%\fiberpose\config.json` |
242
+
243
+ The GUI saves its settings there when it closes. Delete the file to restore the defaults.
244
+
245
+ The configuration controls model path, device preference, image scaling, ridge detection parameters, segmentation mode, centerline filtering, measurement spacing, and export options.
246
+
247
+ You can edit configuration values in the GUI through the configuration editor or pass a config file directly to the CLI:
248
+
249
+ ```bash
250
+ fiberpose --cli --input /path/to/data --config /path/to/config.json
251
+ ```
252
+
253
+ ---
254
+
255
+ ## Project structure
256
+
257
+ ```text
258
+ Fiberpose/
259
+ ├── pyproject.toml # Package metadata, dependencies, `fiberpose` command
260
+ ├── README.md
261
+ ├── PIPELINE.md # Runtime pipeline details
262
+ ├── LICENSE
263
+ └── src/fiberpose/
264
+ ├── cli.py # GUI/CLI/web launcher (`fiberpose` command)
265
+ ├── api.py # Public Python API: analyze()
266
+ ├── models.py # Model lookup, download, and cache
267
+ ├── paths.py # Bundled resources and user config locations
268
+ ├── web/ # Gradio web interface (`fiberpose --web`)
269
+ ├── gui/ # PyQt desktop interface (`fiberpose --gui`)
270
+ ├── cli_runner.py # Batch CLI processing
271
+ ├── pipeline.py # Pipeline orchestration
272
+ ├── analysis.py # Stateless prediction, segmentation, and measurement functions
273
+ ├── render.py # Display/export images of a frame (overlays, views)
274
+ ├── ridge_detector.py # Ridge/centerline detector
275
+ ├── ml.py # ONNX Runtime inference wrapper
276
+ ├── domain.py # Data models and configuration
277
+ ├── io_export.py # Export services
278
+ ├── utils.py # Numeric and image helper functions
279
+ └── resources/
280
+ ├── config.json # Default configuration
281
+ ├── fiber_tool.ui # Qt GUI layout
282
+ └── test.png # Example image
283
+ ```
284
+
285
+ ---
286
+
287
+ ## Troubleshooting
288
+
289
+ ### Model file not found
290
+
291
+ The default model is downloaded on first use, which needs an internet connection. On an offline machine, 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.
292
+
293
+ ### GPU is not used
294
+
295
+ Confirm that ONNX Runtime sees CUDA:
296
+
297
+ ```python
298
+ import onnxruntime as ort
299
+ print(ort.get_available_providers())
300
+ ```
301
+
302
+ If `CUDAExecutionProvider` is missing, install the correct ONNX Runtime GPU package for your platform.
303
+
304
+ ### Segmentation is inverted or poor
305
+
306
+ Try the `--invert` CLI flag or the invert option in the GUI if your fibers are dark on a bright background.
307
+
308
+ ### Measurements are missing
309
+
310
+ Run the full analysis pipeline, not segmentation-only:
311
+
312
+ ```bash
313
+ fiberpose --cli --input /path/to/data --measurements
314
+ ```
315
+
316
+ ---
317
+
318
+ ## Citation
319
+
320
+ If you use Fiberpose in scientific work, please cite the associated manuscript/preprint when available.
321
+
322
+ ```bibtex
323
+ @software{fiberpose,
324
+ title = {Fiberpose: A deep learning framework for segmentation and quantitative analysis of fibrous structures},
325
+ author = {Balashov, Viktor},
326
+ year = {2026},
327
+ url = {https://github.com/vikba/Fiberpose}
328
+ }
329
+ ```
330
+
331
+ ---
332
+
333
+ ## License
334
+
335
+ Fiberpose is free software licensed under the GNU General Public License,
336
+ version 3 only (`GPL-3.0-only`). See `LICENSE` for details.
337
+
338
+ ---
339
+
340
+ ## Disclaimer
341
+
342
+ 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.
deploy/hf_header.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Fiberpose
3
+ emoji: 🧵
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ license: gpl-3.0
9
+ ---
10
+
pyproject.toml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "fiberpose"
7
+ dynamic = ["version"]
8
+ description = "Segmentation and morphometry of fibrous microstructures from a predicted distance-transform field"
9
+ readme = "README.md"
10
+ license = "GPL-3.0-only"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Viktor Balashov" }]
14
+ keywords = ["microscopy", "segmentation", "fibers", "morphometry", "distance transform", "image analysis"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Science/Research",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Scientific/Engineering :: Image Processing",
24
+ ]
25
+ dependencies = [
26
+ "numpy>=1.26",
27
+ "scipy>=1.11",
28
+ "scikit-image>=0.22",
29
+ "numba>=0.59",
30
+ "onnxruntime>=1.17",
31
+ "opencv-python-headless>=4.8",
32
+ "imageio>=2.31",
33
+ "tifffile>=2023.7.10",
34
+ "tqdm>=4.64",
35
+ "platformdirs>=3",
36
+ "pooch>=1.8",
37
+ ]
38
+
39
+ [project.optional-dependencies]
40
+ gui = ["PyQt6>=6.5", "pyqtgraph>=0.13"]
41
+ web = ["gradio>=6", "matplotlib>=3.7"]
42
+
43
+ [project.scripts]
44
+ fiberpose = "fiberpose.cli:main"
45
+
46
+ [project.urls]
47
+ Homepage = "https://github.com/vikba/Fiberpose"
48
+ Issues = "https://github.com/vikba/Fiberpose/issues"
49
+
50
+ [tool.hatch.version]
51
+ path = "src/fiberpose/__init__.py"
52
+
53
+ [tool.hatch.build.targets.wheel]
54
+ packages = ["src/fiberpose"]
src/fiberpose/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fiberpose: distance-transform-based segmentation and morphometry of fibrous microstructures."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ __all__ = ["AnalysisResult", "AppConfig", "FiberposeError", "analyze", "__version__"]
6
+
7
+
8
+ def __getattr__(name):
9
+ # Imported lazily so `import fiberpose` and `fiberpose --help` stay fast
10
+ # and don't load ONNX Runtime or compile numba kernels.
11
+ if name in ("AnalysisResult", "FiberposeError", "analyze"):
12
+ from . import api
13
+
14
+ return getattr(api, name)
15
+ if name == "AppConfig":
16
+ from .domain import AppConfig
17
+
18
+ return AppConfig
19
+ raise AttributeError(f"module 'fiberpose' has no attribute {name!r}")
src/fiberpose/__main__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Allow ``python -m fiberpose``."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
src/fiberpose/analysis.py ADDED
@@ -0,0 +1,736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """2D fiber analysis: DT prediction, centerlines, segmentation, and measurement sampling.
2
+
3
+ Every function is stateless: arrays in, results out. Per-image state lives on `Frame`.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ from typing import Any
10
+
11
+ import cv2
12
+ import numpy as np
13
+ from numba import njit
14
+ from scipy.ndimage import gaussian_filter, laplace, value_indices
15
+ from scipy.sparse import coo_matrix
16
+ from scipy.sparse.csgraph import connected_components
17
+ from skimage.segmentation import watershed
18
+
19
+ from .domain import FiberFragment
20
+ from .ml import OnnxFiberposeModel
21
+ from .raster import disk_mask, disk_radii, stamp_disks
22
+ from .ridge_detector import RidgeDetector
23
+ from .utils import (
24
+ _bilinear,
25
+ _sample_vec2,
26
+ normals_from_dt_2d,
27
+ resample_polyline_xy,
28
+ )
29
+
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ Sample = tuple[int, int, float, float, float, float]
34
+
35
+
36
+ # ------------------------------------------------------------------ #
37
+ # Public pipeline stages
38
+
39
+
40
+ def predict(model: OnnxFiberposeModel, image: np.ndarray) -> dict[str, np.ndarray | None]:
41
+ """Predict the DT of `image` plus its derived fields, keyed like `Frame.set_prediction_outputs`."""
42
+ h, w = image.shape[:2]
43
+ stride = int(model.stride)
44
+ pad_width = ((0, -h % stride), (0, -w % stride)) + ((0, 0),) * (image.ndim - 2)
45
+ dt_pad, fg_pad = model.predict(np.pad(image, pad_width, mode="reflect"))
46
+
47
+ dt = np.asarray(dt_pad[:h, :w], dtype=np.float32)
48
+ dt_smooth = gaussian_filter(dt, sigma=1.5)
49
+ gy, gx = np.gradient(dt_smooth)
50
+ return {
51
+ "dt": dt,
52
+ "dt_u8": np.clip(dt, 0, 255).astype(np.uint8),
53
+ "dt_normalized": dt / 255.0,
54
+ "foreground_prob": None if fg_pad is None else np.asarray(fg_pad[:h, :w], dtype=np.float32),
55
+ "gx": np.asarray(gaussian_filter(gx, sigma=1.0), dtype=np.float32),
56
+ "gy": np.asarray(gaussian_filter(gy, sigma=1.0), dtype=np.float32),
57
+ "lapl_img": np.asarray(laplace(dt_smooth), dtype=np.float32),
58
+ }
59
+
60
+
61
+ def segment(
62
+ dt: np.ndarray,
63
+ dt_u8: np.ndarray,
64
+ gx: np.ndarray,
65
+ gy: np.ndarray,
66
+ foreground_prob: np.ndarray | None,
67
+ *,
68
+ segmentation_mode: str,
69
+ watershed_grad_threshold: float,
70
+ min_segment_foreground_mean: float,
71
+ max_angle_deg: float,
72
+ ridge_sigma: float,
73
+ ridge_low: float,
74
+ ridge_high: float,
75
+ strict_centerlines: bool,
76
+ keep_segments_without_measurement_centerlines: bool,
77
+ merge_expansion_factor: float,
78
+ segmentation_expansion_factor: float,
79
+ min_fragment_centerline_length_px: float,
80
+ measurement_centerline_length_trim_fraction: float,
81
+ grad_quality_trim_fraction: float,
82
+ ) -> tuple[np.ndarray, list[FiberFragment]]:
83
+ """Segment fibers: ridges -> fragments -> uint16 labels.
84
+
85
+ Returns the labels and the fragments that still own a label after pruning.
86
+ """
87
+ shape = dt_u8.shape
88
+ detected_polylines = RidgeDetector.detect_ridges(
89
+ image2d=dt_u8,
90
+ sigma=float(ridge_sigma),
91
+ low=float(ridge_low),
92
+ high=float(ridge_high),
93
+ polarity="light",
94
+ )
95
+ raw_fragments = _group_detected_polylines_into_segmentation_fragments(
96
+ detected_polylines=detected_polylines,
97
+ dt=dt,
98
+ merge_expansion_factor=float(merge_expansion_factor),
99
+ min_fragment_centerline_length_px=float(min_fragment_centerline_length_px),
100
+ trim=3,
101
+ )
102
+ fragments = _filter_measurement_centerlines(
103
+ segmentation_fragments=raw_fragments,
104
+ dt_u8=dt_u8,
105
+ dt=dt,
106
+ gx=gx,
107
+ gy=gy,
108
+ max_angle_deg=max_angle_deg,
109
+ win_len=25.0,
110
+ std_thresh=0.8,
111
+ strict=strict_centerlines,
112
+ keep_segments_without_measurement_centerlines=keep_segments_without_measurement_centerlines,
113
+ )
114
+
115
+ # Drop the fragments with the shortest measurement centerlines.
116
+ trim_count = int(np.floor(len(fragments) * _clamp_trim_fraction(measurement_centerline_length_trim_fraction)))
117
+ if trim_count > 0:
118
+ ordered = sorted(
119
+ fragments,
120
+ key=lambda seg: (float(seg.total_measurement_centerline_length_px), int(seg.fragment_id)),
121
+ )
122
+ drop_ids = {int(seg.fragment_id) for seg in ordered[:trim_count]}
123
+ fragments = [seg for seg in fragments if int(seg.fragment_id) not in drop_ids]
124
+
125
+ grad_err = np.abs(np.sqrt(gx * gx + gy * gy) - 1.0)
126
+ # Pixels each fragment covers at the segmentation expansion, shared by both steps below.
127
+ fragment_pixels = _fragment_pixels(fragments, float(segmentation_expansion_factor), shape)
128
+ fragments, fragment_pixels = _filter_fragments_by_grad_quality(
129
+ fragments=fragments,
130
+ fragment_pixels=fragment_pixels,
131
+ grad_err=grad_err,
132
+ trim_fraction=_clamp_trim_fraction(grad_quality_trim_fraction),
133
+ min_valid_pixels=8,
134
+ )
135
+
136
+ if segmentation_mode == "radial_expansion":
137
+ labels_i32 = _rasterize_segmentation_fragments(fragments=fragments, fragment_pixels=fragment_pixels, shape=shape)
138
+ labels = np.clip(labels_i32, 0, np.iinfo(np.uint16).max).astype(np.uint16, copy=False)
139
+ else:
140
+ markers = _render_markers(shape, fragments)
141
+ labels = _watershed(dt_u8, gx, gy, markers, gradient_threshold=watershed_grad_threshold)
142
+ labels = _prune_labels_by_foreground(
143
+ labels,
144
+ foreground_prob=foreground_prob,
145
+ min_segment_foreground_mean=min_segment_foreground_mean,
146
+ )
147
+
148
+ surviving_ids = set(np.unique(labels)) - {0}
149
+ fragments = [fragment for fragment in fragments if int(fragment.parent_fiber_id) in surviving_ids]
150
+ logger.info("Segmented %d fragments (%d detected)", len(fragments), len(raw_fragments))
151
+ return labels, fragments
152
+
153
+
154
+ def sample_centerlines(
155
+ dt: np.ndarray,
156
+ gx: np.ndarray,
157
+ gy: np.ndarray,
158
+ fragments: list[FiberFragment],
159
+ spacing_px: float = 5.0,
160
+ scale_factor: float = 1.0,
161
+ ) -> tuple[list[Sample], list[Sample]]:
162
+ """Sample thickness and orientation along the fragments' measurement centerlines.
163
+
164
+ Returns:
165
+ - measurement_samples: (y, x, ny, nx, r, angle_deg) in original/display scale
166
+ - drawing_samples: (y, x, ny, nx, r, angle_deg) in processing-image scale
167
+
168
+ Note:
169
+ `_xy` suffix denotes (x, y) ordering, while `_yx` denotes (y, x).
170
+ """
171
+ spacing = max(1.0, float(spacing_px))
172
+ scale = float(scale_factor)
173
+ if not np.isfinite(scale) or scale <= 0:
174
+ scale = 1.0
175
+
176
+ measurement_samples: list[Sample] = []
177
+ drawing_samples: list[Sample] = []
178
+
179
+ def _canon_angle(ty: float, tx: float) -> float:
180
+ n = float(np.hypot(ty, tx))
181
+ if n == 0.0 or not np.isfinite(n):
182
+ return float("nan")
183
+ ty, tx = ty / n, tx / n
184
+ ang = -np.degrees(np.arctan2(ty, tx))
185
+ if ang > 90.0:
186
+ ang -= 180.0
187
+ elif ang <= -90.0:
188
+ ang += 180.0
189
+ if ang <= -90.0:
190
+ ang = -89.999
191
+ return float(ang)
192
+
193
+ for frag in fragments:
194
+ for seg_xy in frag.measurement_centerlines_xy:
195
+ samples_xy = resample_polyline_xy(seg_xy.astype(np.float32), step=spacing)
196
+ if len(samples_xy) < 2:
197
+ continue
198
+
199
+ samples_yx = samples_xy[:, [1, 0]].astype(np.float32)
200
+ normals_yx = normals_from_dt_2d(
201
+ centerline=samples_yx,
202
+ dt=dt,
203
+ gx=gx,
204
+ gy=gy,
205
+ alpha=0.5,
206
+ iters=3,
207
+ tau_g=1e-3,
208
+ )
209
+
210
+ for i, (y, x) in enumerate(samples_yx):
211
+ ny, nx = float(normals_yx[i, 0]), float(normals_yx[i, 1])
212
+ norm = float(np.hypot(ny, nx))
213
+ if norm == 0.0 or not np.isfinite(norm):
214
+ continue
215
+ ny /= norm
216
+ nx /= norm
217
+
218
+ angle_deg = _canon_angle(nx, -ny)
219
+
220
+ v1 = float(_bilinear(dt, y - ny, x - nx))
221
+ v2 = float(_bilinear(dt, y + ny, x + nx))
222
+ r = 0.5 * (v1 + v2) + 1.0
223
+ if r <= 0 or not np.isfinite(r):
224
+ continue
225
+
226
+ drawing_samples.append((int(round(y)), int(round(x)), ny, nx, r, angle_deg))
227
+ measurement_samples.append(
228
+ (int(round(y / scale)), int(round(x / scale)), ny, nx, r / scale, angle_deg)
229
+ )
230
+
231
+ return measurement_samples, drawing_samples
232
+
233
+
234
+ def void_mask_and_pore_dt(dt_u8: np.ndarray, thr_u8: int) -> tuple[np.ndarray, np.ndarray]:
235
+ """
236
+ Returns:
237
+ void_mask_u8: uint8, {0,1}, where 1 marks void (pores), opened to drop thin artifacts
238
+ pore_dt: float32, Euclidean distance (in pixels) inside voids
239
+ """
240
+ t = float(thr_u8) / 255.0
241
+ dt01 = dt_u8.astype(np.float32) / 255.0
242
+ void_mask = (~(dt01 >= t)).astype(np.uint8)
243
+ if void_mask.any():
244
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
245
+ void_mask = cv2.morphologyEx(void_mask, cv2.MORPH_OPEN, kernel)
246
+ if void_mask.any():
247
+ pore_dt = cv2.distanceTransform(void_mask, distanceType=cv2.DIST_L2, maskSize=5).astype(np.float32)
248
+ else:
249
+ pore_dt = np.zeros_like(dt01, dtype=np.float32)
250
+ return void_mask, pore_dt
251
+
252
+
253
+ def sample_inscribed_circles(
254
+ pore_dt: np.ndarray,
255
+ void_mask: np.ndarray,
256
+ scale_factor: float = 1.0,
257
+ min_radius_px: float = 1.0,
258
+ min_peak_px: float = 3.0,
259
+ peak_footprint: int = 3,
260
+ ) -> list[dict[str, Any]]:
261
+ """Greedily place non-overlapping disks at pore-DT peaks, largest first."""
262
+ scale = scale_factor or 1.0
263
+ if not np.isfinite(scale) or scale <= 0:
264
+ scale = 1.0
265
+ H, W = pore_dt.shape[:2]
266
+ current_void = (void_mask.astype(np.uint8) > 0).astype(np.uint8)
267
+
268
+ # Local maxima inside the void. Zeros become 255 so background never counts as a peak.
269
+ k = max(3, int(peak_footprint) | 1)
270
+ arr_work = pore_dt.copy()
271
+ arr_work[arr_work == 0] = 255
272
+ dil = cv2.dilate(arr_work, cv2.getStructuringElement(cv2.MORPH_RECT, (k, k)))
273
+ ys, xs = np.nonzero((arr_work == dil) & (pore_dt > 0) & current_void.astype(bool))
274
+ if xs.size == 0:
275
+ return []
276
+
277
+ radii = pore_dt[ys, xs]
278
+ keep = radii >= float(min_peak_px)
279
+ if not np.any(keep):
280
+ return []
281
+ xs, ys, radii = xs[keep], ys[keep], radii[keep]
282
+
283
+ order = np.argsort(-radii)
284
+ xs, ys, radii = xs[order], ys[order], radii[order]
285
+
286
+ circles: list[dict[str, Any]] = []
287
+ for x, y, r in zip(xs, ys, radii):
288
+ if r < float(min_radius_px):
289
+ continue
290
+ r_int = int(np.floor(float(r)))
291
+ if r_int <= 0:
292
+ continue
293
+ if x - r_int < 0 or x + r_int >= W or y - r_int < 0 or y + r_int >= H:
294
+ continue
295
+
296
+ # The disk lies fully inside the image: test and carve only its window.
297
+ window = current_void[y - r_int:y + r_int + 1, x - r_int:x + r_int + 1]
298
+ disk = disk_mask(r_int)
299
+ if window[disk].all():
300
+ circles.append({'x': int(x), 'y': int(y), 'r_px': float(r), 'r_px_orig': float(r) / scale})
301
+ window[disk] = 0
302
+ return circles
303
+
304
+
305
+ # ------------------------------------------------------------------ #
306
+ # Fragments
307
+
308
+
309
+ def _group_detected_polylines_into_segmentation_fragments(
310
+ *,
311
+ detected_polylines: list[np.ndarray],
312
+ dt: np.ndarray,
313
+ merge_expansion_factor: float = 0.7,
314
+ min_fragment_centerline_length_px: float = 10.0,
315
+ trim: int = 3,
316
+ ) -> list[FiberFragment]:
317
+ """
318
+ Group detected polylines into segmentation fragments using overlap under merge expansion.
319
+ """
320
+ h, w = dt.shape[:2]
321
+ trim_n = max(0, int(trim))
322
+
323
+ polylines: list[np.ndarray] = []
324
+ polyline_radii: list[np.ndarray] = []
325
+ for pts_xy_raw in detected_polylines:
326
+ pts_xy = np.asarray(pts_xy_raw, dtype=np.float32)
327
+ if pts_xy.ndim != 2 or pts_xy.shape[1] != 2:
328
+ continue
329
+ if trim_n > 0 and pts_xy.shape[0] > 2 * trim_n:
330
+ pts_xy = pts_xy[trim_n:-trim_n]
331
+ if pts_xy.shape[0] < 2:
332
+ continue
333
+ x_idx = np.clip(np.rint(pts_xy[:, 0]).astype(np.int32), 0, w - 1)
334
+ y_idx = np.clip(np.rint(pts_xy[:, 1]).astype(np.int32), 0, h - 1)
335
+ polylines.append(pts_xy)
336
+ polyline_radii.append(np.asarray(dt[y_idx, x_idx], dtype=np.float32))
337
+
338
+ if not polylines:
339
+ return []
340
+
341
+ group_ids = _overlap_groups(polylines, polyline_radii, max(0.0, float(merge_expansion_factor)), (h, w))
342
+ grouped_polylines: dict[int, list[np.ndarray]] = {}
343
+ grouped_radii: dict[int, list[np.ndarray]] = {}
344
+ for label_id, pts_xy, radii in zip(group_ids.tolist(), polylines, polyline_radii):
345
+ grouped_polylines.setdefault(label_id, []).append(pts_xy)
346
+ grouped_radii.setdefault(label_id, []).append(radii)
347
+
348
+ fragments: list[FiberFragment] = []
349
+ for label_id in sorted(grouped_polylines):
350
+ max_centerline_length = max(
351
+ FiberFragment._centerline_length(pts_xy) for pts_xy in grouped_polylines[label_id]
352
+ )
353
+ if max_centerline_length < float(min_fragment_centerline_length_px):
354
+ continue
355
+ fragments.append(
356
+ FiberFragment(
357
+ fragment_id=len(fragments) + 1,
358
+ segment_centerlines_xy=grouped_polylines[label_id],
359
+ segment_radii=grouped_radii[label_id],
360
+ parent_fiber_id=int(label_id),
361
+ )
362
+ )
363
+
364
+ return fragments
365
+
366
+
367
+ def _overlap_groups(
368
+ polylines: list[np.ndarray],
369
+ radii: list[np.ndarray],
370
+ expansion: float,
371
+ shape: tuple[int, int],
372
+ ) -> np.ndarray:
373
+ """Group ids (1-based) for polylines whose expanded disks share at least one pixel.
374
+
375
+ Groups are the connected components of the "shares a pixel" graph, numbered in
376
+ order of their first polyline.
377
+ """
378
+ n = len(polylines)
379
+ owners = np.repeat(np.arange(n), [len(p) for p in polylines])
380
+ pixel, owner = stamp_disks(
381
+ np.concatenate(polylines), disk_radii(np.concatenate(radii), expansion), owners, shape
382
+ )
383
+ # Sort by pixel; consecutive entries on the same pixel link two polylines.
384
+ order = np.lexsort((owner, pixel))
385
+ pixel, owner = pixel[order], owner[order]
386
+ shared = pixel[1:] == pixel[:-1]
387
+ edges = np.unique(owner[:-1][shared] * n + owner[1:][shared])
388
+ graph = coo_matrix((np.ones(edges.size, dtype=np.int32), (edges // n, edges % n)), shape=(n, n))
389
+ _, component = connected_components(graph, directed=False)
390
+
391
+ _, first_polyline = np.unique(component, return_index=True)
392
+ rank = np.empty_like(first_polyline)
393
+ rank[np.argsort(first_polyline)] = np.arange(first_polyline.size)
394
+ return rank[component] + 1
395
+
396
+
397
+ def _fragment_pixels(
398
+ fragments: list[FiberFragment],
399
+ segmentation_expansion_factor: float,
400
+ shape: tuple[int, int],
401
+ ) -> list[np.ndarray]:
402
+ """Flat pixel indices each fragment covers: disks of its local radius along its centerlines."""
403
+ if not fragments:
404
+ return []
405
+ points, radii, owners = [], [], []
406
+ for index, frag in enumerate(fragments):
407
+ for pts_xy, frag_radii in zip(frag.segment_centerlines_xy, frag.segment_radii):
408
+ points.append(pts_xy)
409
+ radii.append(frag_radii)
410
+ owners.append(np.full(len(pts_xy), index))
411
+ expansion = max(0.0, float(segmentation_expansion_factor))
412
+ pixel, owner = stamp_disks(
413
+ np.concatenate(points), disk_radii(np.concatenate(radii), expansion), np.concatenate(owners), shape
414
+ )
415
+ # stamp_disks sorts by owner, so each fragment's pixels are one contiguous run.
416
+ return np.split(pixel, np.cumsum(np.bincount(owner, minlength=len(fragments)))[:-1])
417
+
418
+
419
+ def _rasterize_segmentation_fragments(
420
+ *,
421
+ fragments: list[FiberFragment],
422
+ fragment_pixels: list[np.ndarray],
423
+ shape: tuple[int, int],
424
+ ) -> np.ndarray:
425
+ """Render radial-expansion labels; where fragments overlap, the later one wins."""
426
+ expanded_labels = np.zeros(shape, dtype=np.int32)
427
+ flat = expanded_labels.reshape(-1)
428
+ for frag, pixels in zip(fragments, fragment_pixels):
429
+ flat[pixels] = int(frag.parent_fiber_id)
430
+ return expanded_labels
431
+
432
+
433
+ def _filter_fragments_by_grad_quality(
434
+ *,
435
+ fragments: list[FiberFragment],
436
+ fragment_pixels: list[np.ndarray],
437
+ grad_err: np.ndarray,
438
+ trim_fraction: float,
439
+ min_valid_pixels: int = 8,
440
+ ) -> tuple[list[FiberFragment], list[np.ndarray]]:
441
+ """Score fragments by median |grad(dt)| error off their centerlines; drop unreliable/worst ones.
442
+
443
+ Returns the kept fragments and their pixel lists, in input order.
444
+ """
445
+ h, w = grad_err.shape[:2]
446
+ grad_err_flat = grad_err.reshape(-1)
447
+ reliable: list[tuple[FiberFragment, np.ndarray]] = []
448
+ for fragment, pixels in zip(fragments, fragment_pixels):
449
+ centerline_pixels = [
450
+ np.clip(np.rint(pts_xy[:, 1]).astype(np.int64), 0, h - 1) * w
451
+ + np.clip(np.rint(pts_xy[:, 0]).astype(np.int64), 0, w - 1)
452
+ for pts_xy in fragment.segment_centerlines_xy
453
+ ]
454
+ values = grad_err_flat[pixels[~np.isin(pixels, np.concatenate(centerline_pixels))]]
455
+ values = np.asarray(values[np.isfinite(values)], dtype=np.float32)
456
+ score = float(np.median(values)) if values.size else float("nan")
457
+ fragment.grad_quality_score = score
458
+ if values.size >= int(min_valid_pixels) and np.isfinite(score):
459
+ reliable.append((fragment, pixels))
460
+
461
+ drop_count = int(np.floor(len(reliable) * float(trim_fraction)))
462
+ if drop_count > 0:
463
+ ordered = sorted(reliable, key=lambda item: (-float(item[0].grad_quality_score), int(item[0].fragment_id)))
464
+ drop_ids = {int(frag.fragment_id) for frag, _ in ordered[:drop_count]}
465
+ reliable = [item for item in reliable if int(item[0].fragment_id) not in drop_ids]
466
+ return [frag for frag, _ in reliable], [pixels for _, pixels in reliable]
467
+
468
+
469
+ def _filter_measurement_centerlines(
470
+ *,
471
+ segmentation_fragments: list[FiberFragment],
472
+ dt_u8: np.ndarray,
473
+ dt: np.ndarray,
474
+ gx: np.ndarray | None,
475
+ gy: np.ndarray | None,
476
+ max_angle_deg: float,
477
+ win_len: float,
478
+ std_thresh: float,
479
+ strict: bool,
480
+ keep_segments_without_measurement_centerlines: bool,
481
+ ) -> list[FiberFragment]:
482
+ """Collect measurement centerlines per fragment and update fragments in place."""
483
+ if strict and (gx is None or gy is None):
484
+ raise ValueError("Strict centerline filtering requires dt, grad_x, and grad_y.")
485
+ if not strict:
486
+ gx = gy = dt # never read outside strict mode, but numba needs arrays
487
+ active_segmentation_fragments: list[FiberFragment] = []
488
+ for seg in segmentation_fragments:
489
+ seg.measurement_centerlines_xy = []
490
+ for polyline_xy in seg.segment_centerlines_xy:
491
+ pts_xy = np.ascontiguousarray(polyline_xy, dtype=np.float32).reshape(-1, 2)
492
+ spans = _window_spans(
493
+ pts_xy, dt_u8, dt, gx, gy, float(win_len), float(std_thresh), float(max_angle_deg), bool(strict)
494
+ )
495
+ seg.measurement_centerlines_xy += [pts_xy[s:e + 1].copy() for s, e in spans]
496
+ seg.recompute_total_measurement_centerline_length_px()
497
+ if seg.has_measurement_centerline:
498
+ active_segmentation_fragments.append(seg)
499
+ if bool(keep_segments_without_measurement_centerlines):
500
+ active_segmentation_fragments = list(segmentation_fragments)
501
+ return active_segmentation_fragments
502
+
503
+
504
+ def _clamp_trim_fraction(value: float) -> float:
505
+ value = float(value)
506
+ if not np.isfinite(value):
507
+ return 0.05
508
+ return float(min(0.95, max(0.0, value)))
509
+
510
+
511
+ # ------------------------------------------------------------------ #
512
+ # Labels
513
+
514
+
515
+ def _watershed(
516
+ dt_u8: np.ndarray,
517
+ gx: np.ndarray,
518
+ gy: np.ndarray,
519
+ markers: np.ndarray,
520
+ gradient_threshold: float,
521
+ ) -> np.ndarray:
522
+ """
523
+ Watershed on inverted DT, constrained by thresholded gradient magnitude.
524
+
525
+ Two dilations of the detected centerline markers are added to the
526
+ threshold mask. The combined mask is then eroded and dilated before
527
+ watershed.
528
+ """
529
+
530
+ dt_u8 = np.asarray(dt_u8)
531
+ gx = np.asarray(gx, dtype=np.float32)
532
+ gy = np.asarray(gy, dtype=np.float32)
533
+ markers = np.asarray(markers)
534
+ if gx.shape != dt_u8.shape or gy.shape != dt_u8.shape or markers.shape != dt_u8.shape:
535
+ raise ValueError("DT, gradients, and markers must have matching shapes.")
536
+ if not markers.any():
537
+ return np.zeros_like(dt_u8, dtype=np.uint16)
538
+
539
+ threshold = float(gradient_threshold)
540
+ if not np.isfinite(threshold) or threshold < 0.0:
541
+ raise ValueError("Gradient magnitude threshold must be finite and non-negative.")
542
+
543
+ dt_norm = dt_u8.astype(np.float32) / 255.0
544
+ grad_magnitude = np.hypot(gx, gy)
545
+ fiber_region_mask = np.isfinite(grad_magnitude) & (grad_magnitude >= threshold)
546
+
547
+ morphology_kernel = np.ones((3, 3), dtype=np.uint8)
548
+ centerline_mask = (markers > 0).astype(np.uint8)
549
+ dilated_centerlines = cv2.dilate(
550
+ centerline_mask,
551
+ morphology_kernel,
552
+ iterations=2,
553
+ ).astype(bool)
554
+ fiber_region_mask |= dilated_centerlines
555
+ fiber_region_mask_u8 = fiber_region_mask.astype(np.uint8)
556
+ fiber_region_mask_u8 = cv2.erode(
557
+ fiber_region_mask_u8,
558
+ morphology_kernel,
559
+ iterations=1,
560
+ )
561
+ fiber_region_mask = cv2.dilate(
562
+ fiber_region_mask_u8,
563
+ morphology_kernel,
564
+ iterations=1,
565
+ ).astype(bool)
566
+
567
+ elev = 1.0 - dt_norm
568
+ if not fiber_region_mask.any():
569
+ return np.zeros_like(dt_u8, dtype=np.uint16)
570
+ marker_pixels = markers > 0
571
+ logger.info(
572
+ "Watershed gradient mask: threshold=%.4f mask=%d/%d marker_pixels=%d/%d",
573
+ threshold,
574
+ int(np.count_nonzero(fiber_region_mask)),
575
+ int(fiber_region_mask.size),
576
+ int(np.count_nonzero(fiber_region_mask & marker_pixels)),
577
+ int(np.count_nonzero(marker_pixels)),
578
+ )
579
+ conn8 = np.ones((3, 3), dtype=bool)
580
+ labels = watershed(
581
+ elev,
582
+ markers=markers,
583
+ mask=fiber_region_mask,
584
+ connectivity=conn8,
585
+ ).astype(np.uint16)
586
+ return labels
587
+
588
+
589
+ def _prune_labels_by_foreground(
590
+ labels: np.ndarray,
591
+ *,
592
+ foreground_prob: np.ndarray | None,
593
+ min_segment_foreground_mean: float = 0.5,
594
+ ) -> np.ndarray:
595
+ if foreground_prob is None:
596
+ return labels
597
+ labels_arr = np.asarray(labels)
598
+ foreground_arr = np.asarray(foreground_prob, dtype=np.float32)
599
+ if labels_arr.shape != foreground_arr.shape:
600
+ raise ValueError("Foreground probability must match label shape.")
601
+
602
+ threshold = float(min_segment_foreground_mean)
603
+ if not np.isfinite(threshold):
604
+ threshold = 0.5
605
+ threshold = float(np.clip(threshold, 0.0, 1.0))
606
+
607
+ pruned = labels_arr.copy()
608
+ # value_indices lists each label's pixels in raster order, so the float32 mean
609
+ # sums the same values in the same order as a boolean mask would.
610
+ for label_id, pixels in value_indices(labels_arr).items():
611
+ if label_id > 0 and float(np.mean(foreground_arr[pixels])) < threshold:
612
+ pruned[pixels] = 0
613
+ return pruned.astype(labels_arr.dtype, copy=False)
614
+
615
+
616
+ def _render_markers(shape: tuple[int, int], segments: list[FiberFragment]) -> np.ndarray:
617
+ markers = np.zeros(shape, dtype=np.int32)
618
+ for seg in segments:
619
+ for polyline_xy in seg.segment_centerlines_xy:
620
+ pts = np.asarray(polyline_xy, dtype=np.float32)
621
+ pts_int = np.round(pts).astype(np.int32).reshape(-1, 1, 2)
622
+ cv2.polylines(
623
+ markers,
624
+ [pts_int],
625
+ isClosed=False,
626
+ color=int(seg.parent_fiber_id),
627
+ thickness=1,
628
+ lineType=cv2.LINE_8,
629
+ )
630
+ return markers
631
+
632
+
633
+ # ------------------------------------------------------------------ #
634
+ # Measurement-centerline windows
635
+
636
+ # Strict-mode thresholds; never configured, so numba folds them in as constants.
637
+ _GRAD_ALIGNMENT_COS = 0.95
638
+ _RADIUS_REL_TOL = 0.25
639
+ _MIN_VALID_FRACTION = 0.7
640
+
641
+
642
+ @njit(cache=True)
643
+ def _window_spans(pts_xy, image, dt, gx, gy, win_len, std_thresh, max_angle_deg, strict):
644
+ """Merged (start, end) point spans of flat, level windows, each at least `win_len` long.
645
+
646
+ Windows of arc length `win_len` slide along the polyline in steps of `win_len / 2`.
647
+ A window is accepted when `image` is flat along it (low std, small end-to-end rise)
648
+ and, in strict mode, when the DT looks like a clean fiber cross-section.
649
+ Overlapping accepted windows merge as they are found.
650
+ """
651
+ n = len(pts_xy)
652
+ h, w = image.shape
653
+ cum = np.zeros(n, dtype=np.float32) # arc length at each point
654
+ intens = np.empty(n, dtype=np.float64) # image at each point, rounded to the nearest pixel
655
+ total = 0.0
656
+ for i in range(n):
657
+ if i > 0:
658
+ dx, dy = pts_xy[i, 0] - pts_xy[i - 1, 0], pts_xy[i, 1] - pts_xy[i - 1, 1]
659
+ total += np.sqrt(dx * dx + dy * dy)
660
+ cum[i] = total
661
+ x = min(max(int(np.rint(pts_xy[i, 0])), 0), w - 1)
662
+ y = min(max(int(np.rint(pts_xy[i, 1])), 0), h - 1)
663
+ intens[i] = image[y, x]
664
+
665
+ spans = np.empty((n, 2), dtype=np.int64)
666
+ k = 0
667
+ if n < 2 or cum[-1] <= 0:
668
+ return spans[:0]
669
+ s = 0
670
+ while s < n - 1:
671
+ e = min(max(np.searchsorted(cum, cum[s] + win_len), s + 1), n - 1)
672
+ if _is_flat(intens[s:e + 1], cum[e] - cum[s], std_thresh, max_angle_deg) and (
673
+ not strict or _is_clean_cross_section(pts_xy[s:e + 1], dt, gx, gy)
674
+ ):
675
+ if k > 0 and s <= spans[k - 1, 1]:
676
+ spans[k - 1, 1] = max(spans[k - 1, 1], e)
677
+ else:
678
+ spans[k, 0], spans[k, 1] = s, e
679
+ k += 1
680
+ next_s = np.searchsorted(cum, cum[s] + win_len / 2.0)
681
+ if next_s <= s:
682
+ break
683
+ s = next_s
684
+ spans = spans[:k]
685
+ return spans[cum[spans[:, 1]] - cum[spans[:, 0]] >= win_len]
686
+
687
+
688
+ @njit(cache=True)
689
+ def _is_flat(intens, length, std_thresh, max_angle_deg):
690
+ """Low intensity spread, and a rise from first to last point below `max_angle_deg`.
691
+
692
+ Intensities are integers, so distinct stds are far apart and float32 rounding only
693
+ merges a std with a threshold it exactly equals; that tie counts as not flat.
694
+ """
695
+ if length <= 0.0 or np.float32(np.sqrt(np.mean((intens - np.mean(intens)) ** 2))) >= np.float32(std_thresh):
696
+ return False
697
+ return np.degrees(np.arctan(abs(intens[-1] - intens[0]) / length)) < max_angle_deg
698
+
699
+
700
+ @njit(cache=True)
701
+ def _is_clean_cross_section(pts_xy, dt, gx, gy):
702
+ """Most points look like a clean fiber cross-section in the DT.
703
+
704
+ At each point, probe half the local radius r to either side along the normal: the
705
+ DT gradients there must point in opposite directions and the DT must be about r/2.
706
+ """
707
+ n = len(pts_xy)
708
+ valid = total = 0
709
+ for i in range(n):
710
+ a, b = max(i - 1, 0), min(i + 1, n - 1)
711
+ tx, ty = pts_xy[b, 0] - pts_xy[a, 0], pts_xy[b, 1] - pts_xy[a, 1]
712
+ tan_norm = np.sqrt(tx * tx + ty * ty) + np.float32(1e-6)
713
+ nx, ny = float(-ty / tan_norm), float(tx / tan_norm)
714
+ px, py = float(pts_xy[i, 0]), float(pts_xy[i, 1])
715
+ r = _bilinear(dt, py, px)
716
+ if r <= 1e-6 or (abs(nx) <= 1e-8 and abs(ny) <= 1e-8):
717
+ continue
718
+
719
+ h = 0.5 * r
720
+ g_plus = _sample_vec2(gx, gy, py + ny * h, px + nx * h)
721
+ g_minus = _sample_vec2(gx, gy, py - ny * h, px - nx * h)
722
+ mag_plus = np.sqrt(g_plus[0] ** 2 + g_plus[1] ** 2)
723
+ mag_minus = np.sqrt(g_minus[0] ** 2 + g_minus[1] ** 2)
724
+ if mag_plus <= 1e-6 or mag_minus <= 1e-6:
725
+ continue
726
+ u_plus, u_minus = g_plus / (mag_plus + 1e-6), g_minus / (mag_minus + 1e-6)
727
+ opposed = -(u_plus[0] * u_minus[0] + u_plus[1] * u_minus[1]) >= _GRAD_ALIGNMENT_COS
728
+
729
+ tol = _RADIUS_REL_TOL * max(r, 1e-6)
730
+ radius_ok = (
731
+ abs(_bilinear(dt, py + ny * h, px + nx * h) - h) <= tol
732
+ and abs(_bilinear(dt, py - ny * h, px - nx * h) - h) <= tol
733
+ )
734
+ total += 1
735
+ valid += opposed and radius_ok
736
+ return total > 0 and valid / total >= _MIN_VALID_FRACTION
src/fiberpose/api.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable public entry point for analysing a single image.
2
+
3
+ External code (the web demo, notebooks, plugins) should use ``analyze`` and
4
+ ``AnalysisResult`` instead of driving ``PipelineController`` directly.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from functools import lru_cache
11
+ from typing import Any, Optional
12
+
13
+ import numpy as np
14
+
15
+ from .domain import AppConfig, Frame, SampleProperties
16
+ from .ml import onnx_cuda_available
17
+ from .models import resolve_model_path
18
+ from .pipeline import PipelineController
19
+ from .utils import ensure_rgb_u8
20
+
21
+ __all__ = ["AnalysisResult", "FiberposeError", "analyze"]
22
+
23
+ class FiberposeError(RuntimeError):
24
+ """Raised when the pipeline fails on an image."""
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class AnalysisResult:
29
+ """Outputs of ``analyze`` for one image.
30
+
31
+ All arrays are in the coordinate frame of ``image`` (after the optional
32
+ ``config.scale_label`` rescaling).
33
+ """
34
+
35
+ image: np.ndarray
36
+ distance_transform: np.ndarray
37
+ labels: Optional[np.ndarray]
38
+ diameters: np.ndarray
39
+ angles_deg: np.ndarray
40
+ # (y, x, ny, nx, radius_px, angle_deg) per sample, for drawing diameter lines.
41
+ samples: list = field(default_factory=list)
42
+ summary: dict[str, Any] = field(default_factory=dict)
43
+ unit: str = "px"
44
+ # Set when segmentation succeeded but no measurements could be taken.
45
+ message: Optional[str] = None
46
+ frame: Optional[Frame] = field(default=None, repr=False)
47
+
48
+
49
+ @lru_cache(maxsize=2)
50
+ def _controller(model_path: str, device: str) -> PipelineController:
51
+ return PipelineController(model_path, device)
52
+
53
+
54
+ def analyze(
55
+ image: np.ndarray,
56
+ config: AppConfig | None = None,
57
+ *,
58
+ pixel_size: float = 1.0,
59
+ unit: str = "px",
60
+ invert: bool = False,
61
+ previous: AnalysisResult | None = None,
62
+ ) -> AnalysisResult:
63
+ """Run prediction, segmentation and measurements on a 2D image.
64
+
65
+ ``config.model_path`` selects the model by file name or absolute path; when
66
+ empty, the default pretrained model is used (downloaded on first use).
67
+
68
+ Pass the ``previous`` result of the same image to change settings without
69
+ repeating the stages they don't affect (e.g. the model prediction).
70
+ """
71
+ config = config or AppConfig(use_gpu=False)
72
+ model_path = resolve_model_path(config.model_path)
73
+ device = "cuda" if config.use_gpu and onnx_cuda_available() else "cpu"
74
+ sample_props = SampleProperties(
75
+ pixel_size_x=float(pixel_size),
76
+ pixel_size_y=float(pixel_size),
77
+ unit=str(unit).strip() or "px",
78
+ source="api",
79
+ )
80
+ frame = previous.frame if previous else Frame.empty(frame_id="image", orig_img=np.asarray(image))
81
+
82
+ outcome = _controller(model_path, device).ensure_measurements(
83
+ frame, config, sample_props, invert_input=bool(invert)
84
+ )
85
+
86
+ if outcome.error_message or not frame.has_segmentation:
87
+ raise FiberposeError(outcome.error_message or outcome.info_message or "Processing failed.")
88
+
89
+ base = frame.orig_img_scaled if frame.scale_factor != 1.0 and frame.orig_img_scaled is not None else frame.orig_img
90
+ measured = outcome.ok
91
+ return AnalysisResult(
92
+ image=ensure_rgb_u8(base),
93
+ distance_transform=np.asarray(frame.dt, dtype=np.float32),
94
+ labels=frame.labels_2d,
95
+ diameters=_as_array(frame.thickness_units if measured else None),
96
+ angles_deg=_as_array([s[5] for s in frame.measurement_samples or []] if measured else None),
97
+ samples=list(frame.drawing_samples or []) if measured else [],
98
+ summary=dict(frame.fiber_summary or {}) if measured else {},
99
+ unit=sample_props.unit,
100
+ message=None if measured else outcome.info_message,
101
+ frame=frame,
102
+ )
103
+
104
+
105
+ def _as_array(values: Any) -> np.ndarray:
106
+ if values is None:
107
+ return np.array([], dtype=np.float32)
108
+ return np.asarray(values, dtype=np.float32)
src/fiberpose/cli.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Application entry point for launching the Fiberpose GUI, CLI or web interface.
2
+
3
+ Installed as the ``fiberpose`` command and run by ``python -m fiberpose``.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+
10
+ # Must be set before numpy/onnxruntime/torch load their OpenMP runtimes.
11
+ os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
12
+
13
+ import argparse
14
+
15
+ from . import __version__
16
+ from .paths import USER_CONFIG_PATH, default_config_path
17
+
18
+
19
+ def _build_parser() -> argparse.ArgumentParser:
20
+ parser = argparse.ArgumentParser(prog="fiberpose", description="Fiberpose launcher (GUI, CLI, web).")
21
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
22
+ group = parser.add_mutually_exclusive_group()
23
+ group.add_argument("--cli", action="store_true", help="Run command-line batch processing mode.")
24
+ group.add_argument("--gui", action="store_true", help="Force GUI mode (default when --cli is not set).")
25
+ group.add_argument("--web", action="store_true", help="Serve the Gradio web interface.")
26
+
27
+ parser.add_argument("--input", dest="input_path", help="Input path for CLI mode (folder, stack, or image).")
28
+ parser.add_argument(
29
+ "--config",
30
+ dest="config_path",
31
+ default=None,
32
+ help=f"Config JSON path (default: {USER_CONFIG_PATH}).",
33
+ )
34
+ parser.add_argument("--output", dest="output_dir", help="Output directory for CLI exports.")
35
+ parser.add_argument(
36
+ "--measurements",
37
+ action="store_true",
38
+ help="Compute full measurements in CLI mode (default: segmentation only).",
39
+ )
40
+ parser.add_argument(
41
+ "--invert",
42
+ action="store_true",
43
+ default=None,
44
+ help="Invert input intensities before inference (CLI mode).",
45
+ )
46
+ parser.add_argument(
47
+ "--save-kind",
48
+ choices=("results", "csv"),
49
+ default="results",
50
+ help="CLI export preset kind (default: results).",
51
+ )
52
+ return parser
53
+
54
+
55
+ def _launch_gui(config_path: str) -> int:
56
+ try:
57
+ from .gui import launch
58
+ except ImportError:
59
+ print('Error: the GUI requires PyQt6. In the Fiberpose folder, run: pip install -e ".[gui]"')
60
+ return 2
61
+ return launch(config_path)
62
+
63
+
64
+ def _launch_web(config_path: str) -> int:
65
+ try:
66
+ from .web import launch
67
+ except ImportError:
68
+ print('Error: the web interface requires Gradio. Run: pip install "fiberpose[web]"')
69
+ return 2
70
+ from .domain import AppConfig
71
+
72
+ launch(AppConfig.load_from_json(config_path))
73
+ return 0
74
+
75
+
76
+ def _launch_cli(args: argparse.Namespace, config_path: str) -> int:
77
+ if not args.input_path:
78
+ print("Error: --input is required with --cli.")
79
+ return 2
80
+ if not os.path.exists(os.path.abspath(args.input_path)):
81
+ print(f"Error: input path does not exist: {os.path.abspath(args.input_path)}")
82
+ return 2
83
+
84
+ from .cli_runner import CliRunner
85
+
86
+ runner = CliRunner(
87
+ input_path=args.input_path,
88
+ config_path=config_path,
89
+ output_dir=args.output_dir,
90
+ compute_measurements=bool(args.measurements),
91
+ invert_input=args.invert,
92
+ save_kind=args.save_kind,
93
+ )
94
+ return int(runner.run())
95
+
96
+
97
+ def main(argv: list[str] | None = None) -> int:
98
+ parser = _build_parser()
99
+ args = parser.parse_args(argv)
100
+
101
+ if args.config_path:
102
+ config_path = os.path.abspath(args.config_path)
103
+ if not os.path.exists(config_path):
104
+ print(f"Error: config path does not exist: {config_path}")
105
+ return 2
106
+ else:
107
+ config_path = default_config_path()
108
+
109
+ if args.cli:
110
+ return _launch_cli(args, config_path)
111
+ if args.web:
112
+ return _launch_web(config_path)
113
+ return _launch_gui(config_path)
114
+
115
+
116
+ if __name__ == "__main__":
117
+ raise SystemExit(main())
src/fiberpose/cli_runner.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI runner for batch-oriented Fiberpose processing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from datetime import datetime
8
+ from typing import Any, Iterable
9
+
10
+ import imageio.v3 as iio
11
+ from .domain import AppConfig, BatchResult, Frame, ImageBatch, SampleProperties
12
+ from .models import resolve_model_path
13
+ from .paths import default_config_path
14
+
15
+ from tqdm import tqdm
16
+
17
+
18
+ class CliRunner:
19
+ """Run segmentation/measurement batch processing from the command line."""
20
+
21
+ def __init__(
22
+ self,
23
+ *,
24
+ input_path: str,
25
+ config_path: str | None = None,
26
+ output_dir: str | None = None,
27
+ compute_measurements: bool = False,
28
+ invert_input: bool | None = None,
29
+ save_kind: str = "results",
30
+ ) -> None:
31
+ self.input_path = str(input_path)
32
+ self.config_path = os.path.abspath(config_path or default_config_path())
33
+ self.output_dir = output_dir
34
+ self.compute_measurements = bool(compute_measurements)
35
+ self.invert_input = invert_input
36
+ self.save_kind = str(save_kind)
37
+
38
+ @staticmethod
39
+ def _resolve_model_path(config: AppConfig) -> str:
40
+ return resolve_model_path(config.model_path)
41
+
42
+ @staticmethod
43
+ def _resolve_device(config: AppConfig) -> str:
44
+ from .ml import onnx_cuda_available
45
+
46
+ if bool(config.use_gpu) and onnx_cuda_available():
47
+ return "cuda"
48
+ return "cpu"
49
+
50
+ def _effective_output_dir(self) -> str:
51
+ if self.output_dir:
52
+ return os.path.abspath(self.output_dir)
53
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
54
+ return os.path.join(os.getcwd(), f"fiberpose_cli_{timestamp}")
55
+
56
+ @staticmethod
57
+ def _supported_image_extensions() -> set[str]:
58
+ return {".tif", ".tiff", ".png", ".jpg", ".jpeg", ".bmp", ".webp"}
59
+
60
+ @staticmethod
61
+ def _frame_identity(image_batch: ImageBatch, index: int) -> tuple[str, int]:
62
+ metadata = image_batch.metadata or {}
63
+ filenames = metadata.get("filenames", [])
64
+ z_indices = metadata.get("z_indices", [])
65
+
66
+ frame_id = str(filenames[index]) if index < len(filenames) else str(index)
67
+ z_index = int(z_indices[index]) if index < len(z_indices) else int(index)
68
+ return frame_id, z_index
69
+
70
+ @staticmethod
71
+ def _outcome_message(outcome: Any) -> str:
72
+ if outcome is None:
73
+ return "unknown pipeline failure"
74
+ if getattr(outcome, "error_message", None):
75
+ return str(outcome.error_message)
76
+ if getattr(outcome, "info_message", None):
77
+ return str(outcome.info_message)
78
+ return "pipeline stage failed"
79
+
80
+ @staticmethod
81
+ def _is_frame_success(frame: Frame, compute_measurements: bool) -> bool:
82
+ return bool(frame.has_measurements) if compute_measurements else bool(frame.has_segmentation)
83
+
84
+ @staticmethod
85
+ def _progress(total: int, desc: str):
86
+ return tqdm(total=int(total), desc=desc, unit="frame")
87
+
88
+ @classmethod
89
+ def _folder_frame_iterator(
90
+ cls,
91
+ folder_path: str,
92
+ ) -> tuple[Iterable[tuple[Any, str, int]], dict[str, Any], int]:
93
+ entries = sorted(os.listdir(folder_path))
94
+ ext_set = cls._supported_image_extensions()
95
+ jobs: list[tuple[str, str, int]] = []
96
+ total = 0
97
+ first_valid_path: str | None = None
98
+
99
+ for name in entries:
100
+ path = os.path.join(folder_path, name)
101
+ if not os.path.isfile(path):
102
+ continue
103
+ if os.path.splitext(name)[1].lower() not in ext_set:
104
+ continue
105
+ try:
106
+ probe = iio.imread(path)
107
+ except Exception:
108
+ continue
109
+ if first_valid_path is None:
110
+ first_valid_path = path
111
+ frames_count = len(ImageBatch._normalize_stack(probe))
112
+ del probe
113
+ if frames_count <= 0:
114
+ continue
115
+ jobs.append((path, name, frames_count))
116
+ total += int(frames_count)
117
+
118
+ if first_valid_path is None or total == 0:
119
+ raise ValueError("Input folder contains no readable image frames.")
120
+
121
+ metadata: dict[str, Any] = {
122
+ "source_type": "Folder",
123
+ "source_path": folder_path,
124
+ "z_indices": list(range(total)),
125
+ }
126
+ metadata.update(ImageBatch._extract_voxel_sizes(first_valid_path))
127
+
128
+ def _iter() -> Iterable[tuple[Any, str, int]]:
129
+ z_counter = 0
130
+ for path, name, _frames_count in jobs:
131
+ data = iio.imread(path)
132
+ frames = ImageBatch._normalize_stack(data)
133
+ for frame in frames:
134
+ frame_id = name
135
+ yield frame, frame_id, z_counter
136
+ z_counter += 1
137
+
138
+ return _iter(), metadata, total
139
+
140
+ def _process_one_frame(
141
+ self,
142
+ *,
143
+ frame_img: Any,
144
+ frame_id: str,
145
+ z_index: int,
146
+ config: AppConfig,
147
+ sample_props: SampleProperties,
148
+ controller: Any,
149
+ invert_input: bool,
150
+ ) -> Frame:
151
+ frame = Frame.empty(frame_id=frame_id, z_index=z_index, orig_img=frame_img)
152
+ if self.compute_measurements:
153
+ outcome = controller.ensure_measurements(
154
+ frame,
155
+ config,
156
+ sample_props,
157
+ invert_input=invert_input,
158
+ )
159
+ else:
160
+ outcome = controller.ensure_segmentation(frame, config, invert_input=invert_input)
161
+
162
+ if not outcome.ok and not frame.error_message:
163
+ frame.fail(self._outcome_message(outcome))
164
+ return frame
165
+
166
+ def _process_batch(
167
+ self,
168
+ *,
169
+ image_batch: ImageBatch,
170
+ config: AppConfig,
171
+ controller: Any,
172
+ invert_input: bool,
173
+ ) -> BatchResult:
174
+ frame_results: list[Frame] = []
175
+
176
+ progress = self._progress(len(image_batch.frames), "Processing")
177
+ for idx, image in enumerate(image_batch.frames):
178
+ frame_id, z_index = self._frame_identity(image_batch, idx)
179
+ frame = Frame.empty(frame_id=frame_id, z_index=z_index, orig_img=image)
180
+
181
+ if self.compute_measurements:
182
+ outcome = controller.ensure_measurements(
183
+ frame,
184
+ config,
185
+ SampleProperties.from_image_metadata(
186
+ image_batch.metadata,
187
+ source_path=str((image_batch.metadata or {}).get("source_path", "")),
188
+ ),
189
+ invert_input=invert_input,
190
+ )
191
+ else:
192
+ outcome = controller.ensure_segmentation(frame, config, invert_input=invert_input)
193
+
194
+ if not outcome.ok and not frame.error_message:
195
+ frame.fail(self._outcome_message(outcome))
196
+
197
+ frame_results.append(
198
+ frame.snapshot(
199
+ frame_id=frame_id,
200
+ z_index=z_index,
201
+ )
202
+ )
203
+ progress.update(1)
204
+ progress.close()
205
+ return BatchResult(frame_results=frame_results)
206
+
207
+ def _run_streaming_folder(
208
+ self,
209
+ *,
210
+ folder_path: str,
211
+ config: AppConfig,
212
+ controller: Any,
213
+ invert_input: bool,
214
+ output_dir: str,
215
+ ) -> int:
216
+ from .io_export import BatchResultExporter, ExportService
217
+
218
+ frame_iter, metadata, total_frames = self._folder_frame_iterator(folder_path)
219
+ sample_props = SampleProperties.from_image_metadata(metadata, source_path=folder_path)
220
+ image_batch_stub = ImageBatch(frames=[], metadata=metadata)
221
+
222
+ save_options = ExportService.normalize_save_options(config.save_options)
223
+ export_config = ExportService.build_export_config(
224
+ kind=self.save_kind,
225
+ layout="frames",
226
+ save_options=save_options,
227
+ source_base_name=ExportService.current_source_base_name(image_batch_stub, current_image_name=None),
228
+ base_name=None,
229
+ image_format_override=None,
230
+ )
231
+ export_config["write_manifest"] = False
232
+
233
+ exporter = BatchResultExporter(export_config=export_config)
234
+ failures: list[tuple[str, str]] = []
235
+ processed = 0
236
+ written_files: list[str] = []
237
+ skipped: list[dict[str, Any]] = []
238
+ errors: list[dict[str, Any]] = []
239
+
240
+ progress = self._progress(total_frames, "Processing")
241
+ for frame_img, frame_id, z_index in frame_iter:
242
+ frame = self._process_one_frame(
243
+ frame_img=frame_img,
244
+ frame_id=frame_id,
245
+ z_index=z_index,
246
+ config=config,
247
+ sample_props=sample_props,
248
+ controller=controller,
249
+ invert_input=invert_input,
250
+ )
251
+ if self._is_frame_success(frame, self.compute_measurements):
252
+ processed += 1
253
+ else:
254
+ failures.append((str(frame.frame_id), str(frame.error_message or "Processing failed")))
255
+
256
+ batch = BatchResult(frame_results=[frame])
257
+ export_result = exporter.save_all(batch, output_dir, export_config=export_config)
258
+ written_files.extend(export_result.get("written_files", []))
259
+ skipped.extend(export_result.get("skipped", []))
260
+ errors.extend(export_result.get("errors", []))
261
+ for err in export_result.get("errors", []):
262
+ failures.append(
263
+ (
264
+ str(err.get("frame_id", f"frame_{err.get('frame_index', '?')}")),
265
+ f"Export {err.get('artifact', 'artifact')} failed: {err.get('error', 'unknown error')}",
266
+ )
267
+ )
268
+ del batch
269
+ del frame
270
+ del frame_img
271
+ progress.update(1)
272
+ progress.close()
273
+
274
+ manifest = {
275
+ "export_config": export_config,
276
+ "written_files": [os.path.relpath(p, output_dir) for p in written_files],
277
+ "written_count": len(written_files),
278
+ "skipped": skipped,
279
+ "errors": errors,
280
+ }
281
+ manifest_path = os.path.join(output_dir, "manifest.json")
282
+ with open(manifest_path, "w", encoding="utf-8") as handle:
283
+ json.dump(manifest, handle, indent=2)
284
+
285
+ print(f"Processed {processed} of {total_frames} frames.")
286
+ print(f"Saved {len(written_files)} file(s) in: {output_dir}")
287
+ if failures:
288
+ print("Failures:")
289
+ for frame_name, reason in failures[:10]:
290
+ print(f" - {os.path.basename(frame_name)}: {reason}")
291
+ if len(failures) > 10:
292
+ print(f" ... ({len(failures) - 10} more)")
293
+ return 0 if not failures else 1
294
+
295
+ def _print_summary(self, *, batch_result: BatchResult, export_result: dict[str, Any]) -> list[tuple[str, str]]:
296
+ failures: list[tuple[str, str]] = []
297
+ processed = 0
298
+ for fr in batch_result.frame_results:
299
+ if self.compute_measurements:
300
+ ok = bool(fr.has_measurements)
301
+ else:
302
+ ok = bool(fr.has_segmentation)
303
+ if ok:
304
+ processed += 1
305
+ else:
306
+ failures.append((str(fr.frame_id), str(fr.error_message or "Processing failed")))
307
+
308
+ export_errors = export_result.get("errors", [])
309
+ for err in export_errors:
310
+ failures.append(
311
+ (
312
+ str(err.get("frame_id", f"frame_{err.get('frame_index', '?')}")),
313
+ f"Export {err.get('artifact', 'artifact')} failed: {err.get('error', 'unknown error')}",
314
+ )
315
+ )
316
+
317
+ print(f"Processed {processed} of {len(batch_result.frame_results)} frames.")
318
+ print(f"Saved {int(export_result.get('written_count', 0))} file(s) in: {export_result.get('output_dir')}")
319
+ if failures:
320
+ print("Failures:")
321
+ for frame_id, reason in failures[:10]:
322
+ print(f" - {os.path.basename(frame_id)}: {reason}")
323
+ if len(failures) > 10:
324
+ print(f" ... ({len(failures) - 10} more)")
325
+ return failures
326
+
327
+ def run(self) -> int:
328
+ if not self.input_path:
329
+ print("Error: --input is required in CLI mode.")
330
+ return 2
331
+ if self.save_kind not in {"results", "csv"}:
332
+ print("Error: --save-kind must be one of: results, csv.")
333
+ return 2
334
+
335
+ source_path = os.path.abspath(self.input_path)
336
+ if not os.path.exists(source_path):
337
+ print(f"Error: input path does not exist: {source_path}")
338
+ return 2
339
+
340
+ try:
341
+ config = AppConfig.load_from_json(self.config_path)
342
+ except Exception as exc:
343
+ print(f"Error: failed to load config '{self.config_path}': {exc}")
344
+ return 2
345
+
346
+ invert_input = bool(self.invert_input) if self.invert_input is not None else False
347
+ try:
348
+ model_path = self._resolve_model_path(config)
349
+ except Exception as exc:
350
+ print(f"Error: failed to locate or download the model: {exc}")
351
+ return 2
352
+ try:
353
+ device = self._resolve_device(config)
354
+ except Exception as exc:
355
+ print(f"Error: failed to detect runtime providers: {exc}")
356
+ return 2
357
+
358
+ from .pipeline import PipelineController
359
+
360
+ controller = PipelineController(model_path, device)
361
+
362
+ output_dir = self._effective_output_dir()
363
+ os.makedirs(output_dir, exist_ok=True)
364
+
365
+ if os.path.isdir(source_path):
366
+ return self._run_streaming_folder(
367
+ folder_path=source_path,
368
+ config=config,
369
+ controller=controller,
370
+ invert_input=invert_input,
371
+ output_dir=output_dir,
372
+ )
373
+
374
+ try:
375
+ image_batch = ImageBatch.from_source(source_path)
376
+ except Exception as exc:
377
+ print(f"Error: failed to load input '{source_path}': {exc}")
378
+ return 2
379
+
380
+ if len(image_batch) == 0:
381
+ print("Error: input source has no readable frames.")
382
+ return 2
383
+
384
+ batch_result = self._process_batch(
385
+ image_batch=image_batch,
386
+ config=config,
387
+ controller=controller,
388
+ invert_input=invert_input,
389
+ )
390
+
391
+ from .io_export import ExportService
392
+
393
+ save_options = ExportService.normalize_save_options(config.save_options)
394
+ layout = ExportService.current_save_layout(image_batch)
395
+ source_base_name = ExportService.current_source_base_name(image_batch, current_image_name=None)
396
+ export_config = ExportService.build_export_config(
397
+ kind=self.save_kind,
398
+ layout=layout,
399
+ save_options=save_options,
400
+ source_base_name=source_base_name,
401
+ base_name=None,
402
+ image_format_override=None,
403
+ )
404
+
405
+ export_result = batch_result.save_all(output_dir, export_config)
406
+ failures = self._print_summary(batch_result=batch_result, export_result=export_result)
407
+ return 0 if not failures else 1
src/fiberpose/domain.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core data models for configuration, batches, frame outputs, and fiber geometry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field, asdict
7
+ from copy import copy
8
+ from typing import Any, Dict, Iterable, List, Optional
9
+ import os
10
+ import imageio.v3 as iio
11
+ import numpy as np
12
+ import logging
13
+ from tifffile import TiffFile
14
+ logger = logging.getLogger(__name__)
15
+
16
+ @dataclass
17
+ class AppConfig:
18
+ # --- Model & Hardware ---
19
+ """Store configuration values for app."""
20
+ model_path: str = ""
21
+ use_gpu: bool = True
22
+ scale_label: str = "1x"
23
+
24
+ # --- Centerline Params ---
25
+ max_angle_deg: float = 30.0
26
+ ridge_sigma: float = 1.0
27
+ ridge_low: float = 0.01
28
+ ridge_high: float = 0.4
29
+ min_fragment_centerline_length_px: float = 10.0
30
+ measurement_centerline_length_trim_fraction: float = 0.05
31
+ grad_quality_trim_fraction: float = 0.0
32
+ strict_centerlines: bool = False
33
+ keep_segments_without_measurement_centerlines: bool = False
34
+
35
+ # --- Segmentation Params ---
36
+ segmentation_mode: str = "watershed"
37
+ merge_expansion_factor: float = 0.7
38
+ segmentation_expansion_factor: float = 1.0
39
+ watershed_grad_threshold: float = 0.8
40
+ # Retained for DT-based void/pore analysis; watershed uses the gradient threshold above.
41
+ seg_threshold: int = 1
42
+ min_segment_foreground_mean: float = 0.5
43
+
44
+ # --- Analysis & Physical Units ---
45
+ sample_spacing: float = 5.0
46
+
47
+ # --- DT gradient quality view ---
48
+ # Signed error breakpoints for s = |grad(dt)| - 1:
49
+ # [p0, p1, p2, p3] with p0 < p1 <= 0 <= p2 < p3.
50
+ grad_quality_points: list[float] = field(
51
+ default_factory=lambda: [-0.35, -0.08, 0.08, 0.35]
52
+ )
53
+
54
+ # --- Save/export defaults (single image, folder batch, and stack exports) ---
55
+ save_options: dict = field(
56
+ default_factory=lambda: {
57
+ "dt": True,
58
+ "foreground": True,
59
+ "labels": True,
60
+ "overlay": True,
61
+ "diameters": True,
62
+ "orientations": True,
63
+ "outline": False,
64
+ "tables": True,
65
+ "image_format": "png",
66
+ "collision": "suffix",
67
+ "write_manifest": True,
68
+ }
69
+ )
70
+
71
+ def save_to_json(self, filepath: str):
72
+ """Persist to json using the configured export conventions.
73
+
74
+ Args:
75
+ filepath (str): Filesystem location used by this operation."""
76
+ with open(filepath, 'w') as f:
77
+ json.dump(asdict(self), f, indent=4)
78
+
79
+ @classmethod
80
+ def from_dict(cls, data: Dict[str, Any]) -> "AppConfig":
81
+ """Normalize a config mapping into AppConfig."""
82
+ if not isinstance(data, dict):
83
+ raise ValueError("Config JSON root must be an object.")
84
+ data = dict(data)
85
+ valid_keys = set(cls.__dataclass_fields__)
86
+ unknown_keys = sorted(set(data.keys()) - valid_keys)
87
+ if unknown_keys:
88
+ raise ValueError(f"Unknown config key(s): {', '.join(unknown_keys)}")
89
+ return cls(**data)
90
+
91
+ @classmethod
92
+ def load_from_json(cls, filepath: str) -> "AppConfig":
93
+ try:
94
+ with open(filepath, "r", encoding="utf-8") as f:
95
+ data = json.load(f)
96
+ return cls.from_dict(data)
97
+ except FileNotFoundError:
98
+ logger.info("Config file not found: %s. Using defaults.", filepath)
99
+ return cls()
100
+
101
+
102
+ @dataclass
103
+ class SampleProperties:
104
+ """Per-loaded-sample physical calibration used by analysis and UI."""
105
+
106
+ pixel_size_x: float = 1.0
107
+ pixel_size_y: float = 1.0
108
+ voxel_size_z: float = 1.0
109
+ unit: str = "px"
110
+ source: str = "default"
111
+ source_path: str = ""
112
+
113
+ @staticmethod
114
+ def _as_positive(value: Any, default: float = 1.0) -> float:
115
+ if isinstance(value, (tuple, list)) and len(value) == 2:
116
+ try:
117
+ value = float(value[0]) / float(value[1])
118
+ except (TypeError, ValueError, ZeroDivisionError):
119
+ return float(default)
120
+ try:
121
+ out = float(value)
122
+ except (TypeError, ValueError):
123
+ return float(default)
124
+ if out <= 0 or not np.isfinite(out):
125
+ return float(default)
126
+ return out
127
+
128
+ @classmethod
129
+ def defaults(cls) -> "SampleProperties":
130
+ return cls(
131
+ pixel_size_x=1.0,
132
+ pixel_size_y=1.0,
133
+ voxel_size_z=1.0,
134
+ unit="px",
135
+ source="default",
136
+ source_path="",
137
+ )
138
+
139
+ @classmethod
140
+ def from_image_metadata(
141
+ cls,
142
+ metadata: Optional[Dict[str, Any]],
143
+ *,
144
+ source_path: str = "",
145
+ ) -> "SampleProperties":
146
+ meta = metadata or {}
147
+ px_raw = meta.get("pixel_width")
148
+ py_raw = meta.get("pixel_height")
149
+ pz_raw = meta.get("voxel_depth")
150
+ unit_raw = meta.get("unit")
151
+
152
+ has_px = px_raw is not None and cls._as_positive(px_raw, default=-1.0) > 0
153
+ has_py = py_raw is not None and cls._as_positive(py_raw, default=-1.0) > 0
154
+ has_pz = pz_raw is not None and cls._as_positive(pz_raw, default=-1.0) > 0
155
+
156
+ px = cls._as_positive(px_raw) if has_px else None
157
+ py = cls._as_positive(py_raw) if has_py else None
158
+ pz = cls._as_positive(pz_raw) if has_pz else 1.0
159
+
160
+ if px is None and py is None:
161
+ px = 1.0
162
+ py = 1.0
163
+ elif px is None:
164
+ px = py
165
+ elif py is None:
166
+ py = px
167
+
168
+ unit_txt = str(unit_raw).strip() if unit_raw is not None else ""
169
+ unit = unit_txt if unit_txt else "px"
170
+
171
+ has_metadata = bool(has_px or has_py or has_pz or unit_txt)
172
+ return cls(
173
+ pixel_size_x=float(px),
174
+ pixel_size_y=float(py),
175
+ voxel_size_z=float(pz),
176
+ unit=unit,
177
+ source="metadata" if has_metadata else "default",
178
+ source_path=str(source_path or meta.get("source_path") or ""),
179
+ )
180
+
181
+ def effective_pixel_size_xy(self) -> float:
182
+ x = self._as_positive(self.pixel_size_x)
183
+ y = self._as_positive(self.pixel_size_y)
184
+ return 0.5 * (x + y)
185
+
186
+ def spacing_zyx(self) -> tuple[float, float, float]:
187
+ return (
188
+ self._as_positive(self.voxel_size_z),
189
+ self._as_positive(self.pixel_size_y),
190
+ self._as_positive(self.pixel_size_x),
191
+ )
192
+
193
+ @dataclass
194
+ class ImageBatch:
195
+ """Container for an ordered batch of frames plus lightweight metadata."""
196
+ frames: List[np.ndarray]
197
+ metadata: Dict[str, Any] = field(default_factory=dict)
198
+
199
+ def __len__(self) -> int:
200
+ """Report how many items are currently tracked by this container.
201
+
202
+ Returns:
203
+ int: Number of items currently available in the container."""
204
+ return len(self.frames)
205
+
206
+ @property
207
+ def kind(self) -> str:
208
+ """Returns the kind of loaded info: 'Image', 'Folder', or 'Stack'."""
209
+ return self.metadata.get("source_type", "Image")
210
+
211
+ @property
212
+ def name(self) -> str:
213
+ """Returns the base name of the file or folder."""
214
+ path = self.metadata.get("source_path", "")
215
+ if not path:
216
+ return "Unknown"
217
+ return os.path.basename(os.path.normpath(path))
218
+
219
+ @staticmethod
220
+ def _extract_voxel_sizes(path: str) -> Dict[str, Any]:
221
+ """Read physical calibration from TIFF tags and common metadata keys."""
222
+ sizes = {"pixel_width": None, "pixel_height": None, "voxel_depth": None, "unit": None}
223
+
224
+ def _positive(value: Any) -> Optional[float]:
225
+ if value is None:
226
+ return None
227
+ if isinstance(value, (tuple, list)) and len(value) == 2:
228
+ try:
229
+ value = float(value[0]) / float(value[1])
230
+ except (TypeError, ValueError, ZeroDivisionError):
231
+ return None
232
+ try:
233
+ out = float(value)
234
+ except (TypeError, ValueError):
235
+ return None
236
+ if out <= 0 or not np.isfinite(out):
237
+ return None
238
+ return out
239
+
240
+ def _unit_scale_to_um(unit_value: Any) -> Optional[float]:
241
+ if unit_value is None:
242
+ return None
243
+ token = str(getattr(unit_value, "name", unit_value)).strip().lower()
244
+ if token in {"inch", "in", "inches"}:
245
+ return 25400.0
246
+ if token in {"centimeter", "centimetre", "cm"}:
247
+ return 10000.0
248
+ if token in {"millimeter", "millimetre", "mm"}:
249
+ return 1000.0
250
+ if token in {"resunit.inch", "resunit.centimeter", "resunit.centimetre"}:
251
+ if "inch" in token:
252
+ return 25400.0
253
+ return 10000.0
254
+ try:
255
+ token_num = int(unit_value)
256
+ except (TypeError, ValueError):
257
+ return None
258
+ if token_num == 2:
259
+ return 25400.0
260
+ if token_num == 3:
261
+ return 10000.0
262
+ return None
263
+
264
+ try:
265
+ meta = iio.immeta(path)
266
+ except Exception:
267
+ meta = {}
268
+
269
+ sizes["voxel_depth"] = (
270
+ _positive(meta.get("spacing"))
271
+ or _positive(meta.get("PhysicalSizeZ"))
272
+ )
273
+ sizes["unit"] = str(
274
+ meta.get("unit")
275
+ or meta.get("PhysicalSizeXUnit")
276
+ or meta.get("PhysicalSizeYUnit")
277
+ or meta.get("PhysicalSizeZUnit")
278
+ or ""
279
+ ).strip() or None
280
+
281
+ sizes["pixel_width"] = (
282
+ _positive(meta.get("pixel_width"))
283
+ or _positive(meta.get("PhysicalSizeX"))
284
+ )
285
+ sizes["pixel_height"] = (
286
+ _positive(meta.get("pixel_height"))
287
+ or _positive(meta.get("PhysicalSizeY"))
288
+ )
289
+
290
+ if (
291
+ (sizes["pixel_width"] is None or sizes["pixel_height"] is None)
292
+ and str(path).lower().endswith((".tif", ".tiff"))
293
+ ):
294
+ with TiffFile(path) as tif:
295
+ tags = tif.pages[0].tags
296
+ x_res = _positive(tags["XResolution"].value if "XResolution" in tags else None)
297
+ y_res = _positive(tags["YResolution"].value if "YResolution" in tags else None)
298
+ res_unit = tags["ResolutionUnit"].value if "ResolutionUnit" in tags else None
299
+ unit_scale = _unit_scale_to_um(res_unit)
300
+
301
+ if sizes["pixel_width"] is None and x_res is not None:
302
+ sizes["pixel_width"] = (1.0 / x_res) * (unit_scale or 1.0)
303
+ if sizes["pixel_height"] is None and y_res is not None:
304
+ sizes["pixel_height"] = (1.0 / y_res) * (unit_scale or 1.0)
305
+ if sizes["unit"] is None and unit_scale is not None:
306
+ sizes["unit"] = "um"
307
+
308
+ # Minimal fallback for non-TIFF metadata formats.
309
+ if sizes["pixel_width"] is None or sizes["pixel_height"] is None:
310
+ res = meta.get("resolution")
311
+ rx = None
312
+ ry = None
313
+ if isinstance(res, (tuple, list)) and len(res) >= 2:
314
+ rx = _positive(res[0])
315
+ ry = _positive(res[1])
316
+ elif isinstance(res, dict):
317
+ rx = _positive(res.get("x") or res.get("X"))
318
+ ry = _positive(res.get("y") or res.get("Y"))
319
+
320
+ unit_scale = _unit_scale_to_um(
321
+ meta.get("resolution_unit")
322
+ or meta.get("ResolutionUnit")
323
+ or meta.get("resolutionunit")
324
+ )
325
+ if sizes["pixel_width"] is None and rx is not None:
326
+ sizes["pixel_width"] = (1.0 / rx) * (unit_scale or 1.0)
327
+ if sizes["pixel_height"] is None and ry is not None:
328
+ sizes["pixel_height"] = (1.0 / ry) * (unit_scale or 1.0)
329
+ if sizes["unit"] is None and unit_scale is not None:
330
+ sizes["unit"] = "um"
331
+
332
+ return sizes
333
+
334
+ @staticmethod
335
+ def _normalize_stack(data: np.ndarray) -> List[np.ndarray]:
336
+ if data.ndim == 2:
337
+ return [data]
338
+ if data.ndim == 3:
339
+ if data.shape[2] in (3, 4):
340
+ return [data]
341
+ return [data[z] for z in range(data.shape[0])]
342
+ if data.ndim == 4:
343
+ return [data[z] for z in range(data.shape[0])]
344
+ raise ValueError("Unsupported image dimensions for batch loading.")
345
+
346
+ @classmethod
347
+ def from_path(cls, path: str) -> "ImageBatch":
348
+ data = iio.imread(path)
349
+ frames = cls._normalize_stack(data)
350
+ source_type = "Image" if len(frames) == 1 else "Stack"
351
+ filenames = [os.path.basename(path)] * len(frames)
352
+
353
+ # --- Extract physical sizes ---
354
+ voxel_sizes = cls._extract_voxel_sizes(path)
355
+
356
+ metadata = {
357
+ "source_type": source_type,
358
+ "source_path": path,
359
+ "filenames": filenames,
360
+ "z_indices": list(range(len(frames))),
361
+ **voxel_sizes # Merge the extracted sizes into the metadata dictionary
362
+ }
363
+ return cls(frames=frames, metadata=metadata)
364
+
365
+ @classmethod
366
+ def from_folder(
367
+ cls, folder: str, extensions: Optional[Iterable[str]] = None
368
+ ) -> "ImageBatch":
369
+ entries = sorted(os.listdir(folder))
370
+ ext_set = {ext.lower() for ext in extensions} if extensions else None
371
+ frames: List[np.ndarray] = []
372
+ filenames: List[str] = []
373
+
374
+ first_valid_path = None
375
+
376
+ for name in entries:
377
+ path = os.path.join(folder, name)
378
+ if not os.path.isfile(path):
379
+ continue
380
+ if ext_set is not None:
381
+ if os.path.splitext(name)[1].lower() not in ext_set:
382
+ continue
383
+ try:
384
+ data = iio.imread(path)
385
+ if first_valid_path is None:
386
+ first_valid_path = path # Save the first image to extract metadata
387
+ except Exception:
388
+ continue
389
+
390
+ image_frames = cls._normalize_stack(data)
391
+ for image_frame in image_frames:
392
+ frames.append(image_frame)
393
+ filenames.append(name)
394
+
395
+ # --- Extract physical sizes from the first image in the folder ---
396
+ voxel_sizes = {}
397
+ if first_valid_path:
398
+ voxel_sizes = cls._extract_voxel_sizes(first_valid_path)
399
+
400
+ metadata = {
401
+ "source_type": "Folder",
402
+ "source_path": folder,
403
+ "filenames": filenames,
404
+ "z_indices": list(range(len(frames))),
405
+ **voxel_sizes
406
+ }
407
+ return cls(frames=frames, metadata=metadata)
408
+
409
+ @classmethod
410
+ def from_source(
411
+ cls, path: str, extensions: Optional[Iterable[str]] = None
412
+ ) -> "ImageBatch":
413
+ if os.path.isdir(path):
414
+ return cls.from_folder(path, extensions=extensions)
415
+ if os.path.isfile(path):
416
+ return cls.from_path(path)
417
+ raise FileNotFoundError(f"Source path does not exist: {path}")
418
+
419
+ @dataclass
420
+ class BatchResult:
421
+ """Capture outputs and metadata produced by batch."""
422
+ frame_results: List[Frame]
423
+
424
+ def frame_at(self, index: int) -> Frame:
425
+ return self.frame_results[index]
426
+
427
+ def save_all(self, output_dir: str, export_config: Dict[str, Any] | None = None) -> Dict[str, Any]:
428
+ """Persist all using the configured export conventions.
429
+
430
+ Args:
431
+ output_dir (str): Filesystem location used by this operation.
432
+ export_config (Dict[str, Any] | None): Configuration values controlling runtime behavior.
433
+
434
+ Returns:
435
+ Dict[str, Any]: Mapping of computed keys and values."""
436
+ from .io_export import BatchResultExporter
437
+
438
+ exporter = BatchResultExporter(export_config=export_config)
439
+ return exporter.save_all(self, output_dir, export_config=export_config)
440
+
441
+ @dataclass
442
+ class Frame:
443
+ """Flat, stage-aware container for a single frame's processing state."""
444
+
445
+ # Identity
446
+ z_index: int = 0
447
+ frame_id: str = ""
448
+
449
+ # Stage flags
450
+ has_prediction: bool = False
451
+ has_segmentation: bool = False
452
+ has_measurements: bool = False
453
+ prediction_sig: Optional[str] = None
454
+ segmentation_sig: Optional[str] = None
455
+ measurement_sig: Optional[str] = None
456
+ error_message: Optional[str] = None
457
+
458
+ # Source and prediction buffers
459
+ orig_img: Optional[np.ndarray] = None
460
+ orig_img_scaled: Optional[np.ndarray] = None
461
+ scale_factor: float = 1.0
462
+ dt: Optional[np.ndarray] = None
463
+ dt_u8: Optional[np.ndarray] = None
464
+ dt_normalized: Optional[np.ndarray] = None
465
+ foreground_prob: Optional[np.ndarray] = None
466
+ lapl_img: Optional[np.ndarray] = None
467
+ gx: Optional[np.ndarray] = None
468
+ gy: Optional[np.ndarray] = None
469
+
470
+ # Segmentation products
471
+ labels_2d: Optional[np.ndarray] = None
472
+ # Fragments that own a label; never modified after segmentation, so snapshots share them.
473
+ fragments: Optional[List[FiberFragment]] = None
474
+
475
+ # Measurement outputs
476
+ samples_table: Optional[Any] = None
477
+ fiber_summary: Optional[Dict[str, Any]] = None
478
+ measurement_samples: Optional[Any] = None
479
+ drawing_samples: Optional[Any] = None
480
+ thickness_units: Optional[np.ndarray] = None
481
+ porosity: Optional[float] = None
482
+ pore_diams_units: Optional[np.ndarray] = None
483
+ void_mask: Optional[np.ndarray] = None
484
+ pore_dt: Optional[np.ndarray] = None
485
+ pores: Optional[Any] = None
486
+
487
+ # Images built by `render.render`, keyed by view; emptied whenever any stage is cleared.
488
+ views: Dict[str, Optional[np.ndarray]] = field(default_factory=dict, repr=False)
489
+
490
+ @classmethod
491
+ def empty(
492
+ cls,
493
+ *,
494
+ frame_id: str = "",
495
+ z_index: int = 0,
496
+ orig_img: Optional[np.ndarray] = None,
497
+ ) -> "Frame":
498
+ return cls(frame_id=str(frame_id), z_index=int(z_index), orig_img=orig_img)
499
+
500
+ def clear_prediction(self) -> None:
501
+ self.has_prediction = False
502
+ self.dt = None
503
+ self.dt_u8 = None
504
+ self.dt_normalized = None
505
+ self.foreground_prob = None
506
+ self.lapl_img = None
507
+ self.gx = None
508
+ self.gy = None
509
+ self.orig_img_scaled = None
510
+ self.scale_factor = 1.0
511
+ self.prediction_sig = None
512
+ self.error_message = None
513
+ self.clear_segmentation()
514
+
515
+ def clear_segmentation(self) -> None:
516
+ self.has_segmentation = False
517
+ self.labels_2d = None
518
+ self.fragments = None
519
+ self.segmentation_sig = None
520
+ self.clear_measurements()
521
+
522
+ def clear_measurements(self) -> None:
523
+ self.has_measurements = False
524
+ self.samples_table = None
525
+ self.fiber_summary = None
526
+ self.measurement_samples = None
527
+ self.drawing_samples = None
528
+ self.thickness_units = None
529
+ self.porosity = None
530
+ self.pore_diams_units = None
531
+ self.void_mask = None
532
+ self.pore_dt = None
533
+ self.pores = None
534
+ self.measurement_sig = None
535
+ self.views = {}
536
+
537
+
538
+ def set_prediction_outputs(
539
+ self,
540
+ *,
541
+ dt: Optional[np.ndarray],
542
+ gx: Optional[np.ndarray],
543
+ gy: Optional[np.ndarray],
544
+ dt_u8: Optional[np.ndarray],
545
+ dt_normalized: Optional[np.ndarray],
546
+ foreground_prob: Optional[np.ndarray],
547
+ lapl_img: Optional[np.ndarray],
548
+ orig_img_scaled: Optional[np.ndarray],
549
+ scale_factor: float,
550
+ ) -> None:
551
+ self.dt = dt
552
+ self.gx = gx
553
+ self.gy = gy
554
+ self.dt_u8 = dt_u8
555
+ self.dt_normalized = dt_normalized
556
+ self.foreground_prob = foreground_prob
557
+ self.lapl_img = lapl_img
558
+ self.orig_img_scaled = orig_img_scaled
559
+ self.scale_factor = float(scale_factor)
560
+ self.has_prediction = self.dt is not None
561
+ self.error_message = None
562
+ self.clear_segmentation()
563
+
564
+ def set_segmentation_outputs(
565
+ self,
566
+ *,
567
+ labels_2d: np.ndarray,
568
+ fragments: List[FiberFragment],
569
+ ) -> None:
570
+ self.labels_2d = labels_2d
571
+ self.fragments = fragments
572
+ self.has_segmentation = True
573
+ self.error_message = None
574
+ self.clear_measurements()
575
+
576
+ def set_measurement_outputs(
577
+ self,
578
+ *,
579
+ samples_table: Optional[Any],
580
+ fiber_summary: Optional[Dict[str, Any]],
581
+ measurement_samples: Optional[Any],
582
+ drawing_samples: Optional[Any],
583
+ thickness_units: Optional[np.ndarray],
584
+ porosity: Optional[float],
585
+ pore_diams_units: Optional[np.ndarray],
586
+ void_mask: Optional[np.ndarray],
587
+ pore_dt: Optional[np.ndarray],
588
+ pores: Optional[Any],
589
+ ) -> None:
590
+ """Update measurement outputs and synchronize dependent runtime state."""
591
+ self.samples_table = samples_table
592
+ self.fiber_summary = fiber_summary
593
+ self.measurement_samples = measurement_samples
594
+ self.drawing_samples = drawing_samples
595
+ self.thickness_units = thickness_units
596
+ self.porosity = porosity
597
+ self.pore_diams_units = pore_diams_units
598
+ self.void_mask = void_mask
599
+ self.pore_dt = pore_dt
600
+ self.pores = pores
601
+ self.has_measurements = True
602
+ self.error_message = None
603
+
604
+ def fail(self, message: str) -> None:
605
+ self.error_message = str(message)
606
+
607
+ def snapshot(
608
+ self,
609
+ *,
610
+ frame_id: Optional[str] = None,
611
+ z_index: Optional[int] = None,
612
+ ) -> "Frame":
613
+ clone: Frame = copy(self)
614
+ def _clone_array(value: Any) -> Any:
615
+ if isinstance(value, np.ndarray):
616
+ return value.copy()
617
+ return value
618
+
619
+ clone.dt = _clone_array(clone.dt)
620
+ clone.dt_u8 = _clone_array(clone.dt_u8)
621
+ clone.dt_normalized = _clone_array(clone.dt_normalized)
622
+ clone.foreground_prob = _clone_array(clone.foreground_prob)
623
+ clone.lapl_img = _clone_array(clone.lapl_img)
624
+ clone.gx = _clone_array(clone.gx)
625
+ clone.gy = _clone_array(clone.gy)
626
+
627
+ clone.labels_2d = _clone_array(clone.labels_2d)
628
+
629
+ clone.samples_table = _clone_array(clone.samples_table)
630
+ clone.thickness_units = _clone_array(clone.thickness_units)
631
+ clone.pore_diams_units = _clone_array(clone.pore_diams_units)
632
+ clone.void_mask = _clone_array(clone.void_mask)
633
+ clone.pore_dt = _clone_array(clone.pore_dt)
634
+
635
+ # Cached images are never modified in place, so the clone may share them.
636
+ clone.views = dict(clone.views)
637
+ if clone.fiber_summary is not None:
638
+ clone.fiber_summary = dict(clone.fiber_summary)
639
+ if frame_id is not None:
640
+ clone.frame_id = str(frame_id)
641
+ if z_index is not None:
642
+ clone.z_index = int(z_index)
643
+ return clone
644
+
645
+
646
+ @dataclass
647
+ class FiberFragment:
648
+ """Unified 2D fragment carrying both segmentation and measurement centerlines."""
649
+
650
+ fragment_id: int
651
+ segment_centerlines_xy: list[np.ndarray]
652
+ segment_radii: Optional[list[np.ndarray]] = None
653
+ parent_fiber_id: int = -1
654
+ measurement_centerlines_xy: list[np.ndarray] = field(default_factory=list)
655
+ total_measurement_centerline_length_px: float = 0.0
656
+ grad_quality_score: float = float("nan")
657
+
658
+ @staticmethod
659
+ def _normalize_centerline(points_raw: np.ndarray, label: str) -> np.ndarray:
660
+ points_xy = np.asarray(points_raw, dtype=np.float32)
661
+ if points_xy.ndim != 2 or points_xy.shape[1] != 2:
662
+ raise ValueError(f"{label} must be an array of shape (N, 2).")
663
+ if points_xy.shape[0] < 2:
664
+ raise ValueError(f"{label} must contain at least two points.")
665
+ return points_xy
666
+
667
+ @staticmethod
668
+ def _normalize_radii(radii_raw: Optional[np.ndarray], n_points: int, label: str) -> np.ndarray:
669
+ if radii_raw is None:
670
+ return np.zeros(n_points, dtype=np.float32)
671
+ radii = np.asarray(radii_raw, dtype=np.float32).reshape(-1)
672
+ if radii.shape[0] != n_points:
673
+ raise ValueError(f"{label} length must match centerline length.")
674
+ return radii
675
+
676
+ @staticmethod
677
+ def _centerline_length(points_xy: np.ndarray) -> float:
678
+ if points_xy.shape[0] < 2:
679
+ return 0.0
680
+ return float(np.linalg.norm(np.diff(points_xy, axis=0), axis=1).sum())
681
+
682
+ def recompute_total_measurement_centerline_length_px(self) -> float:
683
+ self.total_measurement_centerline_length_px = float(
684
+ sum(self._centerline_length(points_xy) for points_xy in self.measurement_centerlines_xy)
685
+ )
686
+ return self.total_measurement_centerline_length_px
687
+
688
+ def __post_init__(self) -> None:
689
+ if not self.segment_centerlines_xy:
690
+ raise ValueError("FiberFragment must contain at least one segmentation centerline.")
691
+
692
+ centerlines_xy = [
693
+ self._normalize_centerline(points_raw, "Segmentation centerline")
694
+ for points_raw in self.segment_centerlines_xy
695
+ ]
696
+ if not self.segment_radii:
697
+ centerlines_radii = [
698
+ np.zeros(points_xy.shape[0], dtype=np.float32) for points_xy in centerlines_xy
699
+ ]
700
+ else:
701
+ if len(self.segment_radii) != len(centerlines_xy):
702
+ raise ValueError("segment_radii length must match segment_centerlines_xy length.")
703
+ centerlines_radii = [
704
+ self._normalize_radii(radii_raw, points_xy.shape[0], "Segmentation radii")
705
+ for points_xy, radii_raw in zip(centerlines_xy, self.segment_radii)
706
+ ]
707
+
708
+ pairs = list(zip(centerlines_xy, centerlines_radii))
709
+ pairs.sort(key=lambda pair: self._centerline_length(pair[0]), reverse=True)
710
+ self.segment_centerlines_xy = [points_xy for points_xy, _ in pairs]
711
+ self.segment_radii = [radii for _, radii in pairs]
712
+
713
+ self.measurement_centerlines_xy = [
714
+ self._normalize_centerline(points_raw, "Measurement centerline")
715
+ for points_raw in (self.measurement_centerlines_xy or [])
716
+ ]
717
+ self.recompute_total_measurement_centerline_length_px()
718
+
719
+ self.fragment_id = int(self.fragment_id)
720
+ self.parent_fiber_id = int(self.parent_fiber_id)
721
+
722
+ @property
723
+ def has_measurement_centerline(self) -> bool:
724
+ return bool(self.measurement_centerlines_xy)
src/fiberpose/gui/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyQt desktop interface: ``fiberpose --gui``.
2
+
3
+ Importing this package needs the ``gui`` extra (PyQt6, pyqtgraph).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import sys
9
+
10
+ from PyQt6.QtGui import QColor, QIcon, QPalette
11
+ from PyQt6.QtWidgets import QApplication
12
+
13
+ from ..paths import APP_ICON_PATH
14
+
15
+ __all__ = ["launch"]
16
+
17
+
18
+ def launch(config_path: str) -> int:
19
+ """Open the main window and run the Qt event loop; returns its exit code."""
20
+ from .main_window import MainWindow
21
+
22
+ app = QApplication(sys.argv)
23
+ app.setWindowIcon(QIcon(str(APP_ICON_PATH)))
24
+ app.setStyle("Fusion")
25
+
26
+ dark, text, white = QColor(45, 45, 45), QColor(220, 220, 220), QColor(255, 255, 255)
27
+ palette = QPalette()
28
+ for role, color in {
29
+ "Window": dark,
30
+ "WindowText": text,
31
+ "Base": QColor(30, 30, 30),
32
+ "AlternateBase": dark.darker(),
33
+ "ToolTipBase": white,
34
+ "ToolTipText": text,
35
+ "Text": text,
36
+ "Button": dark,
37
+ "ButtonText": text,
38
+ "BrightText": QColor(255, 0, 0),
39
+ "Highlight": QColor(42, 130, 218),
40
+ "HighlightedText": white,
41
+ }.items():
42
+ palette.setColor(QPalette.ColorRole[role], color)
43
+ app.setPalette(palette)
44
+
45
+ font = app.font()
46
+ font.setPointSize(12)
47
+ app.setFont(font)
48
+ win = MainWindow(config_path=config_path)
49
+ win.show()
50
+ return int(app.exec())
src/fiberpose/gui/main_window.py ADDED
@@ -0,0 +1,1795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Main Qt window coordinating image IO, analysis workflows, and visualization state."""
2
+
3
+ import os
4
+ from datetime import datetime
5
+ from typing import Any, Dict
6
+ import numpy as np
7
+
8
+ from PyQt6 import QtGui, QtWidgets
9
+ from PyQt6.QtCore import Qt, QEvent, QTimer, QPoint, QLineF, QSize
10
+ from PyQt6.QtWidgets import (
11
+ QMainWindow,
12
+ QFileDialog,
13
+ QGraphicsScene,
14
+ QGraphicsPixmapItem,
15
+ QGraphicsEllipseItem,
16
+ QGraphicsItem,
17
+ QToolButton,
18
+ QMessageBox,
19
+ )
20
+ from PyQt6.uic import loadUi
21
+
22
+ import pyqtgraph as pg
23
+
24
+ import logging
25
+ logger = logging.getLogger(__name__)
26
+ logging.basicConfig(level=logging.INFO)
27
+
28
+ from .support import (
29
+ PlotProfileDialog,
30
+ ConfigEditorDialog,
31
+ )
32
+ from ..ml import onnx_cuda_available
33
+ from ..domain import BatchResult, Frame, ImageBatch, AppConfig, SampleProperties
34
+ from ..render import render
35
+ from ..utils import to_uint8_for_view
36
+ from ..pipeline import PipelineController, PipelineOutcome
37
+ from .support import UiConfigBinder
38
+ from ..pipeline import BatchService, BatchCallbacks
39
+ from ..io_export import ExportService
40
+ from .support import ScalebarTool, ProfileTool
41
+ from ..paths import DEFAULT_UI_PATH, EXAMPLE_IMAGE_PATH, default_config_path
42
+ from ..models import DEFAULT_MODEL, discover_models, models_dir, normalize_model_entry, resolve_model_path
43
+
44
+ # ------------------- MainWindow -------------------
45
+
46
+
47
+ class MainWindow(QMainWindow):
48
+ """Main Fiberpose window: loads sources, runs the pipeline, and shows views, plots, and exports."""
49
+ def __init__(self, ui_path: str = str(DEFAULT_UI_PATH), config_path: str | None = None):
50
+ super().__init__()
51
+ loadUi(ui_path, self)
52
+ self.setWindowTitle("Fiberpose — fiber segmentation and analysis tool")
53
+ self.config_filepath = os.path.abspath(config_path or default_config_path())
54
+
55
+ # Load config and sync to UI
56
+ self.config = AppConfig.load_from_json(self.config_filepath)
57
+ self.config.model_path = normalize_model_entry(self.config.model_path)
58
+ self.sample_props = SampleProperties.defaults()
59
+ self._ui_binder = UiConfigBinder()
60
+ self._scalebar_tool = ScalebarTool()
61
+ self._profile_tool = ProfileTool()
62
+ self._pipeline_service = PipelineController()
63
+ self._batch_service = BatchService()
64
+ self.sync_config_to_ui()
65
+ self.sync_sample_properties_to_ui()
66
+
67
+ # Enable real-time syncing!
68
+ self._connect_config_signals()
69
+
70
+ # Scene and view setup
71
+ self._scene = QGraphicsScene(self.graphicsView)
72
+ self.graphicsView.setScene(self._scene)
73
+ self._pixitem = QGraphicsPixmapItem()
74
+ self._scene.addItem(self._pixitem)
75
+ self._install_drag_drop()
76
+
77
+ self.graphicsView.setRenderHints(
78
+ QtGui.QPainter.RenderHint.Antialiasing |
79
+ QtGui.QPainter.RenderHint.SmoothPixmapTransform
80
+ )
81
+ self.graphicsView.setViewportUpdateMode(QtWidgets.QGraphicsView.ViewportUpdateMode.BoundingRectViewportUpdate)
82
+ self.graphicsView.setTransformationAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorViewCenter)
83
+ self.graphicsView.setResizeAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorViewCenter)
84
+
85
+ # Working dir & runtime state setup
86
+ self.working_dir = os.path.dirname(ui_path)
87
+ self.current_frame: Frame = Frame.empty()
88
+ self.current_image_name: str | None = None
89
+ self._pixmap_source_shape: tuple[int, int] | None = None
90
+
91
+ # View/zoom state
92
+ self._zoom_mode_active: bool = False
93
+ self._base_scale: float = 1.0
94
+ self._min_zoom_factor: float = 0.2
95
+ self._max_zoom_factor: float = 5.0
96
+
97
+ self.btn_reset_view = QToolButton(self.graphicsView.viewport())
98
+ icon = self.style().standardIcon(QtWidgets.QStyle.StandardPixmap.SP_TitleBarNormalButton)
99
+ self.btn_reset_view.setIcon(icon)
100
+ self.btn_reset_view.setIconSize(QSize(16, 16))
101
+ self.btn_reset_view.setCursor(Qt.CursorShape.ArrowCursor)
102
+ self.btn_reset_view.setToolTip("Reset zoom to fit the image")
103
+ self.btn_reset_view.setAutoRaise(True)
104
+ self.btn_reset_view.setFocusPolicy(Qt.FocusPolicy.NoFocus)
105
+ self.btn_reset_view.clicked.connect(self.reset_zoom)
106
+ self.btn_reset_view.hide()
107
+
108
+ # Batch mode state
109
+ self._suppress_batch_dialogs: bool = False
110
+ self._image_batch: ImageBatch | None = None
111
+ self._batch_result: BatchResult | None = None
112
+ self._current_z_index: int = 0
113
+ self.z_scroll.setEnabled(False)
114
+ self.z_scroll.valueChanged.connect(self._on_z_scroll_changed)
115
+ self._update_slice_label()
116
+
117
+ # Profile plotting tool state
118
+ self._profile_line_item: QGraphicsItem | None = None
119
+ self._profile_point_items: list[QGraphicsItem] = []
120
+ self._profile_dialog: PlotProfileDialog | None = None
121
+
122
+ # Menu & actions
123
+ self.action_load_image.triggered.connect(self.load_original)
124
+ self.action_save_masks_predictions.triggered.connect(self.save_predictions)
125
+ self.action_save_measurements.triggered.connect(self.save_measurements)
126
+ self.action_edit_config.triggered.connect(self._on_edit_config)
127
+ self.action_load_config.triggered.connect(self._on_load_config)
128
+
129
+ self.btn_load_image.clicked.connect(self.load_original)
130
+ self.btn_segment.clicked.connect(self.segment)
131
+ self.btn_measure.clicked.connect(self.analyze_fibers)
132
+ self.btn_set_scalebar.clicked.connect(self._on_set_scalebar_clicked)
133
+ self.btn_plot_profile.clicked.connect(self._on_plot_profile_clicked)
134
+ self.btn_export_results.clicked.connect(self._on_export_results_clicked)
135
+ self.btn_save_screenshot.clicked.connect(self._on_save_screenshot_clicked)
136
+ self.btn_export_csv.clicked.connect(self.save_measurements)
137
+ self.action_batch_processing.triggered.connect(self._on_batch_processing)
138
+
139
+ # Collapsible "Advanced" sections start folded.
140
+ for button, panel in (
141
+ (self.btn_segmentation_advanced, self.widget_segmentation_advanced),
142
+ (self.btn_measurement_advanced, self.widget_measurement_advanced),
143
+ (self.btn_export_advanced, self.widget_export_advanced),
144
+ ):
145
+ panel.setVisible(False)
146
+ button.toggled.connect(
147
+ lambda checked, button=button, panel=panel: self._toggle_advanced(button, panel, checked)
148
+ )
149
+
150
+ self.cb_view.currentIndexChanged.connect(self.refresh_view)
151
+ self.cb_view.setMinimumHeight(self.btn_load_image.sizeHint().height())
152
+ # Units belong to the plots: hidden with them, but keep the row's space so plots don't shift.
153
+ for widget in (self.label_units, self.cb_units):
154
+ policy = widget.sizePolicy()
155
+ policy.setRetainSizeWhenHidden(True)
156
+ widget.setSizePolicy(policy)
157
+ self._clear_results()
158
+
159
+ # Set default model
160
+ self._init_model_selector()
161
+
162
+ # Disable saves initially.
163
+ self._refresh_save_actions()
164
+
165
+ self.resize(1100, 800)
166
+ self.refresh_view()
167
+
168
+ # Delay loading default image until the UI is fully shown.
169
+ QTimer.singleShot(0, self.load_default_image)
170
+
171
+ # Use CUDA by default when available; the model loads on the first prediction.
172
+ self.chb_usegpu.setChecked(onnx_cuda_available())
173
+ self._pipeline_service.set_model(
174
+ self._current_model_path() or str(models_dir() / DEFAULT_MODEL),
175
+ "cuda" if self.chb_usegpu.isChecked() else "cpu",
176
+ )
177
+
178
+ # react to checkbox changes at runtime
179
+ self.chb_usegpu.toggled.connect(self._on_usegpu_toggled)
180
+ self.chb_invert.toggled.connect(self._on_invert_toggled)
181
+
182
+ # Connect toggled signals of rb_show_diam and rb_show_direct to update overlay
183
+ self.rb_show_diam.toggled.connect(self._render_vector_overlay)
184
+ self.rb_show_direct.toggled.connect(self._render_vector_overlay)
185
+ self.rb_show_pores.toggled.connect(self._render_vector_overlay)
186
+
187
+ def closeEvent(self, event: QtGui.QCloseEvent):
188
+ """Triggered when the user closes the main window."""
189
+ # Grab the latest state from the UI
190
+ self.sync_ui_to_config()
191
+ self.sync_ui_to_sample_properties()
192
+ # Save it to disk
193
+ cfg_dir = os.path.dirname(self.config_filepath)
194
+ if cfg_dir:
195
+ os.makedirs(cfg_dir, exist_ok=True)
196
+ self.config.save_to_json(self.config_filepath)
197
+ super().closeEvent(event)
198
+
199
+ def _connect_config_signals(self):
200
+ """Connects UI widget signals to update the config immediately on change."""
201
+
202
+ # Combo boxes (Dropdowns)
203
+ self.cb_model.currentIndexChanged.connect(self.sync_ui_to_config)
204
+ self.cb_scale.currentIndexChanged.connect(self.sync_ui_to_config)
205
+ self.cb_units.currentTextChanged.connect(self._on_units_changed)
206
+
207
+ # Checkboxes and Radio Buttons
208
+ self.chb_usegpu.toggled.connect(self.sync_ui_to_config)
209
+ self.chb_strict.toggled.connect(self.sync_ui_to_config)
210
+
211
+ self.rb_watershed.toggled.connect(self.sync_ui_to_config)
212
+ self.rb_ridge.toggled.connect(self.sync_ui_to_config)
213
+
214
+ # Spinboxes
215
+ self.sp_grad_magnitude_threshold.valueChanged.connect(self.sync_ui_to_config)
216
+
217
+ # Line Edits (Text boxes)
218
+ # Note: We use `editingFinished` instead of `textChanged`.
219
+ self.le_pixelsize.editingFinished.connect(self.sync_ui_to_sample_properties)
220
+ self.le_voxeldepth.editingFinished.connect(self.sync_ui_to_sample_properties)
221
+
222
+ # Export options live in config.save_options, not in the binder.
223
+ for checkbox in (*self._export_checkboxes().values(), self.chb_write_manifest):
224
+ checkbox.toggled.connect(self._sync_ui_to_save_options)
225
+ self.cb_image_format.currentIndexChanged.connect(self._sync_ui_to_save_options)
226
+ self.cb_collision.currentIndexChanged.connect(self._sync_ui_to_save_options)
227
+
228
+ def _init_model_selector(self) -> None:
229
+ models = self._discover_model_files()
230
+ configured_entry = normalize_model_entry(self.config.model_path)
231
+ rel_default = DEFAULT_MODEL
232
+ self.cb_model.blockSignals(True)
233
+ self.cb_model.clear()
234
+ if models:
235
+ for rel_path in models:
236
+ self.cb_model.addItem(rel_path)
237
+ else:
238
+ self.cb_model.addItem(rel_default)
239
+
240
+ # Keep explicit config choice first; fallback to default, then first available model.
241
+ if configured_entry:
242
+ if self.cb_model.findText(configured_entry) < 0:
243
+ self.cb_model.addItem(configured_entry)
244
+ configured_index = self.cb_model.findText(configured_entry)
245
+ if configured_index >= 0:
246
+ self.cb_model.setCurrentIndex(configured_index)
247
+ else:
248
+ self.cb_model.setCurrentIndex(0)
249
+ else:
250
+ default_index = self.cb_model.findText(rel_default)
251
+ if default_index >= 0:
252
+ self.cb_model.setCurrentIndex(default_index)
253
+ else:
254
+ self.cb_model.setCurrentIndex(0)
255
+ self.cb_model.blockSignals(False)
256
+ self.cb_model.currentIndexChanged.connect(self._on_model_selection_changed)
257
+
258
+ def _on_model_selection_changed(self, index: int):
259
+ """Handle model selection changed and propagate UI state updates.
260
+
261
+ Args:
262
+ index (int): Zero-based position used to select an item."""
263
+ new_path = self._current_model_path()
264
+ if not new_path:
265
+ return
266
+ if not os.path.isfile(new_path):
267
+ QMessageBox.warning(
268
+ self,
269
+ "Model missing",
270
+ f"Selected model was not found:\n{new_path}",
271
+ )
272
+ return
273
+ if new_path == self._pipeline_service.model_path:
274
+ return
275
+ self._pipeline_service.set_model(new_path, self._pipeline_service.device)
276
+ self._invalidate_prediction()
277
+
278
+ def _discover_model_files(self) -> list[str]:
279
+ return discover_models()
280
+
281
+ def _current_model_path(self) -> str | None:
282
+ entry = self.cb_model.currentText().strip()
283
+ if not entry:
284
+ return None
285
+ try:
286
+ return resolve_model_path(entry)
287
+ except Exception as exc:
288
+ logger.warning("Could not download model %s: %s", entry, exc)
289
+ return str(models_dir() / normalize_model_entry(entry))
290
+
291
+
292
+ # ------------------- Display helpers -------------------
293
+
294
+ def _set_pixmap_from_array(self, img: np.ndarray | None):
295
+ prev_shape = self._pixmap_source_shape
296
+ if img is None:
297
+ self._pixitem.setPixmap(QtGui.QPixmap())
298
+ self._pixmap_source_shape = None
299
+ self._zoom_mode_active = False
300
+ self._base_scale = 1.0
301
+ self.btn_reset_view.hide()
302
+ self._remove_profile_items()
303
+ return
304
+ self._pixmap_source_shape = img.shape[:2]
305
+ qimg = self._numpy_to_qimage(img)
306
+ pix = QtGui.QPixmap.fromImage(qimg)
307
+ # Scale pixmap if it is smaller than the viewport
308
+ view_size = self.graphicsView.viewport().size()
309
+ if pix.width() < view_size.width() or pix.height() < view_size.height():
310
+ pix = pix.scaled(view_size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
311
+ self._pixitem.setPixmap(pix)
312
+ self._scene.setSceneRect(self._pixitem.boundingRect())
313
+ force_fit = (not self._zoom_mode_active) or (prev_shape != self._pixmap_source_shape)
314
+ self._fit_view_to_pixmap(force=force_fit)
315
+ self._update_reset_button_position()
316
+
317
+ def resizeEvent(self, event):
318
+ super().resizeEvent(event)
319
+ self._update_reset_button_position()
320
+ if not self._zoom_mode_active:
321
+ self._fit_view_to_pixmap(force=True)
322
+
323
+ @staticmethod
324
+ def _numpy_to_qimage(img: np.ndarray) -> QtGui.QImage:
325
+ if img.ndim == 2:
326
+ u8 = np.ascontiguousarray(img.astype(np.uint8, copy=False))
327
+ h, w = u8.shape
328
+ qimg = QtGui.QImage(u8.data, w, h, w, QtGui.QImage.Format.Format_Grayscale8)
329
+ qimg.ndarray_ref = u8
330
+ return qimg
331
+ elif img.ndim == 3 and img.shape[2] == 3:
332
+ u8 = np.ascontiguousarray(img.astype(np.uint8, copy=False))
333
+ h, w, c = u8.shape
334
+ qimg = QtGui.QImage(u8.data, w, h, c*w, QtGui.QImage.Format.Format_RGB888)
335
+ qimg.ndarray_ref = u8
336
+ return qimg
337
+ else:
338
+ u8 = to_uint8_for_view(img)
339
+ return MainWindow._numpy_to_qimage(u8)
340
+
341
+
342
+
343
+ def _fit_view_to_pixmap(self, force: bool = False):
344
+ pm = self._pixitem.pixmap()
345
+ if pm is not None and not pm.isNull():
346
+ if self._zoom_mode_active and not force:
347
+ return
348
+ self.graphicsView.resetTransform()
349
+ self.graphicsView.fitInView(self._pixitem, Qt.AspectRatioMode.KeepAspectRatio)
350
+ self.graphicsView.centerOn(self._pixitem)
351
+ scale = self.graphicsView.transform().m11()
352
+ self._base_scale = scale if scale not in (0.0, None) else 1.0
353
+ self._zoom_mode_active = False
354
+ self._update_reset_button_visibility()
355
+
356
+ def _invalidate_prediction(self) -> None:
357
+ self.current_frame.clear_prediction()
358
+ self._invalidate_measurements()
359
+
360
+ def _invalidate_segmentation(self) -> None:
361
+ self.current_frame.clear_segmentation()
362
+ self._invalidate_measurements()
363
+
364
+ def _invalidate_measurements(self) -> None:
365
+ self.current_frame.clear_measurements()
366
+ self._clear_results()
367
+ self._refresh_save_actions()
368
+
369
+ def _ensure_prediction_ready(self) -> bool:
370
+ self.sync_ui_to_config()
371
+ outcome = self._pipeline_service.ensure_prediction(
372
+ self.current_frame,
373
+ self.config,
374
+ invert_input=bool(self.chb_invert.isChecked()),
375
+ )
376
+ return self._handle_pipeline_outcome(outcome)
377
+
378
+ def _ensure_segmentation_ready(self) -> bool:
379
+ self.sync_ui_to_config()
380
+ outcome = self._pipeline_service.ensure_segmentation(
381
+ self.current_frame,
382
+ self.config,
383
+ invert_input=bool(self.chb_invert.isChecked()),
384
+ )
385
+ return self._handle_pipeline_outcome(outcome)
386
+
387
+ def _ensure_measurements_ready(self) -> bool:
388
+ self.sync_ui_to_config()
389
+ self.sync_ui_to_sample_properties()
390
+ outcome = self._pipeline_service.ensure_measurements(
391
+ self.current_frame,
392
+ self.config,
393
+ self.sample_props,
394
+ invert_input=bool(self.chb_invert.isChecked()),
395
+ )
396
+ if not self._handle_pipeline_outcome(outcome):
397
+ return False
398
+ summary = self.current_frame.fiber_summary or {}
399
+ units_label = str(summary.get("units", "px"))
400
+ info_text = (
401
+ f"Diam Mean: {summary.get('diam_mean', float('nan')):.2f} {units_label}\n"
402
+ f"Diam SD: {summary.get('diam_sd', float('nan')):.2f} {units_label}\n"
403
+ f"Diam Mode: {summary.get('diam_mode', float('nan')):.2f} {units_label}\n"
404
+ f"Diam Median: {summary.get('diam_median', float('nan')):.2f} {units_label}\n"
405
+ f"Orientation Index: {summary.get('orientation_index', float('nan')):.2f}\n"
406
+ f"Angle Mean: {summary.get('mean_angle_deg', float('nan')):.2f} deg\n"
407
+ f"Angle SD: {summary.get('std_angle_deg', float('nan')):.2f} deg\n"
408
+ f"Porosity: {summary.get('porosity', float('nan'))*100:.1f} %\n"
409
+ f"Centerline Fragments: {int(summary.get('fragments_with_centerlines', 0))}"
410
+ )
411
+ self.text_edit2.setPlainText(info_text)
412
+ self._update_distributions_pyqtgraph(units_label)
413
+ return True
414
+
415
+ def _show_info(self, title: str, message: str):
416
+ if self._suppress_batch_dialogs:
417
+ logger.info("[Batch] %s: %s", title, message)
418
+ else:
419
+ QtWidgets.QMessageBox.information(self, title, message)
420
+
421
+ def _handle_pipeline_outcome(self, outcome: PipelineOutcome) -> bool:
422
+ if outcome.ok:
423
+ return True
424
+ if outcome.error_title and outcome.error_message:
425
+ self._show_error(outcome.error_title, outcome.error_message)
426
+ elif outcome.info_title and outcome.info_message:
427
+ self._show_info(outcome.info_title, outcome.info_message)
428
+ return False
429
+
430
+ def _show_warning(self, title: str, message: str):
431
+ if self._suppress_batch_dialogs:
432
+ logger.warning("[Batch] %s: %s", title, message)
433
+ else:
434
+ QtWidgets.QMessageBox.warning(self, title, message)
435
+
436
+ def _show_error(self, title: str, message: str):
437
+ if self._suppress_batch_dialogs:
438
+ logger.error("[Batch] %s: %s", title, message)
439
+ else:
440
+ QtWidgets.QMessageBox.critical(self, title, message)
441
+
442
+ def _apply_runtime_after_config_change(self) -> None:
443
+ model_entry = normalize_model_entry(self.config.model_path)
444
+ self.config.model_path = model_entry
445
+ if model_entry and self.cb_model.findText(model_entry) < 0:
446
+ self.cb_model.addItem(model_entry)
447
+
448
+ self.sync_config_to_ui()
449
+ self.sync_ui_to_config()
450
+
451
+ self._on_model_selection_changed(self.cb_model.currentIndex())
452
+ self._on_usegpu_toggled(self.chb_usegpu.isChecked())
453
+
454
+ def _load_config_from_path(self, path: str) -> bool:
455
+ selected_path = os.path.abspath(path)
456
+ try:
457
+ self.config = AppConfig.load_from_json(selected_path)
458
+ except Exception as exc:
459
+ self._show_error("Load config failed", str(exc))
460
+ return False
461
+
462
+ self.config_filepath = selected_path
463
+ self._apply_runtime_after_config_change()
464
+ return True
465
+
466
+ def _on_load_config(self):
467
+ start_dir = os.path.dirname(self.config_filepath) if self.config_filepath else os.path.expanduser("~")
468
+ selected_path, _ = QFileDialog.getOpenFileName(
469
+ self,
470
+ "Select config file",
471
+ start_dir,
472
+ "JSON Files (*.json);;All Files (*)",
473
+ )
474
+ if not selected_path:
475
+ return
476
+ if self._load_config_from_path(selected_path):
477
+ self.statusbar.showMessage(f"Config loaded: {self.config_filepath}", 5000)
478
+
479
+ def _on_edit_config(self):
480
+ dialog = ConfigEditorDialog(self.config, self.config_filepath, self)
481
+ if dialog.exec() != QtWidgets.QDialog.DialogCode.Accepted:
482
+ return
483
+
484
+ self.config = dialog.result_config()
485
+ self.config_filepath = dialog.result_config_path()
486
+ self._apply_runtime_after_config_change()
487
+ self.statusbar.showMessage(f"Config updated: {self.config_filepath}", 5000)
488
+
489
+ def _export_checkboxes(self) -> Dict[str, QtWidgets.QCheckBox]:
490
+ """Export-panel checkboxes keyed by their save_options artifact name."""
491
+ return {key: getattr(self, f"chb_export_{key}") for key in self._save_artifact_keys()}
492
+
493
+ def _sync_save_options_to_ui(self) -> None:
494
+ """Show config.save_options in the export panel without echoing back into the config."""
495
+ options = self._normalize_save_options(self.config.save_options)
496
+ widgets = (
497
+ *self._export_checkboxes().values(),
498
+ self.chb_write_manifest,
499
+ self.cb_image_format,
500
+ self.cb_collision,
501
+ )
502
+ for widget in widgets:
503
+ widget.blockSignals(True)
504
+ try:
505
+ for key, checkbox in self._export_checkboxes().items():
506
+ checkbox.setChecked(bool(options[key]))
507
+ self.chb_write_manifest.setChecked(bool(options["write_manifest"]))
508
+ self.cb_image_format.setCurrentIndex(max(0, self.cb_image_format.findText(options["image_format"])))
509
+ self.cb_collision.setCurrentIndex(max(0, self.cb_collision.findText(options["collision"])))
510
+ finally:
511
+ for widget in widgets:
512
+ widget.blockSignals(False)
513
+
514
+ def _sync_ui_to_save_options(self, *_args) -> None:
515
+ """Store the export panel state in config.save_options."""
516
+ options: Dict[str, Any] = {
517
+ key: checkbox.isChecked() for key, checkbox in self._export_checkboxes().items()
518
+ }
519
+ options["image_format"] = self.cb_image_format.currentText()
520
+ options["collision"] = self.cb_collision.currentText()
521
+ options["write_manifest"] = self.chb_write_manifest.isChecked()
522
+ self.config.save_options = self._normalize_save_options(options)
523
+
524
+
525
+ # ------------------- Drag & drop -------------------
526
+
527
+ def _install_drag_drop(self):
528
+ v = self.graphicsView
529
+ v.setAcceptDrops(True)
530
+ v.viewport().setAcceptDrops(True)
531
+ v.viewport().installEventFilter(self)
532
+
533
+ def eventFilter(self, obj, event):
534
+ if obj is self.graphicsView.viewport():
535
+ et = event.type()
536
+ if et == QEvent.Type.Resize:
537
+ self._update_reset_button_position()
538
+ elif et == QEvent.Type.Wheel:
539
+ if isinstance(event, QtGui.QWheelEvent):
540
+ if self._handle_wheel_zoom(event):
541
+ return True
542
+ if self._scalebar_tool.pending and et == QEvent.Type.MouseButtonPress:
543
+ if isinstance(event, QtGui.QMouseEvent):
544
+ self._handle_scalebar_mouse(event)
545
+ return True
546
+ if self._profile_tool.active and et == QEvent.Type.MouseButtonPress:
547
+ if isinstance(event, QtGui.QMouseEvent):
548
+ self._handle_profile_mouse(event)
549
+ return True
550
+ if et == QEvent.Type.ContextMenu:
551
+ if isinstance(event, QtGui.QContextMenuEvent):
552
+ self._show_view_context_menu(event.globalPos())
553
+ return True
554
+ if et in (QEvent.Type.DragEnter, QEvent.Type.DragMove):
555
+ md = event.mimeData()
556
+ if md and md.hasUrls() and self._urls_are_loadable(md.urls()):
557
+ event.acceptProposedAction()
558
+ return True
559
+ elif et == QEvent.Type.Drop:
560
+ md = event.mimeData()
561
+ if md and md.hasUrls():
562
+ for u in md.urls():
563
+ if u.isLocalFile():
564
+ p = u.toLocalFile()
565
+ if self._is_loadable_path(p):
566
+ if os.path.isdir(p):
567
+ # Keep drag-and-drop behavior aligned with the Load action:
568
+ # dropping a folder loads it, while processing is triggered
569
+ # explicitly via Segment/Analyze actions.
570
+ self.open_source(path=p, source_kind="folder")
571
+ else:
572
+ self.open_source(path=p, source_kind="auto")
573
+ event.acceptProposedAction()
574
+ return True
575
+ return super().eventFilter(obj, event)
576
+
577
+ def _show_view_context_menu(self, global_pos: QPoint) -> None:
578
+ """Show right-click context actions for the current graphics viewport."""
579
+ if self._pixitem.pixmap().isNull():
580
+ return
581
+ menu = QtWidgets.QMenu(self)
582
+ action_save = menu.addAction("Save active image as PNG")
583
+ selected = menu.exec(global_pos)
584
+ if selected is action_save:
585
+ self._save_active_image_png()
586
+
587
+ def _on_export_results_clicked(self) -> None:
588
+ self.save_predictions()
589
+
590
+ def _on_save_screenshot_clicked(self) -> None:
591
+ if self.current_frame.orig_img is not None:
592
+ self._save_active_image_png()
593
+
594
+ def _save_active_image_png(self) -> None:
595
+ """Save the full active image for the selected view mode as PNG."""
596
+ img = self.refresh_view()
597
+ if img is None:
598
+ self._show_info("No image", "No active image is available to save for this view mode.")
599
+ return
600
+
601
+ view_label = str(self.cb_view.currentText() or "view").strip().lower()
602
+ view_slug = "".join(ch if ch.isalnum() else "_" for ch in view_label).strip("_") or "view"
603
+ base_name = (self.current_image_name or "fiberpose").strip() or "fiberpose"
604
+ default_name = f"{base_name}_{view_slug}.png"
605
+ default_path = os.path.join(self.working_dir, default_name)
606
+
607
+ selected_path, _ = QtWidgets.QFileDialog.getSaveFileName(
608
+ self,
609
+ "Save active image as PNG",
610
+ default_path,
611
+ "PNG Files (*.png);;All Files (*)",
612
+ )
613
+ if not selected_path:
614
+ return
615
+ if not selected_path.lower().endswith(".png"):
616
+ selected_path = f"{selected_path}.png"
617
+
618
+ qimg = self._numpy_to_qimage(img)
619
+ pixmap = QtGui.QPixmap.fromImage(qimg)
620
+ ok = pixmap.save(selected_path, "PNG")
621
+ if not ok:
622
+ self._show_error("Save failed", "Could not save the active image as PNG.")
623
+ return
624
+
625
+ self.working_dir = os.path.dirname(selected_path) or self.working_dir
626
+ self.statusbar.showMessage(f"Saved active image: {selected_path}", 5000)
627
+
628
+ def _is_image_path(self, path: str) -> bool:
629
+ ext = os.path.splitext(path)[1].lower()
630
+ return ext in self._supported_image_extensions()
631
+
632
+ def _is_loadable_path(self, path: str) -> bool:
633
+ return os.path.isdir(path) or self._is_image_path(path)
634
+
635
+ def _urls_are_loadable(self, urls) -> bool:
636
+ return any(u.isLocalFile() and self._is_loadable_path(u.toLocalFile()) for u in urls)
637
+
638
+ def _batch_measurements_match_current_settings(self) -> bool:
639
+ if self._batch_result is None or self._image_batch is None:
640
+ return False
641
+ if len(self._batch_result.frame_results) != len(self._image_batch):
642
+ return False
643
+ invert_input = bool(self.chb_invert.isChecked())
644
+ return all(
645
+ frame.has_measurements
646
+ and frame.fiber_summary is not None
647
+ and frame.measurement_sig
648
+ == self._pipeline_service.measurement_signature(
649
+ frame,
650
+ self.config,
651
+ self.sample_props,
652
+ invert_input=invert_input,
653
+ )
654
+ for frame in self._batch_result.frame_results
655
+ )
656
+
657
+ def _set_image_batch(self, image_batch: ImageBatch):
658
+ self._image_batch = image_batch
659
+ self._batch_result = None
660
+ self._current_z_index = 0
661
+ self._configure_z_scroll(len(image_batch))
662
+ self._set_current_slice(0, update_view=True)
663
+ # New source invalidates previous export availability until
664
+ # segmentation/analysis is run on the newly loaded data.
665
+ self._refresh_save_actions()
666
+
667
+ def _apply_sample_properties_from_batch(self, image_batch: ImageBatch) -> None:
668
+ source_path = str(image_batch.metadata.get("source_path", ""))
669
+ self.sample_props = SampleProperties.from_image_metadata(
670
+ image_batch.metadata,
671
+ source_path=source_path,
672
+ )
673
+ self.sync_sample_properties_to_ui()
674
+
675
+ z, y, x = self.sample_props.spacing_zyx()
676
+ logger.info(
677
+ "Sample metadata applied: pixel_width=%s pixel_height=%s voxel_depth=%s unit=%s source=%s",
678
+ image_batch.metadata.get("pixel_width"),
679
+ image_batch.metadata.get("pixel_height"),
680
+ image_batch.metadata.get("voxel_depth"),
681
+ image_batch.metadata.get("unit"),
682
+ self.sample_props.source,
683
+ )
684
+ if self.sample_props.source == "metadata":
685
+ self.statusbar.showMessage(
686
+ f"Loaded sample spacing from metadata: z={z:.6g}, y={y:.6g}, x={x:.6g} {self.sample_props.unit}/px",
687
+ 6000,
688
+ )
689
+ else:
690
+ self.statusbar.showMessage(
691
+ "No spacing metadata found. Using default sample spacing: z=1, y=1, x=1 px.",
692
+ 6000,
693
+ )
694
+
695
+ def open_source(self, path: str | None = None, source_kind: str = "auto") -> ImageBatch | None:
696
+ """Load an image file/folder/stack source and initialize frame/batch state."""
697
+ selected_path = path
698
+
699
+ if selected_path is None:
700
+ if source_kind == "folder":
701
+ selected_path = QFileDialog.getExistingDirectory(
702
+ self, "Select folder with images", self.working_dir
703
+ )
704
+ else:
705
+ selected_path, _ = QtWidgets.QFileDialog.getOpenFileName(
706
+ self,
707
+ "Select Original Image",
708
+ self.working_dir,
709
+ "Images (*.tif *.tiff *.png *.jpg *.jpeg *.bmp *.webp);;All Files (*)",
710
+ )
711
+ if not selected_path:
712
+ return None
713
+
714
+ if source_kind not in {"auto", "file", "folder"}:
715
+ self._show_error("Open source", f"Unsupported source kind: {source_kind}")
716
+ return None
717
+
718
+ try:
719
+ if source_kind == "folder":
720
+ image_batch = ImageBatch.from_folder(
721
+ selected_path,
722
+ extensions=self._supported_image_extensions(),
723
+ )
724
+ elif source_kind == "file":
725
+ image_batch = ImageBatch.from_path(selected_path)
726
+ else:
727
+ image_batch = ImageBatch.from_source(
728
+ selected_path,
729
+ extensions=self._supported_image_extensions(),
730
+ )
731
+ except Exception as e:
732
+ self._show_error("Error", f"Failed to read source:\n{e}")
733
+ logger.error("Failed to read source %s: %s", selected_path, e)
734
+ return None
735
+
736
+ if len(image_batch) == 0:
737
+ self._show_warning("Unsupported", "No readable frames were found in the selected source.")
738
+ return None
739
+
740
+ self._reset_internal_state()
741
+ if os.path.isdir(selected_path):
742
+ self.working_dir = selected_path
743
+ else:
744
+ self.working_dir = os.path.dirname(selected_path)
745
+ self._set_image_batch(image_batch)
746
+ self._apply_sample_properties_from_batch(image_batch)
747
+ logger.info("Loaded %d frame(s) from %s", len(image_batch), selected_path)
748
+ return image_batch
749
+
750
+ def load_original(self):
751
+ """Load original from persisted storage and normalize it for use."""
752
+ self.open_source(source_kind="file")
753
+
754
+ @classmethod
755
+ def _normalize_save_options(cls, raw_options: Any) -> Dict[str, Any]:
756
+ """Normalize save options into a canonical representation.
757
+
758
+ Args:
759
+ raw_options (Any): Configuration values controlling runtime behavior.
760
+
761
+ Returns:
762
+ Dict[str, Any]: Mapping of computed keys and values."""
763
+ return ExportService.normalize_save_options(raw_options)
764
+
765
+ @staticmethod
766
+ def _save_artifact_keys() -> tuple[str, ...]:
767
+ return ExportService.save_artifact_keys()
768
+
769
+ def _current_save_layout(self) -> str:
770
+ """Return export layout based on loaded source type."""
771
+ return ExportService.current_save_layout(self._image_batch)
772
+
773
+ def _current_source_base_name(self) -> str:
774
+ return ExportService.current_source_base_name(self._image_batch, self.current_image_name)
775
+
776
+ def _effective_batch_result_for_save(self) -> BatchResult | None:
777
+ return ExportService.effective_batch_result_for_save(
778
+ layout=self._current_save_layout(),
779
+ image_batch=self._image_batch,
780
+ batch_result=self._batch_result,
781
+ current_frame=self.current_frame,
782
+ )
783
+
784
+ def _build_export_config(
785
+ self,
786
+ *,
787
+ kind: str,
788
+ layout: str,
789
+ save_options: Dict[str, Any],
790
+ base_name: str | None = None,
791
+ image_format_override: str | None = None,
792
+ ) -> Dict[str, Any]:
793
+ return ExportService.build_export_config(
794
+ kind=kind,
795
+ layout=layout,
796
+ save_options=save_options,
797
+ source_base_name=self._current_source_base_name(),
798
+ base_name=base_name,
799
+ image_format_override=image_format_override,
800
+ )
801
+
802
+ def _prompt_save_destination(
803
+ self,
804
+ *,
805
+ kind: str,
806
+ layout: str,
807
+ default_base_name: str,
808
+ image_format: str,
809
+ ) -> tuple[str, str | None, str | None] | None:
810
+ is_csv = kind == "csv"
811
+ if layout == "single":
812
+ ext = ".csv" if is_csv else (".tiff" if image_format == "tiff" else ".png")
813
+ title_single = "Export CSV (choose file name)" if is_csv else "Export results (choose base name)"
814
+ file_filter = "CSV Files (*.csv);;All Files (*)" if is_csv else "All Files (*)"
815
+ default_path = os.path.join(self.working_dir, f"{default_base_name}{ext}")
816
+ selected, _ = QtWidgets.QFileDialog.getSaveFileName(
817
+ self,
818
+ title_single,
819
+ default_path,
820
+ file_filter,
821
+ )
822
+ if not selected:
823
+ return None
824
+ dest_dir = os.path.dirname(selected) or self.working_dir
825
+ base_name = os.path.splitext(os.path.basename(selected))[0] or default_base_name
826
+ if is_csv:
827
+ return dest_dir, base_name, None
828
+ selected_ext = os.path.splitext(selected)[1].strip().lower()
829
+ if selected_ext in {".tif", ".tiff"}:
830
+ image_format_override = "tiff"
831
+ elif selected_ext == ".png":
832
+ image_format_override = "png"
833
+ else:
834
+ image_format_override = None
835
+ return dest_dir, base_name, image_format_override
836
+
837
+ title_multi = "Export CSV to folder" if is_csv else "Export results to folder"
838
+ dest_dir = QFileDialog.getExistingDirectory(
839
+ self,
840
+ title_multi,
841
+ self.working_dir,
842
+ )
843
+ if not dest_dir:
844
+ return None
845
+ return dest_dir, None, None
846
+
847
+ def _run_export(
848
+ self,
849
+ *,
850
+ batch_result: BatchResult,
851
+ dest_dir: str,
852
+ export_config: Dict[str, Any],
853
+ ) -> bool:
854
+ try:
855
+ export_result = batch_result.save_all(dest_dir, export_config)
856
+ except Exception as exc:
857
+ self._show_error("Error", f"Failed to export:\n{exc}")
858
+ return False
859
+
860
+ self.working_dir = dest_dir
861
+ error_count = len(export_result.get("errors", []))
862
+ if error_count:
863
+ self._show_warning(
864
+ "Exported with issues",
865
+ f"Exported {export_result.get('written_count', 0)} file(s) to:\n{dest_dir}\n"
866
+ f"Encountered {error_count} export error(s).",
867
+ )
868
+ return False
869
+
870
+ self._show_info(
871
+ "Export complete",
872
+ f"Exported {export_result.get('written_count', 0)} file(s) to:\n{dest_dir}",
873
+ )
874
+ return True
875
+
876
+ @staticmethod
877
+ def _has_export_data(kind: str, batch_result: BatchResult | None) -> bool:
878
+ return ExportService.has_export_data(kind, batch_result)
879
+
880
+ def _refresh_save_actions(self) -> None:
881
+ batch_result = self._effective_batch_result_for_save()
882
+ has_results = self._has_export_data("results", batch_result)
883
+ has_csv = self._has_export_data("csv", batch_result)
884
+ self.action_save_masks_predictions.setEnabled(has_results)
885
+ self.action_save_measurements.setEnabled(has_csv)
886
+ self.btn_export_results.setEnabled(has_results)
887
+ self.btn_export_csv.setEnabled(has_csv)
888
+ self.btn_save_screenshot.setEnabled(self.current_frame.orig_img is not None)
889
+
890
+ def _save_by_kind(self, kind: str) -> None:
891
+ batch_result = self._effective_batch_result_for_save()
892
+ if not self._has_export_data(kind, batch_result):
893
+ message = "Run segmentation first." if kind == "results" else "Run Analyze fibers first."
894
+ self._show_info("Nothing to export", message)
895
+ return
896
+
897
+ save_options = self._normalize_save_options(self.config.save_options)
898
+ if kind == "results" and not any(bool(save_options.get(key, False)) for key in self._save_artifact_keys()):
899
+ self._show_warning(
900
+ "Nothing selected",
901
+ "All outputs are unchecked in the Export results panel.",
902
+ )
903
+ return
904
+
905
+ layout = self._current_save_layout()
906
+ default_base_name = (self.current_image_name or "fiberpose") + (
907
+ "_results" if kind == "results" else "_samples"
908
+ )
909
+ target = self._prompt_save_destination(
910
+ kind=kind,
911
+ layout=layout,
912
+ default_base_name=default_base_name,
913
+ image_format=str(save_options.get("image_format", "png")),
914
+ )
915
+ if target is None:
916
+ return
917
+ dest_dir, base_name, image_format_override = target
918
+
919
+ export_config = self._build_export_config(
920
+ kind=kind,
921
+ layout=layout,
922
+ save_options=save_options,
923
+ base_name=base_name,
924
+ image_format_override=image_format_override,
925
+ )
926
+ self._run_export(
927
+ batch_result=batch_result,
928
+ dest_dir=dest_dir,
929
+ export_config=export_config,
930
+ )
931
+
932
+ def save_predictions(self):
933
+ """Persist predictions using the configured export conventions."""
934
+ self._save_by_kind("results")
935
+
936
+ def save_measurements(self):
937
+ """Persist measurements using the configured export conventions."""
938
+ self._save_by_kind("csv")
939
+
940
+
941
+ # ------------------- Scalebar -------------------
942
+
943
+ def _on_set_scalebar_clicked(self):
944
+ if self.current_frame.orig_img is None:
945
+ self._show_info("No image", "Load an image before setting the scalebar.")
946
+ return
947
+
948
+ self._cancel_scalebar_selection()
949
+
950
+ dialog = QtWidgets.QDialog(self)
951
+ dialog.setWindowTitle("Set Scalebar Length")
952
+ form = QtWidgets.QFormLayout(dialog)
953
+
954
+ spin = QtWidgets.QDoubleSpinBox(dialog)
955
+ spin.setDecimals(2)
956
+ spin.setMinimum(1e-6)
957
+ spin.setMaximum(1e9)
958
+ spin.setValue(self._scalebar_tool.length_value)
959
+ form.addRow("Length", spin)
960
+
961
+ combo = QtWidgets.QComboBox(dialog)
962
+ units = ["nm", "um", "mm", "m"]
963
+ combo.addItems(units)
964
+ combo.setCurrentText(self._scalebar_tool.unit)
965
+ form.addRow("Units", combo)
966
+
967
+ buttons = QtWidgets.QDialogButtonBox(
968
+ QtWidgets.QDialogButtonBox.StandardButton.Ok
969
+ | QtWidgets.QDialogButtonBox.StandardButton.Cancel,
970
+ parent=dialog,
971
+ )
972
+ buttons.accepted.connect(dialog.accept)
973
+ buttons.rejected.connect(dialog.reject)
974
+ form.addRow(buttons)
975
+
976
+ if dialog.exec() != QtWidgets.QDialog.DialogCode.Accepted:
977
+ return
978
+
979
+ length_value = float(spin.value())
980
+ if length_value <= 0:
981
+ self._show_warning("Invalid length", "Scalebar length must be positive.")
982
+ return
983
+
984
+ self._scalebar_tool.start(length_value, combo.currentText())
985
+ self.graphicsView.viewport().setCursor(Qt.CursorShape.CrossCursor)
986
+ self._show_info(
987
+ "Select Scalebar",
988
+ "Click the two endpoints of the scalebar on the image. Right-click to cancel.",
989
+ )
990
+
991
+ def _handle_scalebar_mouse(self, event: QtGui.QMouseEvent):
992
+ if event.button() == Qt.MouseButton.RightButton:
993
+ self._cancel_scalebar_selection()
994
+ return
995
+ if event.button() != Qt.MouseButton.LeftButton:
996
+ return
997
+ if self._pixitem.pixmap().isNull():
998
+ return
999
+
1000
+ pos = event.position()
1001
+ scene_pos = self.graphicsView.mapToScene(QPoint(int(round(pos.x())), int(round(pos.y()))))
1002
+ x = float(scene_pos.x())
1003
+ y = float(scene_pos.y())
1004
+
1005
+ pix = self._pixitem.pixmap()
1006
+ width = pix.width()
1007
+ height = pix.height()
1008
+ if x < 0 or y < 0 or x >= width or y >= height:
1009
+ return
1010
+
1011
+ px_size = self._scalebar_tool.add_point(x, y)
1012
+ if px_size is not None:
1013
+ self._finalize_scalebar_selection(pixel_size=px_size)
1014
+ elif not self._scalebar_tool.pending: # two clicks on the same point
1015
+ self._cancel_scalebar_selection()
1016
+
1017
+ def _finalize_scalebar_selection(self, pixel_size: float):
1018
+ self.sample_props.pixel_size_x = float(pixel_size)
1019
+ self.sample_props.pixel_size_y = float(pixel_size)
1020
+ self.sample_props.unit = str(self._scalebar_tool.unit or "px")
1021
+ self.sample_props.source = "manual"
1022
+ self.sync_sample_properties_to_ui()
1023
+ self._invalidate_measurements()
1024
+
1025
+ self._show_info(
1026
+ "Scalebar Set",
1027
+ f"Pixel size set to {pixel_size:.6g} {self._scalebar_tool.unit} per pixel.",
1028
+ )
1029
+ self._cancel_scalebar_selection()
1030
+
1031
+ def _cancel_scalebar_selection(self):
1032
+ self._scalebar_tool.cancel()
1033
+ self.graphicsView.viewport().unsetCursor()
1034
+
1035
+ # ------------------- Zoom helpers -------------------
1036
+
1037
+ def reset_zoom(self):
1038
+ self._fit_view_to_pixmap(force=True)
1039
+
1040
+ def _update_reset_button_position(self):
1041
+ viewport = self.graphicsView.viewport()
1042
+ if viewport is None:
1043
+ return
1044
+ margin = 8
1045
+ hint = self.btn_reset_view.sizeHint()
1046
+ x = viewport.width() - hint.width() - margin
1047
+ y = margin
1048
+ self.btn_reset_view.move(max(margin, x), y)
1049
+
1050
+ def _update_reset_button_visibility(self):
1051
+ self.btn_reset_view.setVisible(self._zoom_mode_active)
1052
+
1053
+ def _handle_wheel_zoom(self, event: QtGui.QWheelEvent) -> bool:
1054
+ if self._pixitem.pixmap().isNull():
1055
+ return False
1056
+ angle = event.angleDelta().y()
1057
+ if angle == 0:
1058
+ return False
1059
+ zoom_factor = 1.25 if angle > 0 else 0.8
1060
+ current_scale = self.graphicsView.transform().m11()
1061
+ if current_scale == 0:
1062
+ current_scale = 1.0
1063
+ target_scale = current_scale * zoom_factor
1064
+ base = self._base_scale if self._base_scale not in (0.0, None) else 1.0
1065
+ relative = target_scale / base
1066
+ if relative < self._min_zoom_factor or relative > self._max_zoom_factor:
1067
+ return True
1068
+ was_anchor = self.graphicsView.transformationAnchor()
1069
+ self.graphicsView.setTransformationAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorUnderMouse)
1070
+ self.graphicsView.scale(zoom_factor, zoom_factor)
1071
+ self.graphicsView.setTransformationAnchor(was_anchor)
1072
+ self._zoom_mode_active = True
1073
+ self._update_reset_button_visibility()
1074
+ return True
1075
+
1076
+ # ------------------- Batch processing -------------------
1077
+
1078
+ @staticmethod
1079
+ def _supported_image_extensions() -> set[str]:
1080
+ return {".tif", ".tiff", ".png", ".jpg", ".jpeg", ".bmp", ".webp"}
1081
+
1082
+ def _run_batch_analysis(
1083
+ self,
1084
+ compute_measurements: bool,
1085
+ image_batch: ImageBatch | None = None,
1086
+ error_title: str | None = None,
1087
+ ) -> BatchResult | None:
1088
+ """Run batch processing via `BatchService` and mirror progress in the UI."""
1089
+ active_batch = image_batch if image_batch is not None else self._image_batch
1090
+ if active_batch is None or len(active_batch) == 0:
1091
+ self._show_info("Load original", "Please load an image or folder first.")
1092
+ return None
1093
+
1094
+ # Build user-facing error text per processing mode unless explicitly provided.
1095
+ title = error_title
1096
+ if not title:
1097
+ title = "Batch analysis failed" if compute_measurements else "Batch segmentation failed"
1098
+ target_view = "Measurements overlay" if compute_measurements else "Overlay"
1099
+ if self.cb_view.currentText() != target_view:
1100
+ self.cb_view.setCurrentText(target_view)
1101
+
1102
+ cached_batch = (
1103
+ self._batch_result
1104
+ if (
1105
+ self._batch_result is not None
1106
+ and active_batch is self._image_batch
1107
+ and len(self._batch_result.frame_results) == len(active_batch)
1108
+ )
1109
+ else None
1110
+ )
1111
+
1112
+ # Read settings once; the window stays disabled so they cannot change mid-batch.
1113
+ self.sync_ui_to_config()
1114
+ self.sync_ui_to_sample_properties()
1115
+ invert = bool(self.chb_invert.isChecked())
1116
+
1117
+ QtWidgets.QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
1118
+ previous_batch_state = self._suppress_batch_dialogs
1119
+ if len(active_batch) > 1:
1120
+ self._suppress_batch_dialogs = True
1121
+ try:
1122
+ self.setEnabled(False)
1123
+ def _on_started(total: int) -> None:
1124
+ self.statusbar.showMessage(f"Processing 0/{total} images")
1125
+
1126
+ def _on_frame_started(index: int, total: int) -> None:
1127
+ self.statusbar.showMessage(f"Processing {index + 1}/{total} images")
1128
+ QtWidgets.QApplication.processEvents()
1129
+
1130
+ def _on_frame_finished(_processed: int, _total: int, result: Frame) -> None:
1131
+ self.current_frame = result.snapshot() # a copy: later slice changes mutate current_frame
1132
+ self.refresh_view()
1133
+ QtWidgets.QApplication.processEvents()
1134
+
1135
+ callbacks = BatchCallbacks(
1136
+ on_started=_on_started,
1137
+ on_frame_started=_on_frame_started,
1138
+ on_frame_finished=_on_frame_finished,
1139
+ on_finished=lambda _result: None,
1140
+ )
1141
+
1142
+ def _process_frame(
1143
+ frame: np.ndarray,
1144
+ frame_id: str,
1145
+ z_index: int,
1146
+ cached_frame: Frame | None,
1147
+ do_measurements: bool,
1148
+ ) -> Frame:
1149
+ if cached_frame is None:
1150
+ result = Frame.empty(frame_id=frame_id, z_index=z_index, orig_img=frame)
1151
+ else:
1152
+ result = cached_frame.snapshot(frame_id=frame_id, z_index=z_index)
1153
+ result.orig_img = frame
1154
+ if do_measurements:
1155
+ outcome = self._pipeline_service.ensure_measurements(
1156
+ result, self.config, self.sample_props, invert_input=invert
1157
+ )
1158
+ else:
1159
+ outcome = self._pipeline_service.ensure_segmentation(result, self.config, invert_input=invert)
1160
+ if not self._handle_pipeline_outcome(outcome) and not result.error_message:
1161
+ result.fail("Processing failed.")
1162
+ return result
1163
+
1164
+ batch_result = self._batch_service.run_batch(
1165
+ active_batch,
1166
+ compute_measurements,
1167
+ process_frame=_process_frame,
1168
+ callbacks=callbacks,
1169
+ cached_result=cached_batch,
1170
+ )
1171
+ except Exception as exc:
1172
+ self._show_error(title, str(exc))
1173
+ logger.error("%s: %s", title, exc)
1174
+ return None
1175
+ finally:
1176
+ self._suppress_batch_dialogs = previous_batch_state
1177
+ self.setEnabled(True)
1178
+ QtWidgets.QApplication.restoreOverrideCursor()
1179
+ self.statusbar.clearMessage()
1180
+
1181
+ # Publish batch outputs back into the GUI and refresh the active slice.
1182
+ self._batch_result = batch_result
1183
+ self._set_current_slice(self._current_z_index, update_view=True)
1184
+ self._refresh_save_actions()
1185
+ logger.info(
1186
+ "Batch %s completed successfully for %d frame(s).",
1187
+ "analysis" if compute_measurements else "segmentation",
1188
+ len(active_batch),
1189
+ )
1190
+ return batch_result
1191
+
1192
+ def _on_batch_processing(self):
1193
+ self._run_batch_processing_for_folder(None)
1194
+
1195
+ def _run_batch_processing_for_folder(self, folder_path: str | None):
1196
+ image_batch = self.open_source(path=folder_path, source_kind="folder")
1197
+ if image_batch is None:
1198
+ return
1199
+
1200
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1201
+ directory = self.working_dir
1202
+ output_root = os.path.join(directory, f"fiberpose_batch_{timestamp}")
1203
+ os.makedirs(output_root, exist_ok=True)
1204
+
1205
+ batch_result = self._run_batch_analysis(
1206
+ compute_measurements=True,
1207
+ image_batch=image_batch,
1208
+ error_title="Batch processing failed",
1209
+ )
1210
+ if batch_result is None:
1211
+ return
1212
+
1213
+ save_options = self._normalize_save_options(self.config.save_options)
1214
+ export_config = self._build_export_config(
1215
+ kind="results",
1216
+ layout="frames",
1217
+ save_options=save_options,
1218
+ base_name=None,
1219
+ image_format_override=None,
1220
+ )
1221
+ export_result = batch_result.save_all(output_root, export_config)
1222
+
1223
+ failures: list[tuple[str, str]] = []
1224
+ processed = 0
1225
+ for result in batch_result.frame_results:
1226
+ if not result.has_measurements:
1227
+ failures.append((result.frame_id, "Measurement stage did not produce results"))
1228
+ else:
1229
+ processed += 1
1230
+ export_errors = export_result.get("errors", [])
1231
+ if export_errors:
1232
+ failures.extend(
1233
+ (
1234
+ err.get("frame_id", f"frame_{err.get('frame_index', '?')}"),
1235
+ f"Export {err.get('artifact', 'artifact')} failed: {err.get('error', 'unknown error')}",
1236
+ )
1237
+ for err in export_errors
1238
+ )
1239
+
1240
+ summary_lines = [
1241
+ f"Processed {processed} of {len(image_batch)} frames.",
1242
+ f"Saved {export_result.get('written_count', 0)} file(s) in: {output_root}",
1243
+ ]
1244
+ if failures:
1245
+ summary_lines.append("Failures:")
1246
+ for path, reason in failures[:10]:
1247
+ summary_lines.append(f" - {os.path.basename(str(path))}: {reason}")
1248
+ if len(failures) > 10:
1249
+ summary_lines.append(f" ... ({len(failures) - 10} more)")
1250
+
1251
+ summary = "\n".join(summary_lines)
1252
+ if failures:
1253
+ self._show_warning("Batch processing complete with issues", summary)
1254
+ else:
1255
+ self._show_info("Batch processing complete", summary)
1256
+
1257
+ # ------------------- Profile plot tool -------------------
1258
+
1259
+ def _ensure_profile_dialog(self) -> PlotProfileDialog:
1260
+ if self._profile_dialog is None:
1261
+ self._profile_dialog = PlotProfileDialog(self)
1262
+ self._profile_dialog.clearRequested.connect(self._on_profile_clear_requested)
1263
+ self._profile_dialog.closed.connect(self._on_profile_dialog_closed)
1264
+ return self._profile_dialog
1265
+
1266
+ def _on_plot_profile_clicked(self):
1267
+ if not self._ensure_prediction_ready():
1268
+ return
1269
+ dialog = self._ensure_profile_dialog()
1270
+ if not dialog.isVisible():
1271
+ dialog.reset_plot()
1272
+ dialog.show()
1273
+ dialog.raise_()
1274
+ dialog.activateWindow()
1275
+ self._profile_tool.start()
1276
+ self._reset_profile_selection(keep_dialog=True)
1277
+
1278
+ def _on_profile_clear_requested(self):
1279
+ self._reset_profile_selection(keep_dialog=True)
1280
+
1281
+ def _on_profile_dialog_closed(self):
1282
+ self._profile_tool.stop()
1283
+ self._profile_dialog = None
1284
+ self._reset_profile_selection()
1285
+
1286
+ def _reset_profile_selection(self, keep_dialog: bool = False):
1287
+ self._profile_tool.reset()
1288
+ self._remove_profile_items()
1289
+ dialog = self._profile_dialog
1290
+ if dialog is not None and (keep_dialog or self._profile_tool.active):
1291
+ dialog.reset_plot()
1292
+ if self._profile_tool.active:
1293
+ self.graphicsView.viewport().setCursor(Qt.CursorShape.CrossCursor)
1294
+ else:
1295
+ self.graphicsView.viewport().unsetCursor()
1296
+
1297
+ def _remove_profile_line(self):
1298
+ if self._profile_line_item is not None and self._profile_line_item.scene() is not None:
1299
+ self._scene.removeItem(self._profile_line_item)
1300
+ self._profile_line_item = None
1301
+
1302
+ def _remove_profile_items(self):
1303
+ self._remove_profile_line()
1304
+ if not self._profile_point_items:
1305
+ self._profile_point_items = []
1306
+ return
1307
+ for item in self._profile_point_items:
1308
+ if item is not None and item.scene() is not None:
1309
+ self._scene.removeItem(item)
1310
+ self._profile_point_items = []
1311
+
1312
+ def _add_profile_marker(self, x: float, y: float):
1313
+ if self._scene is None:
1314
+ return
1315
+ radius = 4.0
1316
+ marker = QGraphicsEllipseItem(x - radius, y - radius, 2 * radius, 2 * radius)
1317
+ pen = QtGui.QPen(QtGui.QColor("#FFD966"))
1318
+ pen.setWidth(2)
1319
+ marker.setPen(pen)
1320
+ marker.setBrush(QtGui.QBrush(QtGui.QColor(255, 217, 102, 120)))
1321
+ marker.setZValue(1000)
1322
+ self._scene.addItem(marker)
1323
+ self._profile_point_items.append(marker)
1324
+
1325
+ def _draw_profile_line(self):
1326
+ if len(self._profile_tool.points_scene) < 2 or self._scene is None:
1327
+ return
1328
+ self._remove_profile_line()
1329
+ (x0, y0), (x1, y1) = self._profile_tool.points_scene[:2]
1330
+ pen = QtGui.QPen(QtGui.QColor("#FAD000"))
1331
+ pen.setWidth(2)
1332
+ pen.setCosmetic(True)
1333
+ line_item = self._scene.addLine(QLineF(x0, y0, x1, y1), pen)
1334
+ line_item.setZValue(999)
1335
+ self._profile_line_item = line_item
1336
+
1337
+ def _scene_to_image_coords(self, scene_x: float, scene_y: float) -> tuple[float, float] | None:
1338
+ if self._pixmap_source_shape is None:
1339
+ return None
1340
+ pix = self._pixitem.pixmap()
1341
+ if pix.isNull():
1342
+ return None
1343
+ display_w = float(pix.width())
1344
+ display_h = float(pix.height())
1345
+ if display_w <= 0 or display_h <= 0:
1346
+ return None
1347
+ src_h, src_w = self._pixmap_source_shape
1348
+ scale_x = float(src_w) / display_w
1349
+ scale_y = float(src_h) / display_h
1350
+ return scene_x * scale_x, scene_y * scale_y
1351
+
1352
+ def _handle_profile_mouse(self, event: QtGui.QMouseEvent):
1353
+ if event.button() == Qt.MouseButton.RightButton:
1354
+ self._reset_profile_selection(keep_dialog=True)
1355
+ return
1356
+ if event.button() != Qt.MouseButton.LeftButton:
1357
+ return
1358
+ if self._pixitem.pixmap().isNull():
1359
+ return
1360
+
1361
+ pos = event.position()
1362
+ scene_pos = self.graphicsView.mapToScene(QPoint(int(round(pos.x())), int(round(pos.y()))))
1363
+ sx = float(scene_pos.x())
1364
+ sy = float(scene_pos.y())
1365
+
1366
+ pix = self._pixitem.pixmap()
1367
+ if sx < 0 or sy < 0 or sx >= pix.width() or sy >= pix.height():
1368
+ return
1369
+
1370
+ img_coords = self._scene_to_image_coords(sx, sy)
1371
+ if img_coords is None:
1372
+ return
1373
+
1374
+ ix, iy = img_coords
1375
+ if self._pixmap_source_shape is None:
1376
+ return
1377
+ src_h, src_w = self._pixmap_source_shape
1378
+ if ix < 0 or iy < 0 or ix >= src_w or iy >= src_h:
1379
+ return
1380
+
1381
+ complete = self._profile_tool.add_point((sx, sy), (ix, iy))
1382
+ self._add_profile_marker(sx, sy)
1383
+
1384
+ if complete:
1385
+ self._finalize_profile_selection()
1386
+
1387
+ def _finalize_profile_selection(self):
1388
+ if len(self._profile_tool.points_scene) < 2 or len(self._profile_tool.points_img) < 2:
1389
+ return
1390
+ self._draw_profile_line()
1391
+ self._update_profile_plot()
1392
+
1393
+ def _update_profile_plot(self):
1394
+ if not self.current_frame.has_prediction or len(self._profile_tool.points_img) < 2:
1395
+ return
1396
+ (x0, y0), (x1, y1) = self._profile_tool.points_img[:2]
1397
+ profile = self._profile_tool.compute_profile(
1398
+ self.current_frame.dt,
1399
+ (x0, y0),
1400
+ (x1, y1),
1401
+ scale_factor=float(self.current_frame.scale_factor),
1402
+ )
1403
+ if profile is None:
1404
+ return
1405
+ distances, profile_vals_true, summary = profile
1406
+ dialog = self._ensure_profile_dialog()
1407
+ dialog.update_profile(distances, profile_vals_true, summary)
1408
+
1409
+ # ------------------- Segmentation -------------------
1410
+
1411
+ def _run_current_frame_pipeline(self, compute_measurements: bool) -> bool:
1412
+ if compute_measurements:
1413
+ return self._ensure_measurements_ready()
1414
+ return self._ensure_segmentation_ready()
1415
+
1416
+ def segment(self):
1417
+ """Run the segmentation workflow for the current frame or active batch."""
1418
+ if self._image_batch is not None:
1419
+ self._run_batch_analysis(compute_measurements=False)
1420
+ return
1421
+ if not self._run_current_frame_pipeline(compute_measurements=False):
1422
+ return
1423
+
1424
+ if self.cb_view.currentText() == "Original":
1425
+ self.cb_view.setCurrentText("Overlay")
1426
+
1427
+ self._refresh_save_actions()
1428
+ self.refresh_view()
1429
+ logger.info("Segmentation completed successfully.")
1430
+
1431
+ def analyze_fibers(self):
1432
+ """
1433
+ Computes thickness samples and renders overlays/plots.
1434
+ """
1435
+ if self._image_batch is not None:
1436
+ if self.cb_view.currentText() != "Measurements overlay":
1437
+ self.cb_view.setCurrentText("Measurements overlay")
1438
+ if self._batch_measurements_match_current_settings():
1439
+ self._set_current_slice(self._current_z_index, update_view=True)
1440
+ return
1441
+ self._run_batch_analysis(compute_measurements=True)
1442
+ return
1443
+
1444
+ if not self._run_current_frame_pipeline(compute_measurements=True):
1445
+ return
1446
+ self._render_vector_overlay()
1447
+
1448
+ fr = self.current_frame
1449
+ summary = fr.fiber_summary or {}
1450
+ units_label = str(summary.get("units", "px"))
1451
+ diam_mean = float(summary.get("diam_mean", float("nan")))
1452
+ diam_sd = float(summary.get("diam_sd", float("nan")))
1453
+ diam_mode = float(summary.get("diam_mode", float("nan")))
1454
+ diam_median = float(summary.get("diam_median", float("nan")))
1455
+ orientation_index = float(summary.get("orientation_index", float("nan")))
1456
+ mean_angle_deg = float(summary.get("mean_angle_deg", float("nan")))
1457
+ std_angle_deg = float(summary.get("std_angle_deg", float("nan")))
1458
+ spacing_px_input = max(1.0, float(self.config.sample_spacing))
1459
+ self._show_info(
1460
+ "Analysis complete",
1461
+ f"Measurement Samples: {int(summary.get('sample_count', 0))} (spacing={int(spacing_px_input)} px)\n"
1462
+ f"Drawing Samples: {len(fr.drawing_samples) if fr.drawing_samples is not None else 0}\n"
1463
+ f"Diam Mean: {diam_mean:.2f} {units_label}\n"
1464
+ f"Diam SD: {diam_sd:.2f} {units_label}\n"
1465
+ f"Diam Mode: {diam_mode:.2f} {units_label}\n"
1466
+ f"Diam Median: {diam_median:.2f} {units_label}\n"
1467
+ f"Orientation Index: {orientation_index:.2f}\n"
1468
+ f"Angle Mean: {mean_angle_deg:.2f} deg\n"
1469
+ f"Angle SD: {std_angle_deg:.2f} deg"
1470
+ )
1471
+ self._refresh_save_actions()
1472
+ logger.info("Fiber analysis completed successfully.")
1473
+
1474
+ def _render_vector_overlay(self):
1475
+ if self.current_frame.labels_2d is None:
1476
+ return
1477
+ if self.cb_view.currentText() not in ("Measurements overlay", "Sampling"):
1478
+ self.cb_view.setCurrentText("Measurements overlay")
1479
+ self.refresh_view()
1480
+
1481
+ def _style_plotwidget(self, pw: pg.PlotWidget, title: str, xlab: str, ylab: str):
1482
+ pw.setBackground("w")
1483
+ pw.showAxis("bottom")
1484
+ pw.showAxis("left")
1485
+ pw.clear()
1486
+ pw.setTitle(title, color="k", size="12pt")
1487
+ pw.showGrid(x=True, y=True, alpha=0.25)
1488
+ ax = pw.getAxis("bottom"); ax.setPen("k"); ax.setTextPen("k"); ax.setLabel(xlab, color="k")
1489
+ ay = pw.getAxis("left"); ay.setPen("k"); ay.setTextPen("k"); ay.setLabel(ylab, color="k")
1490
+ pw.setAntialiasing(True)
1491
+
1492
+ def _update_distributions_pyqtgraph(self, units_label: str):
1493
+ self.text_edit2.setVisible(True)
1494
+ self.label_units.setVisible(True)
1495
+ self.cb_units.setVisible(True)
1496
+ # Thickness
1497
+ diameters = (
1498
+ self.current_frame.thickness_units
1499
+ if self.current_frame.thickness_units is not None
1500
+ else np.array([], dtype=np.float32)
1501
+ )
1502
+ self._style_plotwidget(self.graph_diameters, "Diameter Distribution", f"Diameter ({units_label})", "Count")
1503
+ tu = np.asarray(diameters, dtype=np.float32)
1504
+ if tu.size:
1505
+ hist, edges = np.histogram(tu, bins=40)
1506
+ centers = 0.5 * (edges[:-1] + edges[1:])
1507
+ widths = (edges[1:] - edges[:-1])
1508
+ # Thickness (blue)
1509
+ bg = pg.BarGraphItem(
1510
+ x=centers, height=hist, width=widths,
1511
+ brush=pg.mkBrush("#4472C4"), # blue fill
1512
+ pen=pg.mkPen(color="#2F5597", width=1) # darker blue edge
1513
+ )
1514
+ self.graph_diameters.addItem(bg)
1515
+
1516
+ show_pores = self.rb_show_pores.isChecked()
1517
+
1518
+ if not show_pores:
1519
+ # Angles (-90..90)
1520
+ ang = (
1521
+ np.array([sample[5] for sample in (self.current_frame.measurement_samples or [])], dtype=np.float32)
1522
+ if self.current_frame.measurement_samples is not None
1523
+ else np.array([], dtype=np.float32)
1524
+ )
1525
+ self._style_plotwidget(self.graph_angles, "Orientation Distribution", "Angle (deg)", "Count")
1526
+ if ang.size:
1527
+ hist, edges = np.histogram(ang, bins=36, range=(-90, 90))
1528
+ centers = 0.5 * (edges[:-1] + edges[1:])
1529
+ widths = (edges[1:] - edges[:-1])
1530
+ # Angles (green)
1531
+ bg = pg.BarGraphItem(
1532
+ x=centers, height=hist, width=widths,
1533
+ brush=pg.mkBrush("#76A64E"), # green fill
1534
+ pen=pg.mkPen(color="#3C6E2C", width=1) # darker green edge
1535
+ )
1536
+ self.graph_angles.addItem(bg)
1537
+ else:
1538
+ self._style_plotwidget(self.graph_angles, "Pore Diameter Distribution", f"Diameter ({units_label})", "Count")
1539
+ ds = self.current_frame.pore_diams_units if self.current_frame.pore_diams_units is not None else np.array([], dtype=np.float32)
1540
+ if ds.size:
1541
+ hist, edges = np.histogram(ds, bins=40)
1542
+ centers = 0.5 * (edges[:-1] + edges[1:])
1543
+ widths = (edges[1:] - edges[:-1])
1544
+ bg = pg.BarGraphItem(x=centers, height=hist, width=widths,
1545
+ brush=pg.mkBrush("#70AD47"),
1546
+ pen=pg.mkPen(color="#507E2D", width=1))
1547
+ self.graph_angles.addItem(bg)
1548
+
1549
+ # Fit the complete histograms even after the user has zoomed or panned.
1550
+ self.graph_diameters.autoRange()
1551
+ self.graph_angles.autoRange()
1552
+
1553
+ # ------------------- View & reset -------------------
1554
+
1555
+ def refresh_view(self) -> np.ndarray | None:
1556
+ """Show the image of the selected view and return it."""
1557
+ view = self.cb_view.currentText()
1558
+ measurement_views = ("Pores", "Orientations", "Diameters")
1559
+ if view == "Measurements overlay":
1560
+ view = measurement_views[0 if self.rb_show_pores.isChecked() else 1 if self.rb_show_direct.isChecked() else 2]
1561
+ img = render(self.current_frame, view, self.config.grad_quality_points)
1562
+ if img is None and view in measurement_views:
1563
+ img = render(self.current_frame, "Overlay")
1564
+ self._set_pixmap_from_array(img)
1565
+ return img
1566
+
1567
+ def _configure_z_scroll(self, frame_count: int):
1568
+ total = max(1, int(frame_count))
1569
+ self.z_scroll.blockSignals(True)
1570
+ self.z_scroll.setMinimum(0)
1571
+ self.z_scroll.setMaximum(total - 1)
1572
+ self.z_scroll.setSingleStep(1)
1573
+ self.z_scroll.setPageStep(1)
1574
+ self.z_scroll.setValue(0)
1575
+ self.z_scroll.blockSignals(False)
1576
+ self.z_scroll.setEnabled(total > 1)
1577
+ self._update_slice_label()
1578
+
1579
+ def _update_slice_label(self):
1580
+ if self._image_batch is None:
1581
+ self.label_image_name.setText("Image: none")
1582
+ self.label_image_name.setToolTip("")
1583
+ return
1584
+ total = len(self._image_batch)
1585
+ current = self._current_z_index + 1 if total > 0 else 0
1586
+ kind = self._image_batch.kind
1587
+ if kind == "Folder":
1588
+ filename = self._image_batch.metadata["filenames"][self._current_z_index]
1589
+ text = f"Image: {filename} ({current}/{total})"
1590
+ elif kind == "Stack":
1591
+ text = f"Stack: {self._image_batch.name} (slice {current}/{total})"
1592
+ else:
1593
+ text = f"Image: {self._image_batch.name}"
1594
+ self.label_image_name.setText(text)
1595
+ self.label_image_name.setToolTip(text)
1596
+
1597
+ def _frame_base_name(self, frame_id: str, z_index: int) -> str:
1598
+ base = os.path.splitext(str(frame_id))[0]
1599
+ if self._image_batch is None:
1600
+ return base
1601
+ source_type = self._image_batch.metadata.get("source_type")
1602
+ if source_type == "Stack" and len(self._image_batch) > 1:
1603
+ return f"{base}_z{z_index:03d}"
1604
+ return base
1605
+
1606
+ def _apply_frame_result(self, frame_result: Frame | None):
1607
+ current_orig = self.current_frame.orig_img
1608
+ current_frame_id = self.current_frame.frame_id
1609
+ current_z_index = self.current_frame.z_index
1610
+ if frame_result is None:
1611
+ self.current_frame = Frame.empty(
1612
+ frame_id=current_frame_id,
1613
+ z_index=current_z_index,
1614
+ orig_img=current_orig,
1615
+ )
1616
+ self._clear_results()
1617
+ return
1618
+
1619
+ applied_frame = frame_result.snapshot()
1620
+ applied_frame.orig_img = current_orig
1621
+ self.current_frame = applied_frame
1622
+
1623
+ if self.current_frame.fiber_summary:
1624
+ units_label = self.current_frame.fiber_summary.get("units", "px")
1625
+ info_text = (
1626
+ f"Diam Mean: {self.current_frame.fiber_summary.get('diam_mean', float('nan')):.2f} {units_label}\n"
1627
+ f"Diam SD: {self.current_frame.fiber_summary.get('diam_sd', float('nan')):.2f} {units_label}\n"
1628
+ f"Diam Mode: {self.current_frame.fiber_summary.get('diam_mode', float('nan')):.2f} {units_label}\n"
1629
+ f"Diam Median: {self.current_frame.fiber_summary.get('diam_median', float('nan')):.2f} {units_label}\n"
1630
+ f"Orientation Index: {self.current_frame.fiber_summary.get('orientation_index', float('nan')):.2f}\n"
1631
+ f"Angle Mean: {self.current_frame.fiber_summary.get('mean_angle_deg', float('nan')):.2f} deg\n"
1632
+ f"Angle SD: {self.current_frame.fiber_summary.get('std_angle_deg', float('nan')):.2f} deg\n"
1633
+ f"Porosity: {self.current_frame.fiber_summary.get('porosity', float('nan'))*100:.1f} %\n"
1634
+ f"Centerline Fragments: {int(self.current_frame.fiber_summary.get('fragments_with_centerlines', 0))}"
1635
+ )
1636
+ self.text_edit2.setPlainText(info_text)
1637
+ self._update_distributions_pyqtgraph(units_label)
1638
+ else:
1639
+ self._clear_results()
1640
+
1641
+ def _set_current_slice(self, index: int, update_view: bool = True):
1642
+ if self._image_batch is None:
1643
+ return
1644
+ frame_count = len(self._image_batch)
1645
+ if frame_count == 0:
1646
+ return
1647
+ index = max(0, min(int(index), frame_count - 1))
1648
+ self._current_z_index = index
1649
+ if self.z_scroll.value() != index:
1650
+ self.z_scroll.blockSignals(True)
1651
+ self.z_scroll.setValue(index)
1652
+ self.z_scroll.blockSignals(False)
1653
+ frame = self._image_batch.frames[index]
1654
+ frame_id = (
1655
+ self._image_batch.metadata.get("filenames", [str(index)])[index]
1656
+ if self._image_batch.metadata.get("filenames")
1657
+ else str(index)
1658
+ )
1659
+ self.current_frame.frame_id = str(frame_id)
1660
+ self.current_frame.z_index = int(index)
1661
+ self.current_frame.orig_img = frame
1662
+ self.current_frame.orig_img_scaled = None
1663
+ self.current_image_name = self._frame_base_name(str(frame_id), index)
1664
+ self._apply_frame_result(
1665
+ self._batch_result.frame_at(index) if self._batch_result is not None else None
1666
+ )
1667
+ self._update_slice_label()
1668
+ if update_view:
1669
+ self.refresh_view()
1670
+
1671
+ def _on_z_scroll_changed(self, value: int):
1672
+ if self._image_batch is None:
1673
+ return
1674
+ self._set_current_slice(int(value), update_view=True)
1675
+
1676
+ def _reset_processing_state(self, preserve_original: bool = False):
1677
+ """Reset frame processing state, without touching UI widgets/charts."""
1678
+ preserved_orig = self.current_frame.orig_img if preserve_original else None
1679
+ preserved_frame_id = self.current_frame.frame_id if preserve_original else ""
1680
+ preserved_z = self.current_frame.z_index if preserve_original else 0
1681
+ self.current_frame = Frame.empty(
1682
+ frame_id=preserved_frame_id,
1683
+ z_index=preserved_z,
1684
+ orig_img=preserved_orig,
1685
+ )
1686
+ if not preserve_original:
1687
+ self.current_image_name = None
1688
+
1689
+ def _reset_internal_state(self, preserve_original: bool = False, reset_view: bool = True):
1690
+ """Clear all derived data, images, analysis artifacts, and charts."""
1691
+ self._reset_processing_state(preserve_original=preserve_original)
1692
+ if self._profile_dialog is not None:
1693
+ self._profile_dialog.close()
1694
+
1695
+ self._scalebar_tool.cancel()
1696
+ self.graphicsView.viewport().unsetCursor()
1697
+
1698
+ self._profile_tool.stop()
1699
+ self._remove_profile_items()
1700
+ self.btn_reset_view.hide()
1701
+
1702
+ # ---- results (stats + pyqtgraph charts) ----
1703
+ self._clear_results()
1704
+
1705
+ # ---- UI actions / state ----
1706
+ self._pixitem.setPixmap(QtGui.QPixmap())
1707
+
1708
+ self._refresh_save_actions()
1709
+
1710
+ if reset_view:
1711
+ self.cb_view.setCurrentText("Original")
1712
+
1713
+ def _on_usegpu_toggled(self, checked: bool):
1714
+ cuda_ok = onnx_cuda_available()
1715
+ if checked and not cuda_ok:
1716
+ QMessageBox.warning(self, "CUDA not available", "ONNX CUDA provider not available. Using CPU.")
1717
+ self.chb_usegpu.setChecked(False)
1718
+ self.config.use_gpu = False
1719
+ else:
1720
+ self.config.use_gpu = checked
1721
+
1722
+ self._pipeline_service.set_model(self._pipeline_service.model_path, "cuda" if self.config.use_gpu else "cpu")
1723
+
1724
+ def _on_invert_toggled(self, checked: bool):
1725
+ self._invalidate_prediction()
1726
+
1727
+ # ------------------- New default image loading -------------------
1728
+
1729
+ def load_default_image(self):
1730
+ """Load default image from persisted storage and normalize it for use."""
1731
+ default_img_path = str(EXAMPLE_IMAGE_PATH)
1732
+ if os.path.exists(default_img_path):
1733
+ self.open_source(path=default_img_path, source_kind="file")
1734
+ else:
1735
+ logger.info("Default image not found: %s", default_img_path)
1736
+
1737
+
1738
+ def sync_ui_to_sample_properties(self):
1739
+ """Reads sample-specific calibration fields from the UI."""
1740
+ self.sample_props, changed = self._ui_binder.sync_ui_to_sample_properties(self, self.sample_props)
1741
+ if changed:
1742
+ self._invalidate_measurements()
1743
+
1744
+ def sync_sample_properties_to_ui(self):
1745
+ """Updates sample-specific calibration widgets from self.sample_props."""
1746
+ self._ui_binder.sync_sample_properties_to_ui(self, self.sample_props)
1747
+ self._update_pixel_size_unit_label()
1748
+
1749
+ def sync_ui_to_config(self):
1750
+ """Reads the current state of the UI and stores it in self.config."""
1751
+ self.config, flags = self._ui_binder.sync_ui_to_config(self, self.config)
1752
+ if flags.prediction_changed:
1753
+ self._invalidate_prediction()
1754
+ elif flags.segmentation_changed:
1755
+ self._invalidate_segmentation()
1756
+
1757
+ def sync_config_to_ui(self):
1758
+ """Updates the UI widgets to reflect the values in self.config."""
1759
+ self._ui_binder.sync_config_to_ui(self, self.config)
1760
+ self._sync_save_options_to_ui()
1761
+
1762
+ # ------------------- Panel helpers -------------------
1763
+
1764
+ def _clear_results(self) -> None:
1765
+ """Keep the results strip reserved but visually empty until measurements exist."""
1766
+ self.text_edit2.clear()
1767
+ self.text_edit2.setVisible(False)
1768
+ self.label_units.setVisible(False)
1769
+ self.cb_units.setVisible(False)
1770
+ for pw in (self.graph_diameters, self.graph_angles):
1771
+ pw.clear()
1772
+ pw.setTitle(None)
1773
+ pw.hideAxis("bottom")
1774
+ pw.hideAxis("left")
1775
+ pw.setBackground(self.palette().color(QtGui.QPalette.ColorRole.Window))
1776
+
1777
+ @staticmethod
1778
+ def _toggle_advanced(button: QToolButton, panel: QtWidgets.QWidget, checked: bool) -> None:
1779
+ panel.setVisible(checked)
1780
+ button.setArrowType(Qt.ArrowType.DownArrow if checked else Qt.ArrowType.RightArrow)
1781
+
1782
+ def _update_pixel_size_unit_label(self) -> None:
1783
+ self.label_pixel_unit.setText(self.cb_units.currentText().strip() or "px")
1784
+
1785
+ def _on_units_changed(self, _text: str) -> None:
1786
+ """Units are picked next to the plots: re-measure so plots and stats follow the new unit."""
1787
+ had_measurements = self._batch_result is not None and any(
1788
+ frame.has_measurements for frame in self._batch_result.frame_results
1789
+ )
1790
+ self.sync_ui_to_sample_properties()
1791
+ self._update_pixel_size_unit_label()
1792
+ if had_measurements:
1793
+ view = self.cb_view.currentText()
1794
+ self._run_batch_analysis(compute_measurements=True)
1795
+ self.cb_view.setCurrentText(view)
src/fiberpose/gui/support.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """UI support classes for dialogs, config binding, and interaction tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ from dataclasses import dataclass, field, fields
9
+ from typing import Any, Dict
10
+ import numpy as np
11
+
12
+ from PyQt6 import QtGui, QtWidgets
13
+ from PyQt6.QtCore import Qt, pyqtSignal
14
+
15
+ import pyqtgraph as pg
16
+ from skimage.measure import profile_line
17
+
18
+ from ..domain import AppConfig, SampleProperties
19
+
20
+
21
+ class PlotProfileDialog(QtWidgets.QDialog):
22
+ """Render and manage the plot profile dialog workflow."""
23
+ closed = pyqtSignal()
24
+ clearRequested = pyqtSignal()
25
+
26
+ def __init__(self, parent: QtWidgets.QWidget | None = None):
27
+ super().__init__(parent)
28
+ self.setWindowTitle("Distance Transform Profile")
29
+ self.setModal(False)
30
+ self.resize(520, 420)
31
+
32
+ self._empty_text = "Select two points on the image to plot the distance transform profile."
33
+
34
+ layout = QtWidgets.QVBoxLayout(self)
35
+
36
+ self.info_label = QtWidgets.QLabel(self._empty_text)
37
+ self.info_label.setWordWrap(True)
38
+ layout.addWidget(self.info_label)
39
+
40
+ self.plot_widget = pg.PlotWidget()
41
+ layout.addWidget(self.plot_widget, 1)
42
+ self._style_plot()
43
+
44
+ button_row = QtWidgets.QHBoxLayout()
45
+ self.btn_clear = QtWidgets.QPushButton("Clear selection")
46
+ self.btn_clear.clicked.connect(self._on_clear_clicked)
47
+ button_row.addWidget(self.btn_clear)
48
+ button_row.addStretch(1)
49
+ btn_close = QtWidgets.QPushButton("Close")
50
+ btn_close.clicked.connect(self.close)
51
+ button_row.addWidget(btn_close)
52
+ layout.addLayout(button_row)
53
+
54
+ def _style_plot(self):
55
+ self.plot_widget.setBackground("w")
56
+ self.plot_widget.showGrid(x=True, y=True, alpha=0.25)
57
+ self.plot_widget.setTitle("Distance transform profile", color="k", size="12pt")
58
+ self.plot_widget.setLabel("bottom", "Distance (px)")
59
+ self.plot_widget.setLabel("left", "DT value")
60
+
61
+ def reset_plot(self):
62
+ self.plot_widget.clear()
63
+ self._style_plot()
64
+ self.info_label.setText(self._empty_text)
65
+
66
+ def update_profile(self, distances_px: np.ndarray, values: np.ndarray, summary: str):
67
+ self.plot_widget.clear()
68
+ self._style_plot()
69
+ pen = pg.mkPen(color="#D9534F", width=2)
70
+ self.plot_widget.plot(distances_px, values, pen=pen)
71
+ self.info_label.setText(summary)
72
+
73
+ def _on_clear_clicked(self):
74
+ self.clearRequested.emit()
75
+
76
+ def closeEvent(self, event: QtGui.QCloseEvent):
77
+ self.closed.emit()
78
+ super().closeEvent(event)
79
+
80
+
81
+ class ConfigEditorDialog(QtWidgets.QDialog):
82
+ """Schema-driven editor for AppConfig with load/save-as support."""
83
+
84
+ _FIELD_SPEC: Dict[str, Dict[str, Any]] = {
85
+ "model_path": {
86
+ "label": "Model path",
87
+ "kind": "str",
88
+ "tooltip": "Relative or absolute path to the ONNX model (.onnx).",
89
+ },
90
+ "use_gpu": {"label": "Use GPU", "kind": "bool"},
91
+ "scale_label": {
92
+ "label": "Scale",
93
+ "kind": "enum",
94
+ "options": ["0.5x", "1x", "2x", "4x"],
95
+ "editable": True,
96
+ },
97
+ "max_angle_deg": {"label": "Max angle (deg)", "kind": "float", "min": 0.0, "max": 180.0, "step": 1.0},
98
+ "ridge_sigma": {"label": "Ridge sigma", "kind": "float", "min": 0.0, "max": 1e6, "step": 0.1},
99
+ "ridge_low": {"label": "Ridge low", "kind": "float", "min": 0.0, "max": 1e6, "step": 0.01},
100
+ "ridge_high": {"label": "Ridge high", "kind": "float", "min": 0.0, "max": 1e6, "step": 0.01},
101
+ "min_fragment_centerline_length_px": {
102
+ "label": "Min fragment centerline length (px)",
103
+ "kind": "float",
104
+ "min": 0.0,
105
+ "max": 1e6,
106
+ "step": 1.0,
107
+ },
108
+ "strict_centerlines": {"label": "Strict centerlines", "kind": "bool"},
109
+ "keep_segments_without_measurement_centerlines": {
110
+ "label": "Keep segments without measurement centerlines",
111
+ "kind": "bool",
112
+ },
113
+ "segmentation_mode": {
114
+ "label": "Segmentation mode",
115
+ "kind": "enum",
116
+ "options": ["watershed", "radial_expansion"],
117
+ "editable": False,
118
+ },
119
+ "merge_expansion_factor": {
120
+ "label": "Merge expansion factor",
121
+ "kind": "float",
122
+ "min": 0.0,
123
+ "max": 5.0,
124
+ "step": 0.05,
125
+ },
126
+ "segmentation_expansion_factor": {
127
+ "label": "Segmentation expansion factor",
128
+ "kind": "float",
129
+ "min": 0.0,
130
+ "max": 5.0,
131
+ "step": 0.05,
132
+ },
133
+ "watershed_grad_threshold": {
134
+ "label": "Watershed gradient threshold",
135
+ "kind": "float",
136
+ "min": 0.0,
137
+ "max": 5.0,
138
+ "step": 0.05,
139
+ },
140
+ "seg_threshold": {"label": "Pore DT threshold", "kind": "int", "min": 0, "max": 255, "step": 1},
141
+ "sample_spacing": {"label": "Sample spacing (px)", "kind": "float", "min": 0.1, "max": 1e9, "step": 1.0},
142
+ "grad_quality_points": {
143
+ "label": "Grad quality points (JSON list)",
144
+ "kind": "json_list",
145
+ "tooltip": "Signed-error breakpoints [p0, p1, p2, p3] for DT gradient quality view.",
146
+ },
147
+ "save_options": {
148
+ "label": "Save options (JSON object)",
149
+ "kind": "json",
150
+ "tooltip": "Shared export options for single-image, folder, and stack saves.",
151
+ },
152
+ }
153
+
154
+ def __init__(
155
+ self,
156
+ config: AppConfig,
157
+ config_path: str,
158
+ parent: QtWidgets.QWidget | None = None,
159
+ ):
160
+ super().__init__(parent)
161
+ self.setWindowTitle("Edit configuration")
162
+ self.setModal(True)
163
+ self.resize(640, 620)
164
+
165
+ self._config_path = os.path.abspath(config_path) if config_path else ""
166
+ self._initial_config = AppConfig(**vars(config))
167
+ self._result_config = AppConfig(**vars(config))
168
+ self._widgets: Dict[str, QtWidgets.QWidget] = {}
169
+ self._field_order = [f.name for f in fields(AppConfig)]
170
+
171
+ layout = QtWidgets.QVBoxLayout(self)
172
+
173
+ path_row = QtWidgets.QHBoxLayout()
174
+ path_row.addWidget(QtWidgets.QLabel("Config file:"))
175
+ self.lbl_path = QtWidgets.QLabel("")
176
+ self.lbl_path.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
177
+ self.lbl_path.setWordWrap(True)
178
+ path_row.addWidget(self.lbl_path, 1)
179
+ self.btn_load = QtWidgets.QPushButton("Load...")
180
+ self.btn_save_as = QtWidgets.QPushButton("Save As...")
181
+ path_row.addWidget(self.btn_load)
182
+ path_row.addWidget(self.btn_save_as)
183
+ layout.addLayout(path_row)
184
+
185
+ self.scroll = QtWidgets.QScrollArea()
186
+ self.scroll.setWidgetResizable(True)
187
+ form_host = QtWidgets.QWidget()
188
+ self.form = QtWidgets.QFormLayout(form_host)
189
+ self.form.setFieldGrowthPolicy(QtWidgets.QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
190
+ self.form.setLabelAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
191
+ self.scroll.setWidget(form_host)
192
+ layout.addWidget(self.scroll, 1)
193
+
194
+ self._build_form()
195
+ self._set_config_path(self._config_path)
196
+ self._set_widgets_from_config(config)
197
+
198
+ button_box = QtWidgets.QDialogButtonBox(
199
+ QtWidgets.QDialogButtonBox.StandardButton.Ok
200
+ | QtWidgets.QDialogButtonBox.StandardButton.Cancel
201
+ )
202
+ self.btn_apply = button_box.button(QtWidgets.QDialogButtonBox.StandardButton.Ok)
203
+ if self.btn_apply is not None:
204
+ self.btn_apply.setText("Apply && Save")
205
+ button_box.accepted.connect(self._on_accept)
206
+ button_box.rejected.connect(self.reject)
207
+ layout.addWidget(button_box)
208
+
209
+ self.btn_load.clicked.connect(self._on_load_clicked)
210
+ self.btn_save_as.clicked.connect(self._on_save_as_clicked)
211
+
212
+ def result_config(self) -> AppConfig:
213
+ return AppConfig(**vars(self._result_config))
214
+
215
+ def result_config_path(self) -> str:
216
+ return str(self._config_path)
217
+
218
+ def _build_form(self) -> None:
219
+ for key in self._field_order:
220
+ spec = self._FIELD_SPEC.get(key, {})
221
+ template_value = getattr(self._initial_config, key, None)
222
+ widget = self._create_widget_for_field(key, spec, template_value)
223
+ if widget is None:
224
+ continue
225
+ label = spec.get("label") or key.replace("_", " ").capitalize()
226
+ tooltip = spec.get("tooltip")
227
+ if tooltip:
228
+ widget.setToolTip(str(tooltip))
229
+ self.form.addRow(label, widget)
230
+ self._widgets[key] = widget
231
+
232
+ def _create_widget_for_field(
233
+ self,
234
+ key: str,
235
+ spec: Dict[str, Any],
236
+ template_value: Any,
237
+ ) -> QtWidgets.QWidget | None:
238
+ kind = spec.get("kind")
239
+ if not kind:
240
+ if isinstance(template_value, bool):
241
+ kind = "bool"
242
+ elif isinstance(template_value, int):
243
+ kind = "int"
244
+ elif isinstance(template_value, float):
245
+ kind = "float"
246
+ elif isinstance(template_value, dict):
247
+ kind = "json"
248
+ else:
249
+ kind = "str"
250
+ if kind == "bool":
251
+ return QtWidgets.QCheckBox()
252
+ if kind == "int":
253
+ spin = QtWidgets.QSpinBox()
254
+ spin.setMinimum(int(spec.get("min", -2_000_000_000)))
255
+ spin.setMaximum(int(spec.get("max", 2_000_000_000)))
256
+ spin.setSingleStep(int(spec.get("step", 1)))
257
+ return spin
258
+ if kind == "float":
259
+ spin = QtWidgets.QDoubleSpinBox()
260
+ spin.setDecimals(6)
261
+ spin.setMinimum(float(spec.get("min", -1e12)))
262
+ spin.setMaximum(float(spec.get("max", 1e12)))
263
+ spin.setSingleStep(float(spec.get("step", 0.1)))
264
+ return spin
265
+ if kind == "enum":
266
+ combo = QtWidgets.QComboBox()
267
+ options = [str(v) for v in spec.get("options", [])]
268
+ combo.addItems(options)
269
+ combo.setEditable(bool(spec.get("editable", False)))
270
+ return combo
271
+ if kind == "json":
272
+ text = QtWidgets.QPlainTextEdit()
273
+ text.setTabChangesFocus(True)
274
+ text.setMinimumHeight(120)
275
+ return text
276
+ if kind == "json_list":
277
+ text = QtWidgets.QPlainTextEdit()
278
+ text.setTabChangesFocus(True)
279
+ text.setMinimumHeight(80)
280
+ return text
281
+ return QtWidgets.QLineEdit()
282
+
283
+ def _set_widgets_from_config(self, cfg: AppConfig) -> None:
284
+ for key, widget in self._widgets.items():
285
+ value = getattr(cfg, key, None)
286
+ if isinstance(widget, QtWidgets.QCheckBox):
287
+ widget.setChecked(bool(value))
288
+ elif isinstance(widget, QtWidgets.QSpinBox):
289
+ try:
290
+ widget.setValue(int(value))
291
+ except Exception:
292
+ widget.setValue(0)
293
+ elif isinstance(widget, QtWidgets.QDoubleSpinBox):
294
+ try:
295
+ widget.setValue(float(value))
296
+ except Exception:
297
+ widget.setValue(0.0)
298
+ elif isinstance(widget, QtWidgets.QComboBox):
299
+ txt = str(value) if value is not None else ""
300
+ idx = widget.findText(txt)
301
+ if idx >= 0:
302
+ widget.setCurrentIndex(idx)
303
+ else:
304
+ widget.setCurrentText(txt)
305
+ elif isinstance(widget, QtWidgets.QPlainTextEdit):
306
+ kind = self._FIELD_SPEC.get(key, {}).get("kind")
307
+ if kind == "json_list":
308
+ payload = list(value) if isinstance(value, (list, tuple)) else []
309
+ else:
310
+ payload = value if isinstance(value, dict) else {}
311
+ widget.setPlainText(json.dumps(payload, indent=2, sort_keys=True))
312
+ elif isinstance(widget, QtWidgets.QLineEdit):
313
+ widget.setText("" if value is None else str(value))
314
+
315
+ def _read_config_from_widgets(self) -> AppConfig:
316
+ data: Dict[str, Any] = {}
317
+ for key in self._field_order:
318
+ widget = self._widgets.get(key)
319
+ if widget is None:
320
+ continue
321
+ if isinstance(widget, QtWidgets.QCheckBox):
322
+ data[key] = bool(widget.isChecked())
323
+ elif isinstance(widget, QtWidgets.QSpinBox):
324
+ data[key] = int(widget.value())
325
+ elif isinstance(widget, QtWidgets.QDoubleSpinBox):
326
+ data[key] = float(widget.value())
327
+ elif isinstance(widget, QtWidgets.QComboBox):
328
+ data[key] = widget.currentText().strip()
329
+ elif isinstance(widget, QtWidgets.QPlainTextEdit):
330
+ raw = widget.toPlainText().strip()
331
+ kind = self._FIELD_SPEC.get(key, {}).get("kind")
332
+ if not raw:
333
+ data[key] = [] if kind == "json_list" else {}
334
+ else:
335
+ parsed = json.loads(raw)
336
+ if kind == "json_list":
337
+ if not isinstance(parsed, list):
338
+ raise ValueError(f"Field '{key}' must be a JSON list.")
339
+ else:
340
+ if not isinstance(parsed, dict):
341
+ raise ValueError(f"Field '{key}' must be a JSON object.")
342
+ data[key] = parsed
343
+ elif isinstance(widget, QtWidgets.QLineEdit):
344
+ data[key] = widget.text().strip()
345
+ return AppConfig.from_dict(data)
346
+
347
+ def _set_config_path(self, path: str) -> None:
348
+ self._config_path = os.path.abspath(path) if path else ""
349
+ self.lbl_path.setText(self._config_path or "(not set)")
350
+
351
+ def _on_load_clicked(self) -> None:
352
+ start_dir = os.path.dirname(self._config_path) if self._config_path else os.getcwd()
353
+ selected_path, _ = QtWidgets.QFileDialog.getOpenFileName(
354
+ self,
355
+ "Select config file",
356
+ start_dir,
357
+ "JSON Files (*.json);;All Files (*)",
358
+ )
359
+ if not selected_path:
360
+ return
361
+ selected_path = os.path.abspath(selected_path)
362
+ try:
363
+ cfg = AppConfig.load_from_json(selected_path)
364
+ except Exception as exc:
365
+ QtWidgets.QMessageBox.critical(self, "Load failed", str(exc))
366
+ return
367
+ self._set_widgets_from_config(cfg)
368
+ self._set_config_path(selected_path)
369
+
370
+ def _on_save_as_clicked(self) -> None:
371
+ try:
372
+ cfg = self._read_config_from_widgets()
373
+ except Exception as exc:
374
+ QtWidgets.QMessageBox.warning(self, "Invalid config", str(exc))
375
+ return
376
+
377
+ start_path = self._config_path or os.path.join(os.getcwd(), "config.json")
378
+ selected_path, _ = QtWidgets.QFileDialog.getSaveFileName(
379
+ self,
380
+ "Save config as",
381
+ start_path,
382
+ "JSON Files (*.json);;All Files (*)",
383
+ )
384
+ if not selected_path:
385
+ return
386
+ selected_path = os.path.abspath(selected_path)
387
+ try:
388
+ parent_dir = os.path.dirname(selected_path)
389
+ if parent_dir:
390
+ os.makedirs(parent_dir, exist_ok=True)
391
+ cfg.save_to_json(selected_path)
392
+ except Exception as exc:
393
+ QtWidgets.QMessageBox.critical(self, "Save failed", str(exc))
394
+ return
395
+
396
+ self._set_config_path(selected_path)
397
+ self._result_config = cfg
398
+ QtWidgets.QMessageBox.information(self, "Saved", f"Config saved to:\n{selected_path}")
399
+
400
+ def _on_accept(self) -> None:
401
+ try:
402
+ cfg = self._read_config_from_widgets()
403
+ except Exception as exc:
404
+ QtWidgets.QMessageBox.warning(self, "Invalid config", str(exc))
405
+ return
406
+
407
+ if not self._config_path:
408
+ QtWidgets.QMessageBox.warning(
409
+ self,
410
+ "Config path missing",
411
+ "Use 'Save As...' to select a config file path.",
412
+ )
413
+ return
414
+
415
+ try:
416
+ parent_dir = os.path.dirname(self._config_path)
417
+ if parent_dir:
418
+ os.makedirs(parent_dir, exist_ok=True)
419
+ cfg.save_to_json(self._config_path)
420
+ except Exception as exc:
421
+ QtWidgets.QMessageBox.critical(self, "Save failed", str(exc))
422
+ return
423
+
424
+ self._result_config = cfg
425
+ self.accept()
426
+
427
+
428
+ @dataclass
429
+ class InvalidationFlags:
430
+ """Computed invalidation deltas after applying UI state to config."""
431
+
432
+ prediction_changed: bool = False
433
+ segmentation_changed: bool = False
434
+
435
+
436
+ class UiConfigBinder:
437
+ """Owns synchronization logic between Qt widgets and configuration models."""
438
+
439
+ @staticmethod
440
+ def sync_ui_to_sample_properties(window, sample_props: SampleProperties) -> tuple[SampleProperties, bool]:
441
+ prev_px = float(getattr(sample_props, "pixel_size_x", 1.0))
442
+ prev_py = float(getattr(sample_props, "pixel_size_y", 1.0))
443
+ prev_z = float(getattr(sample_props, "voxel_size_z", 1.0))
444
+ prev_unit = str(getattr(sample_props, "unit", "px"))
445
+
446
+ def _parse_positive(text: str, fallback: float) -> float:
447
+ text = (text or "").strip()
448
+ if not text:
449
+ return float(fallback)
450
+ try:
451
+ value = float(text)
452
+ except ValueError:
453
+ return float(fallback)
454
+ if value > 0 and np.isfinite(value):
455
+ return float(value)
456
+ return float(fallback)
457
+
458
+ px = _parse_positive(
459
+ window.le_pixelsize.text(),
460
+ sample_props.effective_pixel_size_xy(),
461
+ )
462
+ z = _parse_positive(
463
+ window.le_voxeldepth.text(),
464
+ sample_props.voxel_size_z,
465
+ )
466
+
467
+ sample_props.pixel_size_x = float(px)
468
+ sample_props.pixel_size_y = float(px)
469
+ sample_props.voxel_size_z = float(z)
470
+ unit_txt = window.cb_units.currentText().strip()
471
+ sample_props.unit = unit_txt if unit_txt else "px"
472
+ sample_props.source = "manual"
473
+
474
+ changed = (
475
+ not math.isclose(prev_px, float(sample_props.pixel_size_x), rel_tol=1e-9, abs_tol=1e-9)
476
+ or not math.isclose(prev_py, float(sample_props.pixel_size_y), rel_tol=1e-9, abs_tol=1e-9)
477
+ or not math.isclose(prev_z, float(sample_props.voxel_size_z), rel_tol=1e-9, abs_tol=1e-9)
478
+ or prev_unit != str(sample_props.unit)
479
+ )
480
+ return sample_props, changed
481
+
482
+ @staticmethod
483
+ def sync_sample_properties_to_ui(window, sample_props: SampleProperties) -> None:
484
+ px = sample_props.effective_pixel_size_xy()
485
+ window.le_pixelsize.setText(f"{px:.6g}")
486
+ window.le_voxeldepth.setText(f"{sample_props.voxel_size_z:.6g}")
487
+
488
+ unit_txt = sample_props.unit if sample_props.unit else "px"
489
+ window.cb_units.blockSignals(True)
490
+ idx = window.cb_units.findText(unit_txt)
491
+ if idx >= 0:
492
+ window.cb_units.setCurrentIndex(idx)
493
+ else:
494
+ window.cb_units.setCurrentText(unit_txt)
495
+ window.cb_units.blockSignals(False)
496
+
497
+ @staticmethod
498
+ def sync_ui_to_config(window, config: AppConfig) -> tuple[AppConfig, InvalidationFlags]:
499
+ prev_model_path = str(config.model_path)
500
+ prev_scale_label = str(config.scale_label)
501
+ prev_strict = bool(config.strict_centerlines)
502
+ prev_mode = str(config.segmentation_mode)
503
+ prev_gradient_threshold = float(config.watershed_grad_threshold)
504
+
505
+ config.model_path = window.cb_model.currentText().strip()
506
+ config.use_gpu = window.chb_usegpu.isChecked()
507
+ config.scale_label = window.cb_scale.currentText().strip()
508
+ config.strict_centerlines = window.chb_strict.isChecked()
509
+
510
+ if window.rb_ridge.isChecked():
511
+ config.segmentation_mode = "radial_expansion"
512
+ else:
513
+ config.segmentation_mode = "watershed"
514
+
515
+ config.watershed_grad_threshold = float(window.sp_grad_magnitude_threshold.value())
516
+
517
+ prediction_changed = (
518
+ prev_model_path != str(config.model_path)
519
+ or prev_scale_label != str(config.scale_label)
520
+ )
521
+ segmentation_changed = (
522
+ prev_strict != bool(config.strict_centerlines)
523
+ or prev_mode != str(config.segmentation_mode)
524
+ or not math.isclose(
525
+ prev_gradient_threshold,
526
+ float(config.watershed_grad_threshold),
527
+ rel_tol=1e-9,
528
+ abs_tol=1e-9,
529
+ )
530
+ )
531
+ flags = InvalidationFlags(
532
+ prediction_changed=prediction_changed,
533
+ segmentation_changed=segmentation_changed,
534
+ )
535
+ return config, flags
536
+
537
+ @staticmethod
538
+ def sync_config_to_ui(window, config: AppConfig) -> None:
539
+ def set_combo_text(cb, text):
540
+ cb.blockSignals(True)
541
+ idx = cb.findText(text)
542
+ if idx >= 0:
543
+ cb.setCurrentIndex(idx)
544
+ else:
545
+ cb.setCurrentText(text)
546
+ cb.blockSignals(False)
547
+
548
+ set_combo_text(window.cb_model, config.model_path)
549
+
550
+ window.chb_usegpu.blockSignals(True)
551
+ window.chb_usegpu.setChecked(bool(config.use_gpu))
552
+ window.chb_usegpu.blockSignals(False)
553
+
554
+ set_combo_text(window.cb_scale, config.scale_label)
555
+
556
+ window.chb_strict.blockSignals(True)
557
+ window.chb_strict.setChecked(bool(config.strict_centerlines))
558
+ window.chb_strict.blockSignals(False)
559
+
560
+ window.rb_watershed.blockSignals(True)
561
+ window.rb_ridge.blockSignals(True)
562
+ if str(config.segmentation_mode).strip().lower() == "radial_expansion":
563
+ window.rb_ridge.setChecked(True)
564
+ else:
565
+ window.rb_watershed.setChecked(True)
566
+ window.rb_watershed.blockSignals(False)
567
+ window.rb_ridge.blockSignals(False)
568
+
569
+ window.sp_grad_magnitude_threshold.blockSignals(True)
570
+ window.sp_grad_magnitude_threshold.setValue(float(config.watershed_grad_threshold))
571
+ window.sp_grad_magnitude_threshold.blockSignals(False)
572
+
573
+
574
+ @dataclass
575
+ class ScalebarTool:
576
+ """State machine for selecting a two-point scalebar."""
577
+
578
+ length_value: float = 100.0
579
+ unit: str = "um"
580
+ pending: bool = False
581
+ points: list[tuple[float, float]] = field(default_factory=list)
582
+
583
+ def start(self, length_value: float, unit: str) -> None:
584
+ self.length_value = float(length_value)
585
+ self.unit = str(unit)
586
+ self.pending = True
587
+ self.points = []
588
+
589
+ def cancel(self) -> None:
590
+ self.pending = False
591
+ self.points = []
592
+
593
+ def add_point(self, x: float, y: float) -> float | None:
594
+ if not self.pending:
595
+ return None
596
+ self.points.append((float(x), float(y)))
597
+ if len(self.points) < 2:
598
+ return None
599
+ (x0, y0), (x1, y1) = self.points[:2]
600
+ pixel_length = float(np.hypot(x1 - x0, y1 - y0))
601
+ self.pending = False
602
+ self.points = []
603
+ if pixel_length <= 0:
604
+ return None
605
+ return float(self.length_value / pixel_length)
606
+
607
+
608
+ @dataclass
609
+ class ProfileTool:
610
+ """Two-point line profile interaction helper."""
611
+
612
+ active: bool = False
613
+ points_scene: list[tuple[float, float]] = field(default_factory=list)
614
+ points_img: list[tuple[float, float]] = field(default_factory=list)
615
+
616
+ def start(self) -> None:
617
+ self.active = True
618
+ self.points_scene = []
619
+ self.points_img = []
620
+
621
+ def stop(self) -> None:
622
+ self.active = False
623
+ self.points_scene = []
624
+ self.points_img = []
625
+
626
+ def reset(self) -> None:
627
+ self.points_scene = []
628
+ self.points_img = []
629
+
630
+ def add_point(self, scene_xy: tuple[float, float], img_xy: tuple[float, float]) -> bool:
631
+ if len(self.points_scene) >= 2:
632
+ self.reset()
633
+ self.points_scene.append((float(scene_xy[0]), float(scene_xy[1])))
634
+ self.points_img.append((float(img_xy[0]), float(img_xy[1])))
635
+ return len(self.points_scene) == 2
636
+
637
+ @staticmethod
638
+ def compute_profile(
639
+ dt: np.ndarray,
640
+ p0_xy: tuple[float, float],
641
+ p1_xy: tuple[float, float],
642
+ *,
643
+ scale_factor: float,
644
+ ) -> tuple[np.ndarray, np.ndarray, str] | None:
645
+ x0, y0 = p0_xy
646
+ x1, y1 = p1_xy
647
+ length_px = float(np.hypot(x1 - x0, y1 - y0))
648
+ if length_px <= 0:
649
+ return None
650
+
651
+ profile_vals = profile_line(dt, (y0, x0), (y1, x1), mode="reflect", order=1)
652
+ if profile_vals is None or profile_vals.size == 0:
653
+ return None
654
+
655
+ profile_vals = np.asarray(profile_vals, dtype=np.float32)
656
+ scale = float(scale_factor)
657
+ if not np.isfinite(scale) or scale <= 0:
658
+ scale = 1.0
659
+
660
+ true_length_px = length_px / scale
661
+ profile_vals_true = profile_vals / scale
662
+ distances = np.linspace(0.0, true_length_px, profile_vals.size, dtype=np.float32)
663
+ delta = float(profile_vals_true[-1] - profile_vals_true[0])
664
+ summary = (
665
+ f"Length: {true_length_px:.2f} px · ΔDT: {delta:+.2f} · "
666
+ f"Min/Max: {float(profile_vals_true.min()):.2f} / {float(profile_vals_true.max()):.2f}"
667
+ )
668
+ return distances, profile_vals_true, summary
src/fiberpose/io_export.py ADDED
@@ -0,0 +1,639 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export service and batch result exporter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import dataclasses
7
+ import json
8
+ import os
9
+ from typing import Any
10
+
11
+ import cv2
12
+ import imageio.v3 as iio
13
+ import numpy as np
14
+
15
+ from .domain import AppConfig, BatchResult, Frame, ImageBatch
16
+ from .render import render
17
+
18
+
19
+ def frame_at_original_scale(frame: Frame) -> Frame:
20
+ """Copy of `frame` with per-pixel outputs mapped from the processing scale back to `orig_img`'s size.
21
+
22
+ Labels use nearest neighbour (ids never mixed); the DT is resampled and divided by the scale
23
+ so its values are distances in original pixels.
24
+ """
25
+ scale = float(frame.scale_factor or 1.0)
26
+ if scale == 1.0 or frame.orig_img is None or frame.dt is None:
27
+ return frame
28
+ (h, w), (sh, sw) = frame.orig_img.shape[:2], frame.dt.shape[:2]
29
+ interp = cv2.INTER_AREA if scale > 1.0 else cv2.INTER_LINEAR
30
+ resize = lambda a: None if a is None else cv2.resize(np.asarray(a, np.float32), (w, h), interpolation=interp)
31
+ rows = np.minimum(((np.arange(h) + 0.5) * sh / h).astype(np.intp), sh - 1)
32
+ cols = np.minimum(((np.arange(w) + 0.5) * sw / w).astype(np.intp), sw - 1)
33
+ labels = frame.labels_2d
34
+ return dataclasses.replace(
35
+ frame,
36
+ orig_img_scaled=None,
37
+ scale_factor=1.0,
38
+ dt=resize(frame.dt) / scale,
39
+ foreground_prob=resize(frame.foreground_prob),
40
+ labels_2d=None if labels is None else labels[rows[:, None], cols],
41
+ # measurement_samples already hold the same tuples in original coordinates.
42
+ drawing_samples=frame.measurement_samples,
43
+ views={},
44
+ )
45
+
46
+
47
+ class ExportService:
48
+ """Pure export helpers for predictions/results tables."""
49
+
50
+ @staticmethod
51
+ def default_save_options() -> dict[str, Any]:
52
+ return dict(AppConfig().save_options)
53
+
54
+ @staticmethod
55
+ def save_artifact_keys() -> tuple[str, ...]:
56
+ return ("dt", "foreground", "labels", "overlay", "diameters", "orientations", "outline", "tables")
57
+
58
+ @classmethod
59
+ def normalize_save_options(cls, raw_options: Any) -> dict[str, Any]:
60
+ defaults = cls.default_save_options()
61
+ if not isinstance(raw_options, dict):
62
+ return defaults
63
+
64
+ normalized = dict(defaults)
65
+ for key in cls.save_artifact_keys():
66
+ if key in raw_options:
67
+ normalized[key] = bool(raw_options.get(key))
68
+
69
+ image_format = str(raw_options.get("image_format", defaults["image_format"])).strip().lower()
70
+ normalized["image_format"] = image_format if image_format in {"png", "tiff"} else defaults["image_format"]
71
+
72
+ collision = str(raw_options.get("collision", defaults["collision"])).strip().lower()
73
+ normalized["collision"] = collision if collision in {"suffix", "overwrite", "error"} else defaults["collision"]
74
+
75
+ normalized["write_manifest"] = bool(raw_options.get("write_manifest", defaults["write_manifest"]))
76
+ return normalized
77
+
78
+ @staticmethod
79
+ def current_save_layout(image_batch: ImageBatch | None) -> str:
80
+ if image_batch is None:
81
+ return "single"
82
+ source_type = str((image_batch.metadata or {}).get("source_type", "")).strip().lower()
83
+ if source_type == "folder":
84
+ return "frames"
85
+ if source_type == "stack":
86
+ return "stack"
87
+ return "single"
88
+
89
+ @staticmethod
90
+ def current_source_base_name(image_batch: ImageBatch | None, current_image_name: str | None) -> str:
91
+ if image_batch is not None:
92
+ source_path = str((image_batch.metadata or {}).get("source_path", "")).strip()
93
+ if source_path:
94
+ return os.path.splitext(os.path.basename(os.path.normpath(source_path)))[0] or "fiberpose"
95
+ return current_image_name or "fiberpose"
96
+
97
+ @classmethod
98
+ def artifact_exclude_from_save_options(cls, options: dict[str, Any]) -> list[str]:
99
+ return [name for name in cls.save_artifact_keys() if not bool(options.get(name, False))]
100
+
101
+ @staticmethod
102
+ def effective_batch_result_for_save(
103
+ *,
104
+ layout: str,
105
+ image_batch: ImageBatch | None,
106
+ batch_result: BatchResult | None,
107
+ current_frame: Frame,
108
+ ) -> BatchResult | None:
109
+ if layout != "single":
110
+ if image_batch is None or batch_result is None:
111
+ return None
112
+ if len(batch_result.frame_results) != len(image_batch):
113
+ return None
114
+ return batch_result
115
+
116
+ if batch_result is not None and len(batch_result.frame_results) == 1:
117
+ return batch_result
118
+
119
+ if current_frame.orig_img is None:
120
+ return None
121
+
122
+ frame_result = current_frame.snapshot(
123
+ frame_id=str(current_frame.frame_id),
124
+ z_index=int(current_frame.z_index),
125
+ )
126
+ return BatchResult(frame_results=[frame_result])
127
+
128
+ @classmethod
129
+ def build_export_config(
130
+ cls,
131
+ *,
132
+ kind: str,
133
+ layout: str,
134
+ save_options: dict[str, Any],
135
+ source_base_name: str,
136
+ base_name: str | None = None,
137
+ image_format_override: str | None = None,
138
+ ) -> dict[str, Any]:
139
+ if kind not in {"results", "csv"}:
140
+ raise ValueError(f"Unsupported save kind: {kind}")
141
+
142
+ image_format = image_format_override or str(save_options.get("image_format", "png"))
143
+ export_config: dict[str, Any] = {
144
+ "preset": "full" if kind == "results" else "measurements",
145
+ "collision": str(save_options.get("collision", "suffix")),
146
+ "write_manifest": bool(save_options.get("write_manifest", True)),
147
+ "layout": layout,
148
+ "source_base_name": source_base_name,
149
+ }
150
+ if kind == "results":
151
+ export_config["exclude"] = cls.artifact_exclude_from_save_options(save_options)
152
+
153
+ if layout == "single":
154
+ export_config.update(
155
+ {
156
+ "naming": "frame_id",
157
+ "collision": "overwrite",
158
+ "base_name": base_name or source_base_name,
159
+ "write_manifest": False,
160
+ }
161
+ )
162
+ if kind == "results":
163
+ export_config["image_format"] = "tiff" if image_format == "tiff" else "png"
164
+ elif layout == "frames":
165
+ export_config["naming"] = "frame_id"
166
+ if kind == "results":
167
+ export_config["image_format"] = "tiff" if image_format == "tiff" else "png"
168
+ elif layout == "stack":
169
+ if base_name:
170
+ export_config["base_name"] = str(base_name)
171
+ else:
172
+ raise ValueError(f"Unsupported save layout: {layout}")
173
+
174
+ return export_config
175
+
176
+ @staticmethod
177
+ def has_export_data(kind: str, batch_result: BatchResult | None) -> bool:
178
+ if batch_result is None:
179
+ return False
180
+ if kind == "results":
181
+ return any(fr.has_prediction or fr.has_segmentation for fr in batch_result.frame_results)
182
+ if kind == "csv":
183
+ return any(
184
+ fr.has_measurements and fr.samples_table is not None and len(fr.samples_table) > 0
185
+ for fr in batch_result.frame_results
186
+ )
187
+ return False
188
+
189
+
190
+ class BatchResultExporter:
191
+ """Persist batch/frame outputs using a small dict-based export config."""
192
+
193
+ _ALL_ARTIFACTS = ("dt", "foreground", "labels", "overlay", "diameters", "orientations", "outline", "tables")
194
+ _PRESET_ARTIFACTS = {
195
+ "predictions": {"dt", "foreground", "labels", "overlay", "diameters", "orientations", "outline"},
196
+ "measurements": {"tables"},
197
+ "full": {"dt", "foreground", "labels", "overlay", "diameters", "orientations", "outline", "tables"},
198
+ }
199
+ # Array written for each non-table artifact; None means the frame lacks it.
200
+ _ARRAYS = {
201
+ "dt": lambda frame: frame.dt,
202
+ "foreground": lambda frame: frame.foreground_prob,
203
+ "labels": lambda frame: render(frame, "Segmentation") if frame.labels_2d is not None and frame.labels_2d.any() else None,
204
+ "overlay": lambda frame: render(frame, "Overlay"),
205
+ "diameters": lambda frame: render(frame, "Diameters"),
206
+ "orientations": lambda frame: render(frame, "Orientations"),
207
+ "outline": lambda frame: render(frame, "Segmentation outline"),
208
+ }
209
+
210
+ def __init__(self, export_config: dict[str, Any] | None = None):
211
+ self.export_config = dict(export_config or {})
212
+
213
+ def save_all(
214
+ self,
215
+ batch_result,
216
+ output_dir: str,
217
+ export_config: dict[str, Any] | None = None,
218
+ ) -> dict[str, Any]:
219
+ """Export configured artifacts for all frames (or as stacks) and return a save manifest."""
220
+ cfg = self._normalize_export_config(export_config or self.export_config)
221
+ artifacts = self._resolve_artifacts(cfg)
222
+
223
+ os.makedirs(output_dir, exist_ok=True)
224
+
225
+ layout = str(cfg.get("layout", "frames")).strip().lower()
226
+ if layout == "stack":
227
+ written_files, skipped, errors = self._save_stack_artifacts(
228
+ batch_result=batch_result,
229
+ output_dir=output_dir,
230
+ cfg=cfg,
231
+ artifacts=artifacts,
232
+ )
233
+ else:
234
+ written_files, skipped, errors = self._save_framewise_artifacts(
235
+ batch_result=batch_result,
236
+ output_dir=output_dir,
237
+ cfg=cfg,
238
+ artifacts=artifacts,
239
+ )
240
+
241
+ frames = list(batch_result.frame_results)
242
+ if "tables" in artifacts and len(frames) > 1:
243
+ try:
244
+ summary_base = self._stack_base_name(frames, cfg)
245
+ summary_path = self._resolve_output_path(output_dir, summary_base, "_summary", ".csv", cfg)
246
+ self._write_batch_summary_csv(frames, summary_path)
247
+ written_files.append(summary_path)
248
+ except Exception as exc:
249
+ errors.append(
250
+ {
251
+ "frame_index": -1,
252
+ "frame_id": str(self._stack_base_name(frames, cfg)),
253
+ "artifact": "summary",
254
+ "error": str(exc),
255
+ }
256
+ )
257
+
258
+ manifest_path = None
259
+ if cfg.get("write_manifest", True):
260
+ manifest = {
261
+ "export_config": cfg,
262
+ "written_files": [os.path.relpath(p, output_dir) for p in written_files],
263
+ "written_count": len(written_files),
264
+ "skipped": skipped,
265
+ "errors": errors,
266
+ }
267
+ manifest_path = self._resolve_output_path(output_dir, "manifest", "", ".json", cfg)
268
+ with open(manifest_path, "w", encoding="utf-8") as handle:
269
+ json.dump(manifest, handle, indent=2)
270
+
271
+ return {
272
+ "output_dir": output_dir,
273
+ "written_files": written_files,
274
+ "written_count": len(written_files),
275
+ "skipped": skipped,
276
+ "errors": errors,
277
+ "manifest_path": manifest_path,
278
+ }
279
+
280
+ @staticmethod
281
+ def _skip_item(frame_index: int, artifact: str, reason: str) -> dict[str, Any]:
282
+ return {
283
+ "frame_index": int(frame_index),
284
+ "artifact": artifact,
285
+ "reason": reason,
286
+ }
287
+
288
+ def _save_framewise_artifacts(
289
+ self,
290
+ *,
291
+ batch_result,
292
+ output_dir: str,
293
+ cfg: dict[str, Any],
294
+ artifacts: set[str],
295
+ ) -> tuple[list[str], list[dict[str, Any]], list[dict[str, Any]]]:
296
+ written_files: list[str] = []
297
+ skipped: list[dict[str, Any]] = []
298
+ errors: list[dict[str, Any]] = []
299
+ image_ext = ".tiff" if cfg["image_format"] == "tiff" else ".png"
300
+
301
+ for frame_index, frame in enumerate(batch_result.frame_results):
302
+ frame = frame_at_original_scale(frame)
303
+ base_name = self._make_base_name(frame, frame_index, cfg)
304
+ for artifact in self._ALL_ARTIFACTS:
305
+ if artifact not in artifacts:
306
+ continue
307
+ try:
308
+ if artifact == "tables":
309
+ if frame.samples_table is None or len(frame.samples_table) == 0:
310
+ skipped.append(self._skip_item(frame_index, artifact, "missing_data"))
311
+ continue
312
+ path = self._resolve_output_path(output_dir, base_name, "_samples", ".csv", cfg)
313
+ self._write_samples_csv(frame, path)
314
+ written_files.append(path)
315
+ else:
316
+ array = self._ARRAYS[artifact](frame)
317
+ if array is None:
318
+ skipped.append(self._skip_item(frame_index, artifact, "missing_data"))
319
+ continue
320
+ ext = ".tiff" if artifact in ("dt", "foreground") else image_ext
321
+ path = self._resolve_output_path(output_dir, base_name, f"_{artifact}", ext, cfg)
322
+ iio.imwrite(path, array)
323
+ written_files.append(path)
324
+ except Exception as exc:
325
+ errors.append(
326
+ {
327
+ "frame_index": int(frame_index),
328
+ "frame_id": str(frame.frame_id),
329
+ "artifact": artifact,
330
+ "error": str(exc),
331
+ }
332
+ )
333
+
334
+ return written_files, skipped, errors
335
+
336
+ def _save_stack_artifacts(
337
+ self,
338
+ *,
339
+ batch_result,
340
+ output_dir: str,
341
+ cfg: dict[str, Any],
342
+ artifacts: set[str],
343
+ ) -> tuple[list[str], list[dict[str, Any]], list[dict[str, Any]]]:
344
+ """
345
+ Save stack sources as stack-level files.
346
+ Image artifacts are written as multi-page TIFF stacks.
347
+ """
348
+ written_files: list[str] = []
349
+ skipped: list[dict[str, Any]] = []
350
+ errors: list[dict[str, Any]] = []
351
+ frames = [frame_at_original_scale(frame) for frame in batch_result.frame_results]
352
+ if not frames:
353
+ return written_files, skipped, errors
354
+
355
+ base_name = self._stack_base_name(frames, cfg)
356
+
357
+ for artifact in self._ALL_ARTIFACTS:
358
+ if artifact not in artifacts:
359
+ continue
360
+ try:
361
+ if artifact == "tables":
362
+ if not any(
363
+ frame.samples_table is not None and len(frame.samples_table) > 0
364
+ for frame in frames
365
+ ):
366
+ skipped.append(self._skip_item(-1, artifact, "missing_data"))
367
+ continue
368
+ path = self._resolve_output_path(output_dir, base_name, "_samples", ".csv", cfg)
369
+ self._write_stack_samples_csv(frames, path)
370
+ written_files.append(path)
371
+ else:
372
+ arrays = [self._ARRAYS[artifact](frame) for frame in frames]
373
+ if any(array is None for array in arrays):
374
+ skipped.append(self._skip_item(-1, artifact, "missing_data"))
375
+ continue
376
+ path = self._resolve_output_path(output_dir, base_name, f"_{artifact}", ".tiff", cfg)
377
+ iio.imwrite(path, np.stack(arrays, axis=0))
378
+ written_files.append(path)
379
+ except Exception as exc:
380
+ errors.append(
381
+ {
382
+ "frame_index": -1,
383
+ "frame_id": str(base_name),
384
+ "artifact": artifact,
385
+ "error": str(exc),
386
+ }
387
+ )
388
+
389
+ return written_files, skipped, errors
390
+
391
+ def _stack_base_name(self, frames: list[Any], cfg: dict[str, Any]) -> str:
392
+ explicit_base = cfg.get("base_name")
393
+ if explicit_base:
394
+ return self._sanitize_name(str(explicit_base))
395
+
396
+ source_base_name = cfg.get("source_base_name")
397
+ if source_base_name:
398
+ return self._sanitize_name(str(source_base_name))
399
+
400
+ first_id = str(frames[0].frame_id or "").strip()
401
+ if first_id:
402
+ return self._sanitize_name(os.path.splitext(os.path.basename(first_id))[0])
403
+ return "stack"
404
+
405
+ @staticmethod
406
+ def _write_stack_samples_csv(frames: list[Any], path: str) -> None:
407
+ with open(path, "w", newline="") as handle:
408
+ handle.write("z_index,frame_id,x,y,diameter,angle_deg\n")
409
+ for frame in frames:
410
+ if frame.samples_table is None or len(frame.samples_table) == 0:
411
+ continue
412
+ z_index = int(frame.z_index)
413
+ frame_id = str(frame.frame_id)
414
+ thickness_units = frame.thickness_units
415
+ for sample_index, row in enumerate(frame.samples_table, start=1):
416
+ x, y, t_px = row[:3]
417
+ angle_val = float(row[3]) if len(row) > 3 else float("nan")
418
+ if thickness_units is not None and len(thickness_units) >= sample_index:
419
+ diameter_val = float(thickness_units[sample_index - 1])
420
+ else:
421
+ diameter_val = float(t_px)
422
+ handle.write(
423
+ f"{z_index},{frame_id},{int(x)},{int(y)},{diameter_val:.2f},{angle_val:.2f}\n"
424
+ )
425
+
426
+ def _write_batch_summary_csv(self, frames: list[Any], path: str) -> None:
427
+ """Write a one-row-per-frame summary table for multi-image batches."""
428
+ with open(path, "w", newline="") as handle:
429
+ writer = csv.writer(handle)
430
+ writer.writerow(
431
+ [
432
+ "frame_index",
433
+ "z_index",
434
+ "frame_id",
435
+ "diam_mean",
436
+ "diam_sd",
437
+ "diam_mode",
438
+ "diam_median",
439
+ "orientation_index",
440
+ "mean_angle_deg",
441
+ "std_angle_deg",
442
+ "porosity",
443
+ "sample_count",
444
+ "fragments_with_centerlines",
445
+ "units",
446
+ "has_segmentation",
447
+ "has_measurements",
448
+ ]
449
+ )
450
+ for frame_index, frame in enumerate(frames):
451
+ diam_mean, diam_sd, diam_mode, diam_median, orientation_index, mean_angle_deg, std_angle_deg, porosity, sample_count = (
452
+ self._measurement_summary_from_frame(frame)
453
+ )
454
+ summary = frame.fiber_summary or {}
455
+ fragments_with_centerlines = int(summary.get("fragments_with_centerlines", 0))
456
+ units = str(summary.get("units", "px"))
457
+ writer.writerow(
458
+ [
459
+ int(frame_index),
460
+ int(frame.z_index),
461
+ str(frame.frame_id),
462
+ f"{diam_mean:.2f}",
463
+ f"{diam_sd:.2f}",
464
+ f"{diam_mode:.2f}",
465
+ f"{diam_median:.2f}",
466
+ f"{orientation_index:.2f}",
467
+ f"{mean_angle_deg:.2f}",
468
+ f"{std_angle_deg:.2f}",
469
+ f"{porosity:.2f}",
470
+ int(sample_count),
471
+ fragments_with_centerlines,
472
+ units,
473
+ int(frame.has_segmentation),
474
+ int(frame.has_measurements),
475
+ ]
476
+ )
477
+
478
+ def _normalize_export_config(self, export_config: dict[str, Any]) -> dict[str, Any]:
479
+ """Normalize export config into a canonical representation.
480
+
481
+ Args:
482
+ export_config (dict[str, Any]): Configuration values controlling runtime behavior.
483
+
484
+ Returns:
485
+ dict[str, Any]: Mapping of computed keys and values.
486
+
487
+ Raises:
488
+ ValueError: If provided values fail domain validation checks."""
489
+ cfg = {
490
+ "preset": "full",
491
+ "image_format": "png",
492
+ "naming": "frame_id",
493
+ "collision": "suffix",
494
+ "layout": "frames",
495
+ "include": [],
496
+ "exclude": [],
497
+ "base_name": None,
498
+ "source_base_name": None,
499
+ "write_manifest": True,
500
+ }
501
+ cfg.update(export_config)
502
+
503
+ preset = str(cfg.get("preset", "full"))
504
+ if preset not in self._PRESET_ARTIFACTS:
505
+ raise ValueError(f"Unsupported preset: {preset}")
506
+ cfg["preset"] = preset
507
+
508
+ image_format = str(cfg.get("image_format", "png")).lower()
509
+ if image_format not in {"png", "tiff"}:
510
+ raise ValueError(f"Unsupported image_format: {image_format}")
511
+ cfg["image_format"] = image_format
512
+
513
+ naming = str(cfg.get("naming", "frame_id"))
514
+ if naming not in {"frame_id", "index"}:
515
+ raise ValueError(f"Unsupported naming: {naming}")
516
+ cfg["naming"] = naming
517
+
518
+ layout = str(cfg.get("layout", "frames")).lower()
519
+ if layout not in {"single", "frames", "stack"}:
520
+ raise ValueError(f"Unsupported layout: {layout}")
521
+ cfg["layout"] = layout
522
+
523
+ collision = str(cfg.get("collision", "suffix"))
524
+ if collision not in {"suffix", "overwrite", "error"}:
525
+ raise ValueError(f"Unsupported collision: {collision}")
526
+ cfg["collision"] = collision
527
+
528
+ include = cfg.get("include", [])
529
+ exclude = cfg.get("exclude", [])
530
+ if include is None:
531
+ include = []
532
+ if exclude is None:
533
+ exclude = []
534
+ cfg["include"] = [str(item).strip().lower() for item in include]
535
+ cfg["exclude"] = [str(item).strip().lower() for item in exclude]
536
+ cfg["source_base_name"] = (
537
+ str(cfg.get("source_base_name")).strip() if cfg.get("source_base_name") is not None else None
538
+ )
539
+ cfg["write_manifest"] = bool(cfg.get("write_manifest", True))
540
+ return cfg
541
+
542
+ def _resolve_artifacts(self, cfg: dict[str, Any]) -> set[str]:
543
+ artifacts = set(self._PRESET_ARTIFACTS[cfg["preset"]])
544
+ for artifact in cfg.get("include", []):
545
+ if artifact in self._ALL_ARTIFACTS:
546
+ artifacts.add(artifact)
547
+ for artifact in cfg.get("exclude", []):
548
+ artifacts.discard(artifact)
549
+ return artifacts
550
+
551
+ def _make_base_name(self, frame, index: int, cfg: dict[str, Any]) -> str:
552
+ explicit_base = cfg.get("base_name")
553
+ if explicit_base:
554
+ return self._sanitize_name(str(explicit_base))
555
+
556
+ naming = cfg.get("naming", "frame_id")
557
+ frame_id = self._sanitize_name(os.path.splitext(os.path.basename(str(frame.frame_id)))[0])
558
+
559
+ if naming == "index":
560
+ return f"frame_{index:04d}"
561
+ if not frame_id:
562
+ frame_id = f"frame_{index:04d}"
563
+ return frame_id
564
+
565
+ @staticmethod
566
+ def _sanitize_name(value: str) -> str:
567
+ clean = os.path.basename(value).strip()
568
+ return clean if clean else "frame"
569
+
570
+ def _resolve_output_path(
571
+ self,
572
+ output_dir: str,
573
+ base_name: str,
574
+ suffix: str,
575
+ extension: str,
576
+ cfg: dict[str, Any],
577
+ ) -> str:
578
+ candidate = os.path.join(output_dir, f"{base_name}{suffix}{extension}")
579
+ policy = cfg.get("collision", "suffix")
580
+ if policy == "overwrite" or not os.path.exists(candidate):
581
+ return candidate
582
+ if policy == "error":
583
+ raise FileExistsError(f"Output file already exists: {candidate}")
584
+
585
+ # suffix mode
586
+ i = 2
587
+ while True:
588
+ next_candidate = os.path.join(output_dir, f"{base_name}{suffix}_{i}{extension}")
589
+ if not os.path.exists(next_candidate):
590
+ return next_candidate
591
+ i += 1
592
+
593
+ def _write_samples_csv(self, frame, path: str) -> None:
594
+ diam_mean, diam_sd, diam_mode, diam_median, orientation_index, mean_angle_deg, std_angle_deg, porosity, sample_count = (
595
+ self._measurement_summary_from_frame(frame)
596
+ )
597
+
598
+ with open(path, "w", newline="") as handle:
599
+ summary = frame.fiber_summary or {}
600
+ fragments_with_centerlines = int(summary.get("fragments_with_centerlines", 0))
601
+ handle.write("metric,value\n")
602
+ handle.write(f"diam_mean,{diam_mean:.2f}\n")
603
+ handle.write(f"diam_sd,{diam_sd:.2f}\n")
604
+ handle.write(f"diam_mode,{diam_mode:.2f}\n")
605
+ handle.write(f"diam_median,{diam_median:.2f}\n")
606
+ handle.write(f"orientation_index,{orientation_index:.2f}\n")
607
+ handle.write(f"mean_angle_deg,{mean_angle_deg:.2f}\n")
608
+ handle.write(f"std_angle_deg,{std_angle_deg:.2f}\n")
609
+ handle.write(f"porosity,{porosity:.2f}\n")
610
+ handle.write(f"sample_number,{sample_count}\n")
611
+ handle.write(f"fragments_with_centerlines,{fragments_with_centerlines}\n")
612
+ handle.write("\n\n")
613
+ handle.write("x,y,diameter,angle_deg\n")
614
+
615
+ thickness_units = frame.thickness_units
616
+ for idx, row in enumerate(frame.samples_table, start=1):
617
+ x, y, t_px = row[:3]
618
+ angle_val = float(row[3]) if len(row) > 3 else float("nan")
619
+ if thickness_units is not None and len(thickness_units) >= idx:
620
+ diameter_val = float(thickness_units[idx - 1])
621
+ else:
622
+ diameter_val = float(t_px)
623
+ handle.write(f"{int(x)},{int(y)},{diameter_val:.2f},{angle_val:.2f}\n")
624
+
625
+ def _measurement_summary_from_frame(
626
+ self, frame
627
+ ) -> tuple[float, float, float, float, float, float, float, float, int]:
628
+ summary = frame.fiber_summary or {}
629
+ return (
630
+ float(summary.get("diam_mean", float("nan"))),
631
+ float(summary.get("diam_sd", float("nan"))),
632
+ float(summary.get("diam_mode", float("nan"))),
633
+ float(summary.get("diam_median", float("nan"))),
634
+ float(summary.get("orientation_index", float("nan"))),
635
+ float(summary.get("mean_angle_deg", float("nan"))),
636
+ float(summary.get("std_angle_deg", float("nan"))),
637
+ float(summary.get("porosity", float("nan"))),
638
+ int(summary.get("sample_count", 0)),
639
+ )
src/fiberpose/ml.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ONNX Runtime inference wrapper for Fiberpose models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from typing import Any, Optional
8
+
9
+ import numpy as np
10
+ import onnxruntime as ort
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def get_available_providers() -> list[str]:
16
+ """Return providers reported by the local ONNX Runtime build."""
17
+ try:
18
+ return list(ort.get_available_providers())
19
+ except Exception:
20
+ logger.exception("Failed to query ONNX Runtime providers")
21
+ return ["CPUExecutionProvider"]
22
+
23
+
24
+ def onnx_cuda_available() -> bool:
25
+ """Return whether ONNX Runtime exposes CUDAExecutionProvider."""
26
+ return "CUDAExecutionProvider" in get_available_providers()
27
+
28
+
29
+ def _resolve_providers(device: Optional[str]) -> list[str]:
30
+ requested = str(device or "cpu").strip().lower()
31
+ available = get_available_providers()
32
+
33
+ if requested == "cuda":
34
+ if "CUDAExecutionProvider" in available:
35
+ return ["CUDAExecutionProvider", "CPUExecutionProvider"]
36
+ logger.warning("Requested CUDA but CUDAExecutionProvider is unavailable; falling back to CPU.")
37
+ return ["CPUExecutionProvider"]
38
+
39
+
40
+ class OnnxFiberposeModel:
41
+ """ONNX-only inference wrapper used by runtime analysis."""
42
+
43
+ def __init__(
44
+ self,
45
+ model_path: str,
46
+ *,
47
+ device: str = "cpu",
48
+ nout: int | None = None,
49
+ nbase: str = "1,32,64,128,256",
50
+ stride: int | None = None,
51
+ **_: Any,
52
+ ):
53
+ if not os.path.isfile(model_path):
54
+ raise FileNotFoundError(f"Model not found: {model_path}")
55
+
56
+ providers = _resolve_providers(device)
57
+ self.device = "cuda" if providers and providers[0] == "CUDAExecutionProvider" else "cpu"
58
+ self.providers = providers
59
+ self.session = ort.InferenceSession(model_path, providers=providers)
60
+
61
+ inputs = self.session.get_inputs()
62
+ if not inputs:
63
+ raise ValueError(f"ONNX model has no inputs: {model_path}")
64
+ self.input_name = str(inputs[0].name)
65
+ self.input_channels = self._infer_input_channels(inputs[0].shape)
66
+
67
+ self.output_name = str(self.session.get_outputs()[0].name)
68
+ self.nout = int(nout) if nout is not None else None
69
+
70
+ self.nbase_str = nbase
71
+ self.stride = int(stride) if stride is not None else self._infer_stride_from_nbase(nbase)
72
+
73
+ logger.info(
74
+ "Loaded ONNX model '%s' with providers=%s input='%s' output='%s' stride=%d",
75
+ model_path,
76
+ providers,
77
+ self.input_name,
78
+ self.output_name,
79
+ self.stride,
80
+ )
81
+
82
+ @staticmethod
83
+ def _infer_input_channels(shape: Any) -> int:
84
+ if isinstance(shape, (list, tuple)) and len(shape) >= 2:
85
+ ch = shape[1]
86
+ if isinstance(ch, int) and ch > 0:
87
+ return int(ch)
88
+ return 1
89
+
90
+ @staticmethod
91
+ def _infer_stride_from_nbase(nbase: str) -> int:
92
+ try:
93
+ levels = [int(p.strip()) for p in str(nbase).split(",") if p.strip()]
94
+ downs = max(0, len(levels) - 1)
95
+ return int(2 ** downs)
96
+ except Exception:
97
+ return 16
98
+
99
+ def predict(self, img: np.ndarray) -> tuple[np.ndarray, np.ndarray | None]:
100
+ """Return `(dt, foreground_prob)`, with foreground only for `nout == 2`."""
101
+ arr = self._prep_input(img, self.input_channels)
102
+ x = arr[None, ...].astype(np.float32, copy=False)
103
+ outputs = self.session.run([self.output_name], {self.input_name: x})
104
+ if not outputs:
105
+ raise RuntimeError("ONNX Runtime returned no outputs.")
106
+ y = np.asarray(outputs[0])
107
+ if y.ndim != 4:
108
+ raise ValueError(f"Unexpected ONNX output shape: {y.shape}")
109
+
110
+ resolved_nout = int(self.nout) if self.nout is not None else int(y.shape[1])
111
+ if resolved_nout <= 0:
112
+ raise ValueError(f"Unsupported output channel count: nout={resolved_nout}")
113
+ dt_channel = 1 if resolved_nout == 2 else resolved_nout - 1
114
+ if y.shape[1] <= dt_channel:
115
+ raise ValueError(
116
+ "Predicted tensor channel count is incompatible with DT channel selection: "
117
+ f"got shape={y.shape}, selected_channel={dt_channel}"
118
+ )
119
+
120
+ foreground_prob = None
121
+ if resolved_nout == 2:
122
+ foreground_prob = np.asarray(y[0, 0], dtype=np.float32)
123
+
124
+ return np.asarray(y[0, dt_channel], dtype=np.float32), foreground_prob
125
+
126
+ @staticmethod
127
+ def _prep_input(x: np.ndarray, in_channels: int) -> np.ndarray:
128
+ if x.ndim == 2:
129
+ arr = x.astype(np.float32)[None, ...]
130
+ elif x.ndim == 3:
131
+ if x.shape[2] == in_channels:
132
+ arr = np.transpose(x, (2, 0, 1)).astype(np.float32)
133
+ elif in_channels == 1:
134
+ if x.shape[2] >= 3:
135
+ r, g, b = x[..., 0], x[..., 1], x[..., 2]
136
+ gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
137
+ arr = gray.astype(np.float32)[None, ...]
138
+ else:
139
+ arr = x[..., 0:1].astype(np.float32).transpose(2, 0, 1)
140
+ elif in_channels == 3:
141
+ if x.shape[2] == 1:
142
+ arr = np.repeat(x, 3, axis=2).astype(np.float32).transpose(2, 0, 1)
143
+ else:
144
+ arr = x[..., :3].astype(np.float32).transpose(2, 0, 1)
145
+ else:
146
+ raise ValueError(
147
+ f"Unsupported channel adaptation: in_channels={in_channels}, x.shape={x.shape}"
148
+ )
149
+ else:
150
+ raise ValueError(f"Unsupported input shape: {x.shape}")
151
+
152
+ vmin = float(np.min(arr))
153
+ vmax = float(np.max(arr))
154
+ if vmax > vmin:
155
+ arr = (arr - vmin) / (vmax - vmin + 1e-12)
156
+ else:
157
+ arr = np.zeros_like(arr, dtype=np.float32)
158
+
159
+ return arr.astype(np.float32, copy=False)
src/fiberpose/models.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Locate, download and cache pretrained Fiberpose models.
2
+
3
+ Weights are not shipped in the wheel. Models are looked up by file name in
4
+ ``models_dir()``; registered models missing there are downloaded from the
5
+ release assets on first use and verified against the hashes below.
6
+
7
+ Environment overrides:
8
+ FIBERPOSE_MODELS_DIR folder with .onnx models (and where downloads go)
9
+ FIBERPOSE_MODEL path to the .onnx file used when no model is configured
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from pathlib import Path
16
+
17
+ import pooch
18
+
19
+ DEFAULT_MODEL = "R108_dt_fg.onnx"
20
+
21
+ # TODO: upload the registered files as assets of this release before publishing.
22
+ _BASE_URL = "https://github.com/vikba/Fiberpose/releases/download/models-v1/"
23
+
24
+ # Model file -> files to download; external-data files (.onnx.data) must sit
25
+ # next to their .onnx graph.
26
+ _MODELS: dict[str, tuple[str, ...]] = {
27
+ "R108_dt_fg.onnx": ("R108_dt_fg.onnx",),
28
+ }
29
+
30
+ _REGISTRY = {
31
+ "R108_dt_fg.onnx": "sha256:bb515be44e1daa220f8ba457fb1f9d856a2c3865149f4b6b97e12aefdea37536",
32
+ }
33
+
34
+ _LEGACY_PREFIX = "checkpoints/"
35
+
36
+
37
+ def models_dir() -> Path:
38
+ """Folder that holds .onnx models.
39
+
40
+ Order: ``$FIBERPOSE_MODELS_DIR``, then ``<repo>/checkpoints`` when running
41
+ from a source checkout, then the per-user download cache.
42
+ """
43
+ override = os.environ.get("FIBERPOSE_MODELS_DIR")
44
+ if override:
45
+ return Path(override).expanduser()
46
+ repo_root = Path(__file__).resolve().parents[2]
47
+ checkout_models = repo_root / "checkpoints"
48
+ if (repo_root / "pyproject.toml").is_file() and checkout_models.is_dir():
49
+ return checkout_models
50
+ return Path(pooch.os_cache("fiberpose")) / "models"
51
+
52
+
53
+ def normalize_model_entry(entry: str | None) -> str:
54
+ """Strip the legacy ``checkpoints/`` prefix used by older configs."""
55
+ entry = str(entry or "").strip().replace("\\", "/")
56
+ if entry.startswith(_LEGACY_PREFIX):
57
+ entry = entry[len(_LEGACY_PREFIX):]
58
+ return entry
59
+
60
+
61
+ def discover_models() -> list[str]:
62
+ """File names of the .onnx models available in ``models_dir()``, plus registered ones."""
63
+ folder = models_dir()
64
+ local = sorted(p.name for p in folder.glob("*.onnx")) if folder.is_dir() else []
65
+ return local + [name for name in _MODELS if name not in local]
66
+
67
+
68
+ def resolve_model_path(entry: str | None = None) -> str:
69
+ """Map a config/GUI model entry to an absolute path, downloading it if needed.
70
+
71
+ An empty entry means the default model (or ``$FIBERPOSE_MODEL`` if set).
72
+ Absolute paths are returned unchanged; names are looked up in ``models_dir()``.
73
+ """
74
+ name = normalize_model_entry(entry)
75
+ if not name:
76
+ override = os.environ.get("FIBERPOSE_MODEL")
77
+ if override:
78
+ return str(Path(override).expanduser())
79
+ name = DEFAULT_MODEL
80
+ if os.path.isabs(name):
81
+ return name
82
+ local = models_dir() / name
83
+ if local.is_file() or name not in _MODELS:
84
+ return str(local)
85
+ return fetch_model(name)
86
+
87
+
88
+ def fetch_model(name: str = DEFAULT_MODEL) -> str:
89
+ """Download a registered model into ``models_dir()`` and return its path."""
90
+ if name not in _MODELS:
91
+ raise ValueError(f"Unknown model {name!r}; registered: {', '.join(_MODELS)}")
92
+ fetcher = pooch.create(path=models_dir(), base_url=_BASE_URL, registry=_REGISTRY)
93
+ paths = [fetcher.fetch(fname) for fname in _MODELS[name]]
94
+ return paths[0]
src/fiberpose/paths.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filesystem locations used by Fiberpose.
2
+
3
+ Bundled resources live inside the package and are read-only once installed.
4
+ Anything Fiberpose writes (the user config) goes to the per-user config folder.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import shutil
10
+ from pathlib import Path
11
+
12
+ from platformdirs import user_config_dir
13
+
14
+ PACKAGE_DIR = Path(__file__).resolve().parent
15
+ RESOURCES_DIR = PACKAGE_DIR / "resources"
16
+
17
+ DEFAULT_UI_PATH = RESOURCES_DIR / "fiber_tool.ui"
18
+ DARK_THEME_PATH = RESOURCES_DIR / "dark_theme.qss"
19
+ APP_ICON_PATH = RESOURCES_DIR / "fiberpose.png"
20
+ EXAMPLE_IMAGE_PATH = RESOURCES_DIR / "test.png"
21
+ BUNDLED_CONFIG_PATH = RESOURCES_DIR / "config.json"
22
+
23
+ USER_CONFIG_PATH = Path(user_config_dir("fiberpose", appauthor=False)) / "config.json"
24
+
25
+
26
+ def default_config_path() -> str:
27
+ """Return the user config path, creating it from the bundled default on first use."""
28
+ if not USER_CONFIG_PATH.exists():
29
+ USER_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
30
+ shutil.copyfile(BUNDLED_CONFIG_PATH, USER_CONFIG_PATH)
31
+ return str(USER_CONFIG_PATH)
src/fiberpose/pipeline.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pipeline orchestration for frame and batch processing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from dataclasses import dataclass
8
+ from typing import Any, Callable
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ from . import analysis
14
+ from .domain import AppConfig, BatchResult, Frame, ImageBatch, SampleProperties
15
+ from .ml import OnnxFiberposeModel
16
+
17
+ # Config fields passed to `analysis.segment`; changing any of them invalidates the segmentation.
18
+ _SEGMENTATION_FIELDS = (
19
+ "segmentation_mode",
20
+ "watershed_grad_threshold",
21
+ "min_segment_foreground_mean",
22
+ "max_angle_deg",
23
+ "ridge_sigma",
24
+ "ridge_low",
25
+ "ridge_high",
26
+ "strict_centerlines",
27
+ "keep_segments_without_measurement_centerlines",
28
+ "merge_expansion_factor",
29
+ "segmentation_expansion_factor",
30
+ "min_fragment_centerline_length_px",
31
+ "measurement_centerline_length_trim_fraction",
32
+ "grad_quality_trim_fraction",
33
+ )
34
+
35
+
36
+ @dataclass
37
+ class PipelineOutcome:
38
+ """Result envelope for pipeline stage execution."""
39
+
40
+ ok: bool
41
+ error_title: str | None = None
42
+ error_message: str | None = None
43
+ info_title: str | None = None
44
+ info_message: str | None = None
45
+
46
+
47
+ class PipelineController:
48
+ """Runs prediction -> segmentation -> measurement on a `Frame`, caching each stage on the frame.
49
+
50
+ The only state kept here is the loaded model; all image results live on the frame.
51
+ """
52
+
53
+ def __init__(self, model_path: str | None = None, device: str = "cpu"):
54
+ self.model_path = model_path
55
+ self.device = device
56
+ self._model: OnnxFiberposeModel | None = None
57
+
58
+ def set_model(self, model_path: str | None, device: str) -> None:
59
+ """Select the model; it is loaded on the next prediction."""
60
+ if (model_path, device) != (self.model_path, self.device):
61
+ self.model_path, self.device, self._model = model_path, device, None
62
+
63
+ @staticmethod
64
+ def _effective_scale_factor(config: AppConfig) -> float:
65
+ token = str(config.scale_label or "1x").strip().lower().replace("×", "x")
66
+ if token.endswith("x"):
67
+ token = token[:-1]
68
+ try:
69
+ scale = float(token)
70
+ except Exception:
71
+ scale = 1.0
72
+ if not np.isfinite(scale) or scale <= 0:
73
+ return 1.0
74
+ return float(scale)
75
+
76
+ def _processing_image(self, frame: Frame, config: AppConfig) -> np.ndarray | None:
77
+ image = frame.orig_img
78
+ if image is None:
79
+ return None
80
+
81
+ scale = self._effective_scale_factor(config)
82
+ if math.isclose(scale, 1.0, rel_tol=1e-9, abs_tol=1e-9):
83
+ frame.scale_factor = 1.0
84
+ frame.orig_img_scaled = None
85
+ return image
86
+
87
+ needs_rescale = (
88
+ frame.orig_img_scaled is None
89
+ or not math.isclose(float(frame.scale_factor), float(scale), rel_tol=1e-9, abs_tol=1e-9)
90
+ )
91
+ if needs_rescale:
92
+ interp = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_CUBIC
93
+ frame.orig_img_scaled = cv2.resize(
94
+ image,
95
+ None,
96
+ fx=float(scale),
97
+ fy=float(scale),
98
+ interpolation=interp,
99
+ )
100
+ frame.scale_factor = float(scale)
101
+ return frame.orig_img_scaled
102
+
103
+ @staticmethod
104
+ def _image_for_inference(image: np.ndarray | None, invert_input: bool) -> np.ndarray | None:
105
+ if image is None or not bool(invert_input):
106
+ return image
107
+ try:
108
+ return cv2.bitwise_not(image)
109
+ except Exception:
110
+ return np.max(image) - image
111
+
112
+ @staticmethod
113
+ def segmentation_params(config: AppConfig) -> dict[str, Any]:
114
+ return {name: getattr(config, name) for name in _SEGMENTATION_FIELDS}
115
+
116
+ @staticmethod
117
+ def measurement_params(config: AppConfig) -> dict[str, Any]:
118
+ return {
119
+ "sample_spacing": max(1.0, float(config.sample_spacing)),
120
+ "seg_threshold": int(config.seg_threshold),
121
+ }
122
+
123
+ @classmethod
124
+ def prediction_signature(cls, frame: Frame, config: AppConfig, *, invert_input: bool) -> str | None:
125
+ image = frame.orig_img
126
+ if image is None:
127
+ return None
128
+ payload = {
129
+ "image_id": int(id(image)),
130
+ "shape": tuple(int(v) for v in image.shape),
131
+ "dtype": str(image.dtype),
132
+ "model_path": str(config.model_path),
133
+ "invert_input": bool(invert_input),
134
+ "scale_factor": float(cls._effective_scale_factor(config)),
135
+ }
136
+ return json.dumps(payload, sort_keys=True, default=str)
137
+
138
+ @classmethod
139
+ def segmentation_signature(cls, frame: Frame, config: AppConfig, *, invert_input: bool) -> str | None:
140
+ prediction_sig = cls.prediction_signature(frame, config, invert_input=invert_input)
141
+ if prediction_sig is None:
142
+ return None
143
+ payload = {
144
+ "prediction_sig": prediction_sig,
145
+ "segmentation_params": cls.segmentation_params(config),
146
+ }
147
+ return json.dumps(payload, sort_keys=True, default=str)
148
+
149
+ @classmethod
150
+ def measurement_signature(
151
+ cls,
152
+ frame: Frame,
153
+ config: AppConfig,
154
+ sample_props: SampleProperties,
155
+ *,
156
+ invert_input: bool,
157
+ ) -> str | None:
158
+ segmentation_sig = cls.segmentation_signature(frame, config, invert_input=invert_input)
159
+ if segmentation_sig is None:
160
+ return None
161
+ props = sample_props if sample_props is not None else SampleProperties.defaults()
162
+ payload = {
163
+ "segmentation_sig": segmentation_sig,
164
+ "measurement_params": cls.measurement_params(config),
165
+ "pixel_size_x": float(props.pixel_size_x),
166
+ "pixel_size_y": float(props.pixel_size_y),
167
+ "voxel_size_z": float(props.voxel_size_z),
168
+ "unit": str(props.unit),
169
+ }
170
+ return json.dumps(payload, sort_keys=True, default=str)
171
+
172
+ @staticmethod
173
+ def _compute_orientation_stats(angles_samples_deg: np.ndarray) -> tuple[float, float, float]:
174
+ if angles_samples_deg is None or getattr(angles_samples_deg, "size", 0) == 0:
175
+ return float("nan"), float("nan"), float("nan")
176
+
177
+ angles_rad = np.deg2rad(2.0 * angles_samples_deg)
178
+ mean_cos = float(np.mean(np.cos(angles_rad)))
179
+ mean_sin = float(np.mean(np.sin(angles_rad)))
180
+ orientation_index = float(np.clip(np.hypot(mean_cos, mean_sin), 0.0, 1.0))
181
+
182
+ mean_angle_rad = 0.5 * float(np.arctan2(mean_sin, mean_cos))
183
+ mean_angle_deg = float(np.rad2deg(mean_angle_rad))
184
+ if mean_angle_deg <= -90.0:
185
+ mean_angle_deg += 180.0
186
+
187
+ if orientation_index > 0 and np.isfinite(orientation_index):
188
+ r = float(np.clip(orientation_index, 1e-8, 1.0))
189
+ std_angle_rad = float(np.sqrt(max(0.0, -2.0 * np.log(r))))
190
+ std_angle_deg = 0.5 * float(np.rad2deg(std_angle_rad))
191
+ else:
192
+ std_angle_deg = float("nan")
193
+
194
+ return orientation_index, mean_angle_deg, std_angle_deg
195
+
196
+ def _build_measurement_outputs(
197
+ self,
198
+ *,
199
+ measurement_samples: list[Any],
200
+ pores: list[dict[str, Any]],
201
+ porosity: float,
202
+ pixel_size: float,
203
+ units_label: str,
204
+ pore_scale: float,
205
+ fragments_with_centerlines: int,
206
+ ) -> dict[str, Any]:
207
+ if measurement_samples:
208
+ radii_px = np.array([sample[4] for sample in measurement_samples], dtype=np.float32)
209
+ angles_arr = np.array([sample[5] for sample in measurement_samples], dtype=np.float32)
210
+ thickness_px = 2.0 * radii_px
211
+ thickness_units = thickness_px * float(pixel_size)
212
+ xs = np.array([sample[1] for sample in measurement_samples], dtype=np.int32)
213
+ ys = np.array([sample[0] for sample in measurement_samples], dtype=np.int32)
214
+ samples_table = np.column_stack([xs, ys, thickness_px, angles_arr]).astype(object)
215
+ else:
216
+ angles_arr = np.array([], dtype=np.float32)
217
+ thickness_units = np.array([], dtype=np.float32)
218
+ samples_table = None
219
+
220
+ angles_arr = angles_arr[np.isfinite(angles_arr)] if angles_arr.size else angles_arr
221
+ safe_scale = float(pore_scale) if np.isfinite(pore_scale) and pore_scale > 0 else 1.0
222
+ pore_diams_units = np.array(
223
+ [2.0 * p.get("r_px_orig", p["r_px"] / safe_scale) * float(pixel_size) for p in pores],
224
+ dtype=np.float32,
225
+ )
226
+
227
+ if thickness_units.size:
228
+ diam_mean = float(np.mean(thickness_units))
229
+ diam_sd = float(np.std(thickness_units))
230
+ diam_median = float(np.median(thickness_units))
231
+ if np.ptp(thickness_units) == 0:
232
+ diam_mode = float(thickness_units[0])
233
+ else:
234
+ hist, edges = np.histogram(thickness_units, bins=40)
235
+ peak = int(np.argmax(hist))
236
+ diam_mode = float((edges[peak] + edges[peak + 1]) / 2.0)
237
+ else:
238
+ diam_mean = diam_sd = diam_mode = diam_median = float("nan")
239
+
240
+ orientation_index, mean_angle_deg, std_angle_deg = self._compute_orientation_stats(angles_arr)
241
+
242
+ fiber_summary = {
243
+ "diam_mean": diam_mean,
244
+ "diam_sd": diam_sd,
245
+ "diam_mode": diam_mode,
246
+ "diam_median": diam_median,
247
+ "orientation_index": float(orientation_index),
248
+ "mean_angle_deg": float(mean_angle_deg),
249
+ "std_angle_deg": float(std_angle_deg),
250
+ "porosity": float(porosity),
251
+ "sample_count": len(measurement_samples),
252
+ "fragments_with_centerlines": int(fragments_with_centerlines),
253
+ "units": units_label,
254
+ }
255
+ return {
256
+ "samples_table": samples_table,
257
+ "thickness_units": thickness_units,
258
+ "pore_diams_units": pore_diams_units,
259
+ "fiber_summary": fiber_summary,
260
+ }
261
+
262
+ def measure(self, frame: Frame, config: AppConfig, sample_props: SampleProperties) -> dict[str, Any]:
263
+ measurement_params = self.measurement_params(config)
264
+ spacing_px_input = float(measurement_params["sample_spacing"])
265
+ current_scale = frame.scale_factor if frame.scale_factor and np.isfinite(frame.scale_factor) else 1.0
266
+ spacing_px_scaled = max(1.0, spacing_px_input * current_scale)
267
+ pixel_size = sample_props.effective_pixel_size_xy()
268
+ units_label = sample_props.unit if sample_props.unit else "px"
269
+
270
+ measurement_samples, drawing_samples = analysis.sample_centerlines(
271
+ frame.dt, frame.gx, frame.gy, frame.fragments, spacing_px=spacing_px_scaled, scale_factor=frame.scale_factor
272
+ )
273
+ void_mask, pore_dt = analysis.void_mask_and_pore_dt(frame.dt_u8, int(measurement_params["seg_threshold"]))
274
+ porosity = float(void_mask.mean())
275
+ pores = analysis.sample_inscribed_circles(
276
+ pore_dt=pore_dt,
277
+ void_mask=void_mask,
278
+ scale_factor=frame.scale_factor,
279
+ min_radius_px=1.5 * current_scale,
280
+ min_peak_px=3.0 * current_scale,
281
+ peak_footprint=5,
282
+ )
283
+
284
+ outputs = self._build_measurement_outputs(
285
+ measurement_samples=measurement_samples,
286
+ pores=pores,
287
+ porosity=porosity,
288
+ pixel_size=pixel_size,
289
+ units_label=units_label,
290
+ pore_scale=frame.scale_factor,
291
+ fragments_with_centerlines=sum(f.has_measurement_centerline for f in frame.fragments),
292
+ )
293
+ outputs.update(
294
+ {
295
+ "measurement_samples": measurement_samples,
296
+ "drawing_samples": drawing_samples,
297
+ "porosity": porosity,
298
+ "void_mask": void_mask,
299
+ "pore_dt": pore_dt,
300
+ "pores": pores,
301
+ }
302
+ )
303
+ return outputs
304
+
305
+ def ensure_prediction(self, frame: Frame, config: AppConfig, *, invert_input: bool) -> PipelineOutcome:
306
+ if frame.orig_img is None:
307
+ return PipelineOutcome(False, info_title="Load original", info_message="Load an image before using this operation.")
308
+
309
+ target_sig = self.prediction_signature(frame, config, invert_input=invert_input)
310
+ if frame.has_prediction and frame.prediction_sig == target_sig:
311
+ return PipelineOutcome(True)
312
+
313
+ try:
314
+ if self._model is None:
315
+ self._model = OnnxFiberposeModel(str(self.model_path), device=self.device)
316
+ image = self._image_for_inference(self._processing_image(frame, config), invert_input=invert_input)
317
+ prediction = analysis.predict(self._model, image)
318
+ except Exception as exc:
319
+ frame.fail(str(exc))
320
+ return PipelineOutcome(False, error_title="Prediction failed", error_message=str(exc))
321
+
322
+ frame.set_prediction_outputs(**prediction, orig_img_scaled=frame.orig_img_scaled, scale_factor=frame.scale_factor)
323
+ frame.prediction_sig = target_sig
324
+ return PipelineOutcome(True)
325
+
326
+ def ensure_segmentation(self, frame: Frame, config: AppConfig, *, invert_input: bool) -> PipelineOutcome:
327
+ frame.error_message = None
328
+ ready = self.ensure_prediction(frame, config, invert_input=invert_input)
329
+ if not ready.ok:
330
+ return ready
331
+ target_sig = self.segmentation_signature(frame, config, invert_input=invert_input)
332
+ if frame.has_segmentation and frame.segmentation_sig == target_sig:
333
+ return PipelineOutcome(True)
334
+
335
+ frame.clear_segmentation()
336
+ try:
337
+ labels, fragments = analysis.segment(
338
+ frame.dt, frame.dt_u8, frame.gx, frame.gy, frame.foreground_prob, **self.segmentation_params(config)
339
+ )
340
+ except Exception as exc:
341
+ frame.fail(str(exc))
342
+ return PipelineOutcome(False, error_title="Segmentation failed", error_message=str(exc))
343
+
344
+ frame.set_segmentation_outputs(labels_2d=labels, fragments=fragments)
345
+ frame.segmentation_sig = target_sig
346
+ return PipelineOutcome(True)
347
+
348
+ def ensure_measurements(
349
+ self,
350
+ frame: Frame,
351
+ config: AppConfig,
352
+ sample_props: SampleProperties,
353
+ *,
354
+ invert_input: bool,
355
+ ) -> PipelineOutcome:
356
+ target_sig = self.measurement_signature(frame, config, sample_props, invert_input=invert_input)
357
+ if target_sig is not None and frame.has_measurements and frame.measurement_sig == target_sig:
358
+ return PipelineOutcome(True)
359
+
360
+ segmentation_ready = self.ensure_segmentation(frame, config, invert_input=invert_input)
361
+ if not segmentation_ready.ok:
362
+ return segmentation_ready
363
+
364
+ frame.clear_measurements()
365
+ if not any(f.has_measurement_centerline for f in frame.fragments):
366
+ return PipelineOutcome(False, info_title="No centerlines", info_message="No measurement centerlines available.")
367
+
368
+ try:
369
+ outputs = self.measure(frame=frame, config=config, sample_props=sample_props)
370
+ except Exception as exc:
371
+ frame.fail(str(exc))
372
+ return PipelineOutcome(False, error_title="Analysis failed", error_message=str(exc))
373
+
374
+ frame.set_measurement_outputs(**outputs)
375
+ frame.measurement_sig = target_sig
376
+ return PipelineOutcome(True)
377
+
378
+
379
+ @dataclass
380
+ class BatchCallbacks:
381
+ """Callbacks invoked during batch run."""
382
+
383
+ on_started: Callable[[int], None]
384
+ on_frame_started: Callable[[int, int], None]
385
+ on_frame_finished: Callable[[int, int, Frame], None]
386
+ on_finished: Callable[[BatchResult], None]
387
+
388
+
389
+ class BatchService:
390
+ """Runs frame processing over an `ImageBatch` and assembles results."""
391
+
392
+ def run_batch(
393
+ self,
394
+ image_batch: ImageBatch,
395
+ compute_measurements: bool,
396
+ process_frame: Callable[[np.ndarray, str, int, Frame | None, bool], Frame],
397
+ callbacks: BatchCallbacks,
398
+ cached_result: BatchResult | None = None,
399
+ ) -> BatchResult:
400
+ total_images = len(image_batch)
401
+ callbacks.on_started(total_images)
402
+
403
+ z_indices = image_batch.metadata.get("z_indices", list(range(total_images)))
404
+ filenames = image_batch.metadata.get("filenames", [str(i) for i in range(total_images)])
405
+
406
+ results: list[Frame] = []
407
+
408
+ for idx, frame in enumerate(image_batch.frames):
409
+ frame_id = str(filenames[idx]) if idx < len(filenames) else str(idx)
410
+ z_index = int(z_indices[idx]) if idx < len(z_indices) else idx
411
+ callbacks.on_frame_started(idx, total_images)
412
+ cached_frame = None
413
+ if cached_result is not None and 0 <= int(z_index) < len(cached_result.frame_results):
414
+ cached_frame = cached_result.frame_at(int(z_index))
415
+ result = process_frame(frame, frame_id, z_index, cached_frame, compute_measurements)
416
+ results.append(result)
417
+ callbacks.on_frame_finished(idx + 1, total_images, result)
418
+
419
+ batch_result = BatchResult(frame_results=results)
420
+ callbacks.on_finished(batch_result)
421
+ return batch_result
src/fiberpose/raster.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vectorized disk rasterization that reproduces ``cv2.circle`` exactly.
2
+
3
+ Several pipeline stages need "the pixels covered by filled circles drawn along a
4
+ polyline". Drawing each circle into a full-size mask makes those stages cost
5
+ O(objects x image area). The helpers here return pixel indices instead, so the
6
+ cost is proportional to the covered area only.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from functools import lru_cache
12
+
13
+ import cv2
14
+ import numpy as np
15
+
16
+ # Upper bound on (points x stencil pixels) materialized at once by stamp_disks.
17
+ _STAMP_CHUNK = 1 << 22
18
+
19
+
20
+ @lru_cache(maxsize=None)
21
+ def disk_mask(radius: int) -> np.ndarray:
22
+ """Boolean (2r+1, 2r+1) mask of the pixels ``cv2.circle(..., thickness=-1)`` fills."""
23
+ radius = int(radius)
24
+ canvas = np.zeros((2 * radius + 1, 2 * radius + 1), dtype=np.uint8)
25
+ cv2.circle(canvas, (radius, radius), radius, 1, thickness=-1)
26
+ mask = canvas.astype(bool)
27
+ mask.flags.writeable = False
28
+ return mask
29
+
30
+
31
+ @lru_cache(maxsize=None)
32
+ def disk_offsets(radius: int) -> tuple[np.ndarray, np.ndarray]:
33
+ """(dy, dx) offsets of the pixels in ``disk_mask(radius)`` relative to its center."""
34
+ dy, dx = np.nonzero(disk_mask(radius))
35
+ dy = dy - int(radius)
36
+ dx = dx - int(radius)
37
+ dy.flags.writeable = False
38
+ dx.flags.writeable = False
39
+ return dy, dx
40
+
41
+
42
+ def disk_radii(radii: np.ndarray, expansion: float) -> np.ndarray:
43
+ """Integer disk radii ``max(1, round(radius * expansion))`` (round half to even, like ``round``)."""
44
+ scaled = np.asarray(radii, dtype=np.float64) * float(expansion)
45
+ return np.maximum(1, np.rint(scaled).astype(np.int64))
46
+
47
+
48
+ def stamp_disks(
49
+ points_xy: np.ndarray,
50
+ radii_px: np.ndarray,
51
+ owners: np.ndarray,
52
+ shape: tuple[int, int],
53
+ ) -> tuple[np.ndarray, np.ndarray]:
54
+ """Pixels covered by filled disks, as unique ``(pixel, owner)`` pairs.
55
+
56
+ Each point ``i`` contributes a disk of integer radius ``radii_px[i]`` centered at
57
+ ``round(points_xy[i])`` and attributed to ``owners[i]`` (a non-negative id). Centers outside the image
58
+ are skipped and disks are clipped at the image border, matching a loop of
59
+ ``cv2.circle`` calls on an image of ``shape``.
60
+
61
+ Returns flat pixel indices (``y * width + x``) and owner ids, sorted by owner then pixel.
62
+ """
63
+ h, w = int(shape[0]), int(shape[1])
64
+ pts = np.asarray(points_xy, dtype=np.float64).reshape(-1, 2)
65
+ cx = np.rint(pts[:, 0]).astype(np.int64)
66
+ cy = np.rint(pts[:, 1]).astype(np.int64)
67
+ radii_px = np.asarray(radii_px, dtype=np.int64).reshape(-1)
68
+ owners = np.asarray(owners, dtype=np.int64).reshape(-1)
69
+
70
+ inside = (cx >= 0) & (cy >= 0) & (cx < w) & (cy < h)
71
+ cx, cy, radii_px, owners = cx[inside], cy[inside], radii_px[inside], owners[inside]
72
+
73
+ keys: list[np.ndarray] = []
74
+ for radius in np.unique(radii_px):
75
+ sel = np.flatnonzero(radii_px == radius)
76
+ dy, dx = disk_offsets(int(radius))
77
+ step = max(1, _STAMP_CHUNK // dy.size)
78
+ for start in range(0, sel.size, step):
79
+ idx = sel[start:start + step]
80
+ ys = cy[idx, None] + dy[None, :]
81
+ xs = cx[idx, None] + dx[None, :]
82
+ valid = (ys >= 0) & (ys < h) & (xs >= 0) & (xs < w)
83
+ pixel = ys[valid] * w + xs[valid]
84
+ owner = np.broadcast_to(owners[idx, None], valid.shape)[valid]
85
+ keys.append(np.unique(owner * (h * w) + pixel))
86
+
87
+ if not keys:
88
+ empty = np.zeros(0, dtype=np.int64)
89
+ return empty, empty.copy()
90
+ key = np.unique(np.concatenate(keys))
91
+ return key % (h * w), key // (h * w)
src/fiberpose/render.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Images of a `Frame` for display and export, built on demand from the frame's data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Sequence
6
+
7
+ import cv2
8
+ import numpy as np
9
+ from scipy.ndimage import value_indices
10
+ from scipy.spatial import cKDTree
11
+ from skimage.segmentation import find_boundaries
12
+
13
+ from .domain import AppConfig, Frame
14
+ from .utils import ensure_rgb_u8, labels_to_color, to_uint8_for_view
15
+
16
+ # Fully saturated color for every OpenCV hue (0..179). Converted one pixel at a time:
17
+ # cvtColor's vectorized path for longer rows rounds some channels differently.
18
+ _HUE_TO_BGR = np.array(
19
+ [cv2.cvtColor(np.uint8([[[h, 255, 255]]]), cv2.COLOR_HSV2BGR)[0, 0] for h in range(180)],
20
+ dtype=np.uint8,
21
+ )
22
+
23
+
24
+ def render(frame: Frame, view: str, grad_quality_points: Sequence[float] | None = None) -> np.ndarray | None:
25
+ """Image for `view`: a label of the GUI's View box, or "Diameters", "Orientations", "Pores".
26
+
27
+ Returns None when the frame lacks the data the view needs. Images are cached in
28
+ `frame.views` until a pipeline stage is recomputed; treat them as read-only.
29
+ """
30
+ if view in frame.views:
31
+ return frame.views[view]
32
+ labels = frame.labels_2d
33
+ base = frame.orig_img if frame.scale_factor == 1.0 or frame.orig_img_scaled is None else frame.orig_img_scaled
34
+ match view:
35
+ case "Original":
36
+ image = ensure_rgb_u8(frame.orig_img)
37
+ case "DT":
38
+ image = to_uint8_for_view(frame.dt_normalized)
39
+ case "Foreground":
40
+ image = to_uint8_for_view(frame.foreground_prob)
41
+ case "Laplacian":
42
+ image = to_uint8_for_view(frame.lapl_img)
43
+ case "gx" | "gy":
44
+ image = to_uint8_for_view(getattr(frame, view))
45
+ case "Gradient magnitude":
46
+ image = None if frame.gx is None else to_uint8_for_view(np.hypot(frame.gx, frame.gy))
47
+ case "DT grad error":
48
+ # Signed error |grad(dt)| - 1: blue <= p0, green over [p1, p2], red >= p3, linear in between.
49
+ # Depends on the points, so it is not cached.
50
+ if frame.dt is None:
51
+ return None
52
+ points = grad_quality_points or AppConfig().grad_quality_points
53
+ if not np.all(np.diff(points) > 0):
54
+ points = AppConfig().grad_quality_points
55
+ err = np.sqrt(frame.gx * frame.gx + frame.gy * frame.gy) - 1.0
56
+ image = np.stack(
57
+ [np.interp(err, points, ramp) for ramp in ((0, 0, 0, 255), (0, 255, 255, 0), (255, 0, 0, 0))],
58
+ axis=-1,
59
+ ).astype(np.uint8)
60
+ image[frame.dt <= 0] = 0
61
+ return image
62
+ case "Segmentation":
63
+ image = labels_to_color(labels)
64
+ case "Overlay":
65
+ colors, base_rgb = render(frame, "Segmentation"), ensure_rgb_u8(base)
66
+ if colors is None or base_rgb is None or base_rgb.shape[:2] != labels.shape:
67
+ image = None
68
+ else:
69
+ image = base_rgb.copy()
70
+ fg = labels > 0
71
+ image[fg] = (base_rgb[fg] / 2 + colors[fg] / 2).astype(np.uint8)
72
+ case "Segmentation outline":
73
+ image = ensure_rgb_u8(base)
74
+ if labels is None or image is None or image.shape[:2] != labels.shape:
75
+ image = None
76
+ else:
77
+ image = image.copy()
78
+ image[find_boundaries(labels, mode="outer")] = (255, 0, 0)
79
+ case "Centerlines":
80
+ if frame.fragments is None:
81
+ image = None
82
+ else:
83
+ image = cv2.cvtColor(to_uint8_for_view(frame.dt_u8), cv2.COLOR_GRAY2BGR)
84
+ for attr, color in (("segment_centerlines_xy", (255, 0, 0)), ("measurement_centerlines_xy", (0, 255, 0))):
85
+ lines = [p.reshape(-1, 1, 2).astype(np.int32) for f in frame.fragments for p in getattr(f, attr)]
86
+ if lines:
87
+ cv2.polylines(image, lines, isClosed=False, color=color, thickness=1, lineType=cv2.LINE_AA)
88
+ image[find_boundaries(labels, mode="outer")] = (0, 0, 255)
89
+ case "Sampling" | "Diameters":
90
+ # Diameter lines at the sample points: all of them over the DT, every 10th over the overlay.
91
+ if view == "Diameters" and not frame.has_measurements:
92
+ image = None
93
+ else:
94
+ image = ensure_rgb_u8(frame.dt_u8) if view == "Sampling" else render(frame, "Overlay")
95
+ samples = frame.drawing_samples or []
96
+ if image is not None and samples:
97
+ image = image.copy()
98
+ h, w = image.shape[:2]
99
+ for idx, (y, x, ny, nx, r, _angle) in enumerate(samples[:: -(-len(samples) // 15000)]):
100
+ if not (0 <= y < h and 0 <= x < w) or r <= 0 or (view == "Diameters" and idx % 10):
101
+ continue
102
+ x0, x1 = (min(max(int(round(v)), 0), w - 1) for v in (x - nx * r, x + nx * r))
103
+ y0, y1 = (min(max(int(round(v)), 0), h - 1) for v in (y - ny * r, y + ny * r))
104
+ cv2.line(image, (x0, y0), (x1, y1), (255, 255, 0), 1, cv2.LINE_AA)
105
+ if view == "Sampling":
106
+ cv2.circle(image, (int(round(x)), int(round(y))), 1, (255, 0, 0), thickness=-1, lineType=cv2.LINE_AA)
107
+ case "Orientations":
108
+ base_rgb = ensure_rgb_u8(base)
109
+ image = _orientations(frame, base_rgb) if frame.has_measurements and base_rgb is not None else None
110
+ case "Pores":
111
+ if not frame.has_measurements or frame.pore_dt is None:
112
+ image = None
113
+ else:
114
+ void = frame.void_mask > 0
115
+ norm = np.zeros_like(frame.pore_dt, dtype=np.float32)
116
+ if np.any(void):
117
+ vmax = float(np.percentile(frame.pore_dt[void], 99.0)) or float(np.max(frame.pore_dt))
118
+ if vmax > 0:
119
+ norm[void] = (frame.pore_dt[void] / vmax).clip(0.0, 1.0)
120
+ image = cv2.applyColorMap((norm * 255.0).astype(np.uint8), cv2.COLORMAP_TURBO)
121
+ image[~void] = (0, 0, 0)
122
+ for pore in frame.pores or []:
123
+ r = int(round(pore["r_px"]))
124
+ if r > 0:
125
+ cv2.circle(image, (int(pore["x"]), int(pore["y"])), r, (255, 255, 255), thickness=1, lineType=cv2.LINE_AA)
126
+ case _:
127
+ image = None
128
+ frame.views[view] = image
129
+ return image
130
+
131
+
132
+ def _orientations(frame: Frame, base_rgb: np.ndarray) -> np.ndarray:
133
+ """Color each labelled pixel by the axial mean angle of its label's 4 nearest samples, weighted by 1/distance."""
134
+ image = base_rgb.copy()
135
+ labels = frame.labels_2d
136
+ height, width = labels.shape[:2]
137
+ sample_map: dict[int, list[tuple[float, float, float]]] = {}
138
+ for y, x, _ny, _nx, _r, angle_deg in frame.drawing_samples or []:
139
+ iy = int(round(float(y)))
140
+ ix = int(round(float(x)))
141
+ if iy < 0 or iy >= height or ix < 0 or ix >= width:
142
+ continue
143
+ label_id = int(labels[iy, ix])
144
+ if label_id <= 0 or not np.isfinite(angle_deg):
145
+ continue
146
+ sample_map.setdefault(label_id, []).append((float(y), float(x), float(angle_deg)))
147
+
148
+ label_pixels = value_indices(labels)
149
+ for label_id, label_samples in sample_map.items():
150
+ ys, xs = label_pixels[label_id]
151
+ sample_arr = np.asarray(label_samples, dtype=np.float32)
152
+ k = min(4, sample_arr.shape[0])
153
+ distances, indices = cKDTree(sample_arr[:, :2]).query(np.stack([ys, xs], axis=1).astype(np.float32), k=k)
154
+ distances = np.asarray(distances, dtype=np.float32).reshape(len(ys), k)
155
+ indices = np.asarray(indices, dtype=np.int32).reshape(len(ys), k)
156
+ weights = 1.0 / (distances + 1e-6)
157
+ theta2 = np.deg2rad(2.0 * sample_arr[:, 2][indices])
158
+ c = np.sum(weights * np.cos(theta2), axis=1)
159
+ s = np.sum(weights * np.sin(theta2), axis=1)
160
+ image[ys, xs] = _angles_to_bgr(0.5 * np.rad2deg(np.arctan2(s, c)))
161
+ return image
162
+
163
+
164
+ def _angles_to_bgr(angles_deg: np.ndarray) -> np.ndarray:
165
+ """Map axial angles (deg) to (N, 3) colors; the hue is offset by 30 deg. Non-finite -> gray."""
166
+ angles = np.asarray(angles_deg, dtype=np.float64)
167
+ ang = np.mod(-angles + 30.0, 180.0) - 90.0
168
+ hue = (ang + 90.0) / 180.0 * 179.0
169
+ finite = np.isfinite(hue)
170
+ colors = _HUE_TO_BGR[np.where(finite, hue, 0.0).astype(np.uint8)]
171
+ colors[~finite] = (200, 200, 200)
172
+ return colors
src/fiberpose/resources/config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_path": "R108_dt_fg.onnx",
3
+ "use_gpu": true,
4
+ "scale_label": "1x",
5
+ "max_angle_deg": 30.0,
6
+ "ridge_sigma": 1.0,
7
+ "ridge_low": 0.01,
8
+ "ridge_high": 0.4,
9
+ "min_fragment_centerline_length_px": 10.0,
10
+ "measurement_centerline_length_trim_fraction": 0.05,
11
+ "grad_quality_trim_fraction": 0.0,
12
+ "strict_centerlines": false,
13
+ "keep_segments_without_measurement_centerlines": false,
14
+ "segmentation_mode": "watershed",
15
+ "merge_expansion_factor": 0.7,
16
+ "segmentation_expansion_factor": 1.0,
17
+ "watershed_grad_threshold": 0.8,
18
+ "seg_threshold": 1,
19
+ "min_segment_foreground_mean": 0.5,
20
+ "sample_spacing": 5.0,
21
+ "grad_quality_points": [
22
+ -0.35,
23
+ -0.08,
24
+ 0.08,
25
+ 0.35
26
+ ],
27
+ "save_options": {
28
+ "dt": true,
29
+ "foreground": true,
30
+ "labels": true,
31
+ "overlay": true,
32
+ "diameters": true,
33
+ "orientations": true,
34
+ "outline": false,
35
+ "tables": true,
36
+ "image_format": "png",
37
+ "collision": "suffix",
38
+ "write_manifest": true
39
+ }
40
+ }
src/fiberpose/resources/dark_theme.qss ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ==== Global base (match QPalette Window/Text) ==== */
2
+ QWidget {
3
+ background-color: #2d2d2d; /* Window = (45,45,45) */
4
+ color: #dcdcdc; /* Text = (220,220,220) */
5
+ }
6
+
7
+ /* Disabled text (match QPalette Disabled Text) */
8
+ *:disabled {
9
+ color: #7f7f7f; /* Disabled = (127,127,127) */
10
+ }
11
+
12
+ /* ---- Main containers ---- */
13
+ QMainWindow,
14
+ QFrame {
15
+ background-color: #2d2d2d; /* Window */
16
+ }
17
+
18
+ /* Tooltips (match ToolTipBase / ToolTipText) */
19
+ QToolTip {
20
+ background-color: #ffffff; /* ToolTipBase */
21
+ color: #dcdcdc; /* ToolTipText */
22
+ border: 1px solid #666;
23
+ }
24
+
25
+ /* ---- Inputs use Base / AlternateBase ---- */
26
+ QLineEdit,
27
+ QPlainTextEdit,
28
+ QTextEdit,
29
+ QSpinBox, QDoubleSpinBox,
30
+ QComboBox,
31
+ QDateEdit, QTimeEdit, QDateTimeEdit {
32
+ background-color: #1e1e1e; /* Base = (30,30,30) */
33
+ color: #dcdcdc; /* Text */
34
+ border: 1px solid #555;
35
+ border-radius: 4px;
36
+ padding: 2px 6px;
37
+ }
38
+
39
+ /* Dropdown popup for combos uses Window/Base colors */
40
+ QComboBox QAbstractItemView {
41
+ background-color: #1e1e1e; /* Base */
42
+ color: #dcdcdc; /* Text */
43
+ alternate-background-color: #282828; /* AlternateBase = (40,40,40) */
44
+ selection-background-color: #2a82da; /* Highlight = (42,130,218) */
45
+ selection-color: #ffffff; /* HighlightedText */
46
+ border: 1px solid #555;
47
+ }
48
+
49
+ /* Item views (lists/tables/trees) */
50
+ QAbstractItemView {
51
+ background-color: #1e1e1e; /* Base */
52
+ color: #dcdcdc; /* Text */
53
+ alternate-background-color: #282828; /* AlternateBase */
54
+ selection-background-color: #2a82da; /* Highlight */
55
+ selection-color: #ffffff; /* HighlightedText */
56
+ gridline-color: #444;
57
+ outline: 0;
58
+ }
59
+
60
+ /* ---- Buttons (match Button/ButtonText) ---- */
61
+ QPushButton, QToolButton {
62
+ background-color: #444; /* normal */
63
+ color: #f0f0f0;
64
+ border: 1px solid #666;
65
+ border-radius: 4px;
66
+ padding: 4px 10px;
67
+ }
68
+
69
+ QPushButton:hover, QToolButton:hover {
70
+ background-color: #555; /* hover: lighter gray */
71
+ }
72
+
73
+ QPushButton:pressed, QToolButton:pressed {
74
+ background-color: #666; /* pressed: even lighter gray */
75
+ }
76
+
77
+ QPushButton:disabled, QToolButton:disabled {
78
+ background-color: #333; /* disabled: darker gray */
79
+ color: #7f7f7f;
80
+ border: 1px solid #444;
81
+ }
82
+
83
+ /* Group boxes */
84
+ QGroupBox {
85
+ border: 1px solid #555;
86
+ border-radius: 6px;
87
+ margin-top: 8px;
88
+ padding-top: 12px;
89
+ }
90
+ QGroupBox::title {
91
+ subcontrol-origin: margin;
92
+ left: 10px;
93
+ padding: 0 4px;
94
+ color: #dcdcdc; /* WindowText */
95
+ background: transparent;
96
+ }
97
+
98
+ /* ---- Checkboxes ---- */
99
+ QCheckBox {
100
+ color: #f0f0f0;
101
+ }
102
+
103
+ QCheckBox::indicator {
104
+ background-color: #555; /* lighter gray base */
105
+ border: 1px solid #777;
106
+ }
107
+
108
+ QCheckBox::indicator:checked {
109
+ background-color: #2a82da; /* same highlight as palette */
110
+ border: 1px solid #2a82da;
111
+ }
112
+
113
+ QCheckBox::indicator:hover {
114
+ background-color: #666; /* a bit lighter on hover */
115
+ border: 1px solid #999;
116
+ }
117
+
118
+ QCheckBox::indicator:disabled {
119
+ background-color: #444;
120
+ border: 1px solid #555;
121
+ }
122
+
123
+
124
+ /* Focus/selection visuals (global highlight) */
125
+ *:focus {
126
+ outline: none; /* avoid dotted focus; Qt will show focus rects where needed */
127
+ }
128
+ QLineEdit:focus,
129
+ QPlainTextEdit:focus, QTextEdit:focus,
130
+ QComboBox:focus, QAbstractItemView:focus {
131
+ border: 1px solid #2a82da; /* Highlight */
132
+ }
133
+
134
+ /* Graphics view (image window) */
135
+ QGraphicsView {
136
+ background-color: #1e1e1e; /* Base */
137
+ border: 1px solid #333;
138
+ }
139
+
140
+ /* Status bar (optional, in case you use it) */
141
+ QStatusBar {
142
+ background-color: #2d2d2d; /* Window */
143
+ color: #dcdcdc; /* WindowText */
144
+ }
145
+
146
+ /* ---- Spinboxes ---- */
147
+ /* Spinboxes: keep default layout; just add light arrows */
148
+ QSpinBox, QDoubleSpinBox {
149
+ background-color: #1e1e1e; /* Base */
150
+ color: #dcdcdc; /* Text */
151
+ border: 1px solid #555;
152
+ border-radius: 4px;
153
+ padding-right: 18px; /* room for buttons */
154
+ padding-left: 6px;
155
+ }
156
+
157
+ /* Up/Down subcontrols (keep default size/shape) */
158
+ QSpinBox::up-button, QDoubleSpinBox::up-button,
159
+ QSpinBox::down-button, QDoubleSpinBox::down-button {
160
+ background-color: #353535; /* Button */
161
+ border: 1px solid #555;
162
+ width: 16px;
163
+ }
164
+
165
+ QSpinBox::up-button:hover, QDoubleSpinBox::up-button:hover,
166
+ QSpinBox::down-button:hover, QDoubleSpinBox::down-button:hover {
167
+ background-color: #444;
168
+ }
169
+
170
+ /* Light arrow glyphs via SVG */
171
+ QSpinBox::up-arrow { image: url(resources/icons/chevron_up_white.svg); }
172
+ QDoubleSpinBox::up-arrow { image: url(resources/icons/chevron_up_white.svg); }
173
+ QSpinBox::down-arrow { image: url(resources/icons/chevron_down_white.svg); }
174
+ QDoubleSpinBox::down-arrow{ image: url(resources/icons/chevron_down_white.svg); }
175
+
176
+ /* Optional: remove arrows when disabled (Fusion does this visually too) */
177
+ QSpinBox::up-arrow:disabled,
178
+ QDoubleSpinBox::up-arrow:disabled,
179
+ QSpinBox::down-arrow:disabled,
180
+ QDoubleSpinBox::down-arrow:disabled {
181
+ image: none;
182
+ }
src/fiberpose/resources/fiber_tool.ui ADDED
@@ -0,0 +1,1059 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <ui version="4.0">
3
+ <class>MainWindow</class>
4
+ <widget class="QMainWindow" name="MainWindow">
5
+ <property name="geometry">
6
+ <rect>
7
+ <x>0</x>
8
+ <y>0</y>
9
+ <width>1100</width>
10
+ <height>800</height>
11
+ </rect>
12
+ </property>
13
+ <property name="windowTitle">
14
+ <string/>
15
+ </property>
16
+ <widget class="QWidget" name="centralwidget">
17
+ <layout class="QHBoxLayout" name="horizontalLayout">
18
+ <property name="leftMargin">
19
+ <number>10</number>
20
+ </property>
21
+ <property name="topMargin">
22
+ <number>18</number>
23
+ </property>
24
+ <item>
25
+ <widget class="QFrame" name="frame">
26
+ <property name="sizePolicy">
27
+ <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
28
+ <horstretch>0</horstretch>
29
+ <verstretch>0</verstretch>
30
+ </sizepolicy>
31
+ </property>
32
+ <property name="minimumSize">
33
+ <size>
34
+ <width>320</width>
35
+ <height>0</height>
36
+ </size>
37
+ </property>
38
+ <property name="maximumSize">
39
+ <size>
40
+ <width>320</width>
41
+ <height>16777215</height>
42
+ </size>
43
+ </property>
44
+ <property name="frameShape">
45
+ <enum>QFrame::Shape::NoFrame</enum>
46
+ </property>
47
+ <layout class="QVBoxLayout" name="leftLayout">
48
+ <property name="leftMargin">
49
+ <number>0</number>
50
+ </property>
51
+ <property name="topMargin">
52
+ <number>0</number>
53
+ </property>
54
+ <property name="rightMargin">
55
+ <number>0</number>
56
+ </property>
57
+ <property name="bottomMargin">
58
+ <number>0</number>
59
+ </property>
60
+ <item>
61
+ <layout class="QHBoxLayout" name="loadRow">
62
+ <item>
63
+ <widget class="QPushButton" name="btn_load_image">
64
+ <property name="text">
65
+ <string>Load image</string>
66
+ </property>
67
+ </widget>
68
+ </item>
69
+ <item>
70
+ <widget class="QPushButton" name="btn_load_folder">
71
+ <property name="text">
72
+ <string>Load folder</string>
73
+ </property>
74
+ </widget>
75
+ </item>
76
+ <item>
77
+ <widget class="QLabel" name="label_image_name">
78
+ <property name="sizePolicy">
79
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
80
+ <horstretch>0</horstretch>
81
+ <verstretch>0</verstretch>
82
+ </sizepolicy>
83
+ </property>
84
+ <property name="text">
85
+ <string>Image: none</string>
86
+ </property>
87
+ <property name="wordWrap">
88
+ <bool>true</bool>
89
+ </property>
90
+ </widget>
91
+ </item>
92
+ </layout>
93
+ </item>
94
+ <item>
95
+ <widget class="QGroupBox" name="groupBox_segmentation">
96
+ <property name="title">
97
+ <string>Segmentation</string>
98
+ </property>
99
+ <layout class="QVBoxLayout" name="segmentationLayout">
100
+ <item>
101
+ <widget class="QPushButton" name="btn_segment">
102
+ <property name="text">
103
+ <string>Segment</string>
104
+ </property>
105
+ </widget>
106
+ </item>
107
+ <item>
108
+ <layout class="QHBoxLayout" name="segmentationBasicRow">
109
+ <item>
110
+ <widget class="QLabel" name="label_resolution">
111
+ <property name="text">
112
+ <string>Resolution:</string>
113
+ </property>
114
+ </widget>
115
+ </item>
116
+ <item>
117
+ <widget class="QComboBox" name="cb_scale">
118
+ <item>
119
+ <property name="text">
120
+ <string>0.5x</string>
121
+ </property>
122
+ </item>
123
+ <item>
124
+ <property name="text">
125
+ <string>1x</string>
126
+ </property>
127
+ </item>
128
+ <item>
129
+ <property name="text">
130
+ <string>2x</string>
131
+ </property>
132
+ </item>
133
+ <item>
134
+ <property name="text">
135
+ <string>4x</string>
136
+ </property>
137
+ </item>
138
+ </widget>
139
+ </item>
140
+ <item>
141
+ <spacer name="segmentationBasicSpacer">
142
+ <property name="orientation">
143
+ <enum>Qt::Orientation::Horizontal</enum>
144
+ </property>
145
+ <property name="sizeHint" stdset="0">
146
+ <size>
147
+ <width>0</width>
148
+ <height>0</height>
149
+ </size>
150
+ </property>
151
+ </spacer>
152
+ </item>
153
+ <item>
154
+ <widget class="QCheckBox" name="chb_invert">
155
+ <property name="text">
156
+ <string>Invert image</string>
157
+ </property>
158
+ </widget>
159
+ </item>
160
+ </layout>
161
+ </item>
162
+ <item>
163
+ <widget class="QToolButton" name="btn_segmentation_advanced">
164
+ <property name="text">
165
+ <string>Advanced</string>
166
+ </property>
167
+ <property name="checkable">
168
+ <bool>true</bool>
169
+ </property>
170
+ <property name="toolButtonStyle">
171
+ <enum>Qt::ToolButtonStyle::ToolButtonTextBesideIcon</enum>
172
+ </property>
173
+ <property name="autoRaise">
174
+ <bool>true</bool>
175
+ </property>
176
+ <property name="arrowType">
177
+ <enum>Qt::ArrowType::RightArrow</enum>
178
+ </property>
179
+ </widget>
180
+ </item>
181
+ <item>
182
+ <widget class="QWidget" name="widget_segmentation_advanced" native="true">
183
+ <layout class="QVBoxLayout" name="segmentationAdvancedLayout">
184
+ <property name="leftMargin">
185
+ <number>0</number>
186
+ </property>
187
+ <property name="topMargin">
188
+ <number>0</number>
189
+ </property>
190
+ <property name="rightMargin">
191
+ <number>0</number>
192
+ </property>
193
+ <property name="bottomMargin">
194
+ <number>0</number>
195
+ </property>
196
+ <item>
197
+ <layout class="QHBoxLayout" name="modelRow">
198
+ <item>
199
+ <widget class="QLabel" name="label_model">
200
+ <property name="text">
201
+ <string>Model:</string>
202
+ </property>
203
+ </widget>
204
+ </item>
205
+ <item>
206
+ <widget class="QComboBox" name="cb_model">
207
+ <property name="sizePolicy">
208
+ <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
209
+ <horstretch>0</horstretch>
210
+ <verstretch>0</verstretch>
211
+ </sizepolicy>
212
+ </property>
213
+ </widget>
214
+ </item>
215
+ </layout>
216
+ </item>
217
+ <item>
218
+ <layout class="QHBoxLayout" name="gradientRow">
219
+ <item>
220
+ <widget class="QLabel" name="label_gradient">
221
+ <property name="text">
222
+ <string>Gradient magnitude:</string>
223
+ </property>
224
+ </widget>
225
+ </item>
226
+ <item>
227
+ <spacer name="gradientSpacer">
228
+ <property name="orientation">
229
+ <enum>Qt::Orientation::Horizontal</enum>
230
+ </property>
231
+ <property name="sizeHint" stdset="0">
232
+ <size>
233
+ <width>0</width>
234
+ <height>0</height>
235
+ </size>
236
+ </property>
237
+ </spacer>
238
+ </item>
239
+ <item>
240
+ <widget class="QDoubleSpinBox" name="sp_grad_magnitude_threshold">
241
+ <property name="decimals">
242
+ <number>2</number>
243
+ </property>
244
+ <property name="maximum">
245
+ <double>5.000000000000000</double>
246
+ </property>
247
+ <property name="singleStep">
248
+ <double>0.050000000000000</double>
249
+ </property>
250
+ <property name="value">
251
+ <double>0.800000000000000</double>
252
+ </property>
253
+ </widget>
254
+ </item>
255
+ </layout>
256
+ </item>
257
+ <item>
258
+ <layout class="QHBoxLayout" name="modeRow">
259
+ <item>
260
+ <widget class="QRadioButton" name="rb_watershed">
261
+ <property name="text">
262
+ <string>Watershed</string>
263
+ </property>
264
+ <property name="checked">
265
+ <bool>true</bool>
266
+ </property>
267
+ </widget>
268
+ </item>
269
+ <item>
270
+ <widget class="QRadioButton" name="rb_ridge">
271
+ <property name="text">
272
+ <string>Radial expansion</string>
273
+ </property>
274
+ </widget>
275
+ </item>
276
+ </layout>
277
+ </item>
278
+ <item>
279
+ <layout class="QHBoxLayout" name="flagsRow">
280
+ <item>
281
+ <widget class="QCheckBox" name="chb_strict">
282
+ <property name="text">
283
+ <string>Strict</string>
284
+ </property>
285
+ </widget>
286
+ </item>
287
+ <item>
288
+ <widget class="QCheckBox" name="chb_usegpu">
289
+ <property name="text">
290
+ <string>Use GPU</string>
291
+ </property>
292
+ </widget>
293
+ </item>
294
+ </layout>
295
+ </item>
296
+ <item>
297
+ <widget class="QPushButton" name="btn_plot_profile">
298
+ <property name="text">
299
+ <string>Plot profile</string>
300
+ </property>
301
+ </widget>
302
+ </item>
303
+ </layout>
304
+ </widget>
305
+ </item>
306
+ </layout>
307
+ </widget>
308
+ </item>
309
+ <item>
310
+ <widget class="QGroupBox" name="groupBox_measurement">
311
+ <property name="title">
312
+ <string>Measurement</string>
313
+ </property>
314
+ <layout class="QVBoxLayout" name="measurementLayout">
315
+ <item>
316
+ <widget class="QPushButton" name="btn_measure">
317
+ <property name="text">
318
+ <string>Measure</string>
319
+ </property>
320
+ </widget>
321
+ </item>
322
+ <item>
323
+ <layout class="QHBoxLayout" name="pixelSizeRow">
324
+ <item>
325
+ <widget class="QLabel" name="label_pixel_size">
326
+ <property name="text">
327
+ <string>Pixel size:</string>
328
+ </property>
329
+ </widget>
330
+ </item>
331
+ <item>
332
+ <widget class="QLineEdit" name="le_pixelsize">
333
+ <property name="maximumSize">
334
+ <size>
335
+ <width>90</width>
336
+ <height>16777215</height>
337
+ </size>
338
+ </property>
339
+ <property name="text">
340
+ <string>1</string>
341
+ </property>
342
+ </widget>
343
+ </item>
344
+ <item>
345
+ <widget class="QLabel" name="label_pixel_unit">
346
+ <property name="text">
347
+ <string>px</string>
348
+ </property>
349
+ </widget>
350
+ </item>
351
+ <item>
352
+ <spacer name="pixelSizeSpacer">
353
+ <property name="orientation">
354
+ <enum>Qt::Orientation::Horizontal</enum>
355
+ </property>
356
+ <property name="sizeHint" stdset="0">
357
+ <size>
358
+ <width>0</width>
359
+ <height>0</height>
360
+ </size>
361
+ </property>
362
+ </spacer>
363
+ </item>
364
+ <item>
365
+ <widget class="QPushButton" name="btn_set_scalebar">
366
+ <property name="text">
367
+ <string>Set scalebar…</string>
368
+ </property>
369
+ </widget>
370
+ </item>
371
+ </layout>
372
+ </item>
373
+ <item>
374
+ <widget class="QToolButton" name="btn_measurement_advanced">
375
+ <property name="text">
376
+ <string>Advanced</string>
377
+ </property>
378
+ <property name="checkable">
379
+ <bool>true</bool>
380
+ </property>
381
+ <property name="toolButtonStyle">
382
+ <enum>Qt::ToolButtonStyle::ToolButtonTextBesideIcon</enum>
383
+ </property>
384
+ <property name="autoRaise">
385
+ <bool>true</bool>
386
+ </property>
387
+ <property name="arrowType">
388
+ <enum>Qt::ArrowType::RightArrow</enum>
389
+ </property>
390
+ </widget>
391
+ </item>
392
+ <item>
393
+ <widget class="QWidget" name="widget_measurement_advanced" native="true">
394
+ <layout class="QVBoxLayout" name="measurementAdvancedLayout">
395
+ <property name="leftMargin">
396
+ <number>0</number>
397
+ </property>
398
+ <property name="topMargin">
399
+ <number>0</number>
400
+ </property>
401
+ <property name="rightMargin">
402
+ <number>0</number>
403
+ </property>
404
+ <property name="bottomMargin">
405
+ <number>0</number>
406
+ </property>
407
+ <item>
408
+ <layout class="QHBoxLayout" name="voxelDepthRow">
409
+ <item>
410
+ <widget class="QLabel" name="label_voxel_depth">
411
+ <property name="text">
412
+ <string>Voxel depth:</string>
413
+ </property>
414
+ </widget>
415
+ </item>
416
+ <item>
417
+ <widget class="QLineEdit" name="le_voxeldepth">
418
+ <property name="maximumSize">
419
+ <size>
420
+ <width>90</width>
421
+ <height>16777215</height>
422
+ </size>
423
+ </property>
424
+ <property name="text">
425
+ <string>1</string>
426
+ </property>
427
+ </widget>
428
+ </item>
429
+ <item>
430
+ <spacer name="voxelDepthSpacer">
431
+ <property name="orientation">
432
+ <enum>Qt::Orientation::Horizontal</enum>
433
+ </property>
434
+ <property name="sizeHint" stdset="0">
435
+ <size>
436
+ <width>0</width>
437
+ <height>0</height>
438
+ </size>
439
+ </property>
440
+ </spacer>
441
+ </item>
442
+ </layout>
443
+ </item>
444
+ <item>
445
+ <widget class="QLabel" name="label_overlay">
446
+ <property name="text">
447
+ <string>Overlay:</string>
448
+ </property>
449
+ </widget>
450
+ </item>
451
+ <item>
452
+ <layout class="QHBoxLayout" name="overlayRow">
453
+ <item>
454
+ <widget class="QRadioButton" name="rb_show_diam">
455
+ <property name="text">
456
+ <string>Diameters</string>
457
+ </property>
458
+ <property name="checked">
459
+ <bool>true</bool>
460
+ </property>
461
+ </widget>
462
+ </item>
463
+ <item>
464
+ <widget class="QRadioButton" name="rb_show_direct">
465
+ <property name="text">
466
+ <string>Directions</string>
467
+ </property>
468
+ </widget>
469
+ </item>
470
+ <item>
471
+ <widget class="QRadioButton" name="rb_show_pores">
472
+ <property name="text">
473
+ <string>Pores</string>
474
+ </property>
475
+ </widget>
476
+ </item>
477
+ </layout>
478
+ </item>
479
+ </layout>
480
+ </widget>
481
+ </item>
482
+ </layout>
483
+ </widget>
484
+ </item>
485
+ <item>
486
+ <widget class="QGroupBox" name="groupBox_export">
487
+ <property name="title">
488
+ <string>Export results</string>
489
+ </property>
490
+ <layout class="QVBoxLayout" name="exportLayout">
491
+ <item>
492
+ <widget class="QPushButton" name="btn_export_results">
493
+ <property name="text">
494
+ <string>Export results</string>
495
+ </property>
496
+ </widget>
497
+ </item>
498
+ <item>
499
+ <widget class="QCheckBox" name="chb_export_labels">
500
+ <property name="text">
501
+ <string>Segmentation masks</string>
502
+ </property>
503
+ </widget>
504
+ </item>
505
+ <item>
506
+ <widget class="QCheckBox" name="chb_export_tables">
507
+ <property name="text">
508
+ <string>Measurements table (CSV)</string>
509
+ </property>
510
+ </widget>
511
+ </item>
512
+ <item>
513
+ <widget class="QCheckBox" name="chb_export_overlay">
514
+ <property name="text">
515
+ <string>Overlay visualization</string>
516
+ </property>
517
+ </widget>
518
+ </item>
519
+ <item>
520
+ <widget class="QToolButton" name="btn_export_advanced">
521
+ <property name="text">
522
+ <string>Advanced</string>
523
+ </property>
524
+ <property name="checkable">
525
+ <bool>true</bool>
526
+ </property>
527
+ <property name="toolButtonStyle">
528
+ <enum>Qt::ToolButtonStyle::ToolButtonTextBesideIcon</enum>
529
+ </property>
530
+ <property name="autoRaise">
531
+ <bool>true</bool>
532
+ </property>
533
+ <property name="arrowType">
534
+ <enum>Qt::ArrowType::RightArrow</enum>
535
+ </property>
536
+ </widget>
537
+ </item>
538
+ <item>
539
+ <widget class="QWidget" name="widget_export_advanced" native="true">
540
+ <layout class="QVBoxLayout" name="exportAdvancedLayout">
541
+ <property name="leftMargin">
542
+ <number>0</number>
543
+ </property>
544
+ <property name="topMargin">
545
+ <number>0</number>
546
+ </property>
547
+ <property name="rightMargin">
548
+ <number>0</number>
549
+ </property>
550
+ <property name="bottomMargin">
551
+ <number>0</number>
552
+ </property>
553
+ <item>
554
+ <widget class="QCheckBox" name="chb_export_diameters">
555
+ <property name="text">
556
+ <string>Diameter measurements overlay</string>
557
+ </property>
558
+ </widget>
559
+ </item>
560
+ <item>
561
+ <widget class="QCheckBox" name="chb_export_orientations">
562
+ <property name="text">
563
+ <string>Orientation measurements overlay</string>
564
+ </property>
565
+ </widget>
566
+ </item>
567
+ <item>
568
+ <widget class="QCheckBox" name="chb_export_outline">
569
+ <property name="text">
570
+ <string>Segmentation outline image</string>
571
+ </property>
572
+ </widget>
573
+ </item>
574
+ <item>
575
+ <widget class="QCheckBox" name="chb_export_dt">
576
+ <property name="text">
577
+ <string>Distance transform (float32 TIFF)</string>
578
+ </property>
579
+ </widget>
580
+ </item>
581
+ <item>
582
+ <widget class="QCheckBox" name="chb_export_foreground">
583
+ <property name="text">
584
+ <string>Foreground probability (float32 TIFF)</string>
585
+ </property>
586
+ </widget>
587
+ </item>
588
+ <item>
589
+ <layout class="QHBoxLayout" name="imageFormatRow">
590
+ <item>
591
+ <widget class="QLabel" name="label_image_format">
592
+ <property name="text">
593
+ <string>Image format:</string>
594
+ </property>
595
+ </widget>
596
+ </item>
597
+ <item>
598
+ <widget class="QComboBox" name="cb_image_format">
599
+ <item>
600
+ <property name="text">
601
+ <string>png</string>
602
+ </property>
603
+ </item>
604
+ <item>
605
+ <property name="text">
606
+ <string>tiff</string>
607
+ </property>
608
+ </item>
609
+ </widget>
610
+ </item>
611
+ <item>
612
+ <spacer name="imageFormatRowSpacer">
613
+ <property name="orientation">
614
+ <enum>Qt::Orientation::Horizontal</enum>
615
+ </property>
616
+ <property name="sizeHint" stdset="0">
617
+ <size>
618
+ <width>0</width>
619
+ <height>0</height>
620
+ </size>
621
+ </property>
622
+ </spacer>
623
+ </item>
624
+ </layout>
625
+ </item>
626
+ <item>
627
+ <layout class="QHBoxLayout" name="collisionRow">
628
+ <item>
629
+ <widget class="QLabel" name="label_collision">
630
+ <property name="text">
631
+ <string>Collision policy:</string>
632
+ </property>
633
+ </widget>
634
+ </item>
635
+ <item>
636
+ <widget class="QComboBox" name="cb_collision">
637
+ <item>
638
+ <property name="text">
639
+ <string>suffix</string>
640
+ </property>
641
+ </item>
642
+ <item>
643
+ <property name="text">
644
+ <string>overwrite</string>
645
+ </property>
646
+ </item>
647
+ <item>
648
+ <property name="text">
649
+ <string>error</string>
650
+ </property>
651
+ </item>
652
+ </widget>
653
+ </item>
654
+ <item>
655
+ <spacer name="collisionRowSpacer">
656
+ <property name="orientation">
657
+ <enum>Qt::Orientation::Horizontal</enum>
658
+ </property>
659
+ <property name="sizeHint" stdset="0">
660
+ <size>
661
+ <width>0</width>
662
+ <height>0</height>
663
+ </size>
664
+ </property>
665
+ </spacer>
666
+ </item>
667
+ </layout>
668
+ </item>
669
+ <item>
670
+ <widget class="QCheckBox" name="chb_write_manifest">
671
+ <property name="text">
672
+ <string>Write export manifest (manifest.json)</string>
673
+ </property>
674
+ </widget>
675
+ </item>
676
+ </layout>
677
+ </widget>
678
+ </item>
679
+ </layout>
680
+ </widget>
681
+ </item>
682
+ <item>
683
+ <spacer name="leftSpacer">
684
+ <property name="orientation">
685
+ <enum>Qt::Orientation::Vertical</enum>
686
+ </property>
687
+ <property name="sizeHint" stdset="0">
688
+ <size>
689
+ <width>0</width>
690
+ <height>0</height>
691
+ </size>
692
+ </property>
693
+ </spacer>
694
+ </item>
695
+ </layout>
696
+ </widget>
697
+ </item>
698
+ <item>
699
+ <layout class="QVBoxLayout" name="verticalLayout_2" stretch="0,1,0">
700
+ <item>
701
+ <layout class="QHBoxLayout" name="viewRow">
702
+ <item>
703
+ <widget class="QLabel" name="label_view">
704
+ <property name="text">
705
+ <string>View:</string>
706
+ </property>
707
+ </widget>
708
+ </item>
709
+ <item>
710
+ <widget class="QComboBox" name="cb_view">
711
+ <item>
712
+ <property name="text">
713
+ <string>Original</string>
714
+ </property>
715
+ </item>
716
+ <item>
717
+ <property name="text">
718
+ <string>DT</string>
719
+ </property>
720
+ </item>
721
+ <item>
722
+ <property name="text">
723
+ <string>Foreground</string>
724
+ </property>
725
+ </item>
726
+ <item>
727
+ <property name="text">
728
+ <string>Gradient magnitude</string>
729
+ </property>
730
+ </item>
731
+ <item>
732
+ <property name="text">
733
+ <string>DT grad error</string>
734
+ </property>
735
+ </item>
736
+ <item>
737
+ <property name="text">
738
+ <string>Centerlines</string>
739
+ </property>
740
+ </item>
741
+ <item>
742
+ <property name="text">
743
+ <string>Segmentation outline</string>
744
+ </property>
745
+ </item>
746
+ <item>
747
+ <property name="text">
748
+ <string>Segmentation</string>
749
+ </property>
750
+ </item>
751
+ <item>
752
+ <property name="text">
753
+ <string>Overlay</string>
754
+ </property>
755
+ </item>
756
+ <item>
757
+ <property name="text">
758
+ <string>Measurements overlay</string>
759
+ </property>
760
+ </item>
761
+ <item>
762
+ <property name="text">
763
+ <string>Sampling</string>
764
+ </property>
765
+ </item>
766
+ <item>
767
+ <property name="text">
768
+ <string>Laplacian</string>
769
+ </property>
770
+ </item>
771
+ <item>
772
+ <property name="text">
773
+ <string>gx</string>
774
+ </property>
775
+ </item>
776
+ <item>
777
+ <property name="text">
778
+ <string>gy</string>
779
+ </property>
780
+ </item>
781
+ </widget>
782
+ </item>
783
+ <item>
784
+ <widget class="QPushButton" name="btn_save_screenshot">
785
+ <property name="text">
786
+ <string>Export Current View</string>
787
+ </property>
788
+ </widget>
789
+ </item>
790
+ <item>
791
+ <spacer name="viewSpacer">
792
+ <property name="orientation">
793
+ <enum>Qt::Orientation::Horizontal</enum>
794
+ </property>
795
+ <property name="sizeHint" stdset="0">
796
+ <size>
797
+ <width>0</width>
798
+ <height>0</height>
799
+ </size>
800
+ </property>
801
+ </spacer>
802
+ </item>
803
+ </layout>
804
+ </item>
805
+ <item>
806
+ <widget class="QGraphicsView" name="graphicsView">
807
+ <property name="minimumSize">
808
+ <size>
809
+ <width>493</width>
810
+ <height>400</height>
811
+ </size>
812
+ </property>
813
+ </widget>
814
+ </item>
815
+ <item>
816
+ <widget class="QWidget" name="widget_plots" native="true">
817
+ <layout class="QVBoxLayout" name="plotsAreaLayout">
818
+ <property name="leftMargin">
819
+ <number>0</number>
820
+ </property>
821
+ <property name="topMargin">
822
+ <number>0</number>
823
+ </property>
824
+ <property name="rightMargin">
825
+ <number>0</number>
826
+ </property>
827
+ <property name="bottomMargin">
828
+ <number>0</number>
829
+ </property>
830
+ <item>
831
+ <layout class="QHBoxLayout" name="unitsRow">
832
+ <item>
833
+ <widget class="QLabel" name="label_units">
834
+ <property name="text">
835
+ <string>Units:</string>
836
+ </property>
837
+ </widget>
838
+ </item>
839
+ <item>
840
+ <widget class="QComboBox" name="cb_units">
841
+ <item>
842
+ <property name="text">
843
+ <string>px</string>
844
+ </property>
845
+ </item>
846
+ <item>
847
+ <property name="text">
848
+ <string>um</string>
849
+ </property>
850
+ </item>
851
+ <item>
852
+ <property name="text">
853
+ <string>nm</string>
854
+ </property>
855
+ </item>
856
+ <item>
857
+ <property name="text">
858
+ <string>mm</string>
859
+ </property>
860
+ </item>
861
+ <item>
862
+ <property name="text">
863
+ <string>m</string>
864
+ </property>
865
+ </item>
866
+ </widget>
867
+ </item>
868
+ <item>
869
+ <spacer name="unitsSpacer">
870
+ <property name="orientation">
871
+ <enum>Qt::Orientation::Horizontal</enum>
872
+ </property>
873
+ <property name="sizeHint" stdset="0">
874
+ <size>
875
+ <width>0</width>
876
+ <height>0</height>
877
+ </size>
878
+ </property>
879
+ </spacer>
880
+ </item>
881
+ </layout>
882
+ </item>
883
+ <item>
884
+ <layout class="QHBoxLayout" name="plotsRow">
885
+ <item>
886
+ <widget class="PlotWidget" name="graph_diameters" native="true">
887
+ <property name="minimumSize">
888
+ <size>
889
+ <width>0</width>
890
+ <height>200</height>
891
+ </size>
892
+ </property>
893
+ <property name="maximumSize">
894
+ <size>
895
+ <width>16777215</width>
896
+ <height>300</height>
897
+ </size>
898
+ </property>
899
+ </widget>
900
+ </item>
901
+ <item>
902
+ <widget class="PlotWidget" name="graph_angles" native="true">
903
+ <property name="minimumSize">
904
+ <size>
905
+ <width>0</width>
906
+ <height>200</height>
907
+ </size>
908
+ </property>
909
+ <property name="maximumSize">
910
+ <size>
911
+ <width>16777215</width>
912
+ <height>300</height>
913
+ </size>
914
+ </property>
915
+ </widget>
916
+ </item>
917
+ <item>
918
+ <layout class="QVBoxLayout" name="statsColumn">
919
+ <item>
920
+ <widget class="QPlainTextEdit" name="text_edit2">
921
+ <property name="sizePolicy">
922
+ <sizepolicy hsizetype="Expanding" vsizetype="Ignored">
923
+ <horstretch>0</horstretch>
924
+ <verstretch>0</verstretch>
925
+ </sizepolicy>
926
+ </property>
927
+ <property name="minimumSize">
928
+ <size>
929
+ <width>0</width>
930
+ <height>160</height>
931
+ </size>
932
+ </property>
933
+ <property name="maximumSize">
934
+ <size>
935
+ <width>240</width>
936
+ <height>300</height>
937
+ </size>
938
+ </property>
939
+ <property name="readOnly">
940
+ <bool>true</bool>
941
+ </property>
942
+ </widget>
943
+ </item>
944
+ <item alignment="Qt::AlignmentFlag::AlignLeft">
945
+ <widget class="QPushButton" name="btn_export_csv">
946
+ <property name="text">
947
+ <string>Export CSV</string>
948
+ </property>
949
+ </widget>
950
+ </item>
951
+ </layout>
952
+ </item>
953
+ </layout>
954
+ </item>
955
+ </layout>
956
+ </widget>
957
+ </item>
958
+ </layout>
959
+ </item>
960
+ <item>
961
+ <widget class="QScrollBar" name="z_scroll"/>
962
+ </item>
963
+ </layout>
964
+ </widget>
965
+ <widget class="QMenuBar" name="menubar">
966
+ <property name="geometry">
967
+ <rect>
968
+ <x>0</x>
969
+ <y>0</y>
970
+ <width>1100</width>
971
+ <height>33</height>
972
+ </rect>
973
+ </property>
974
+ <widget class="QMenu" name="menuFile">
975
+ <property name="title">
976
+ <string>File</string>
977
+ </property>
978
+ <addaction name="action_load_image"/>
979
+ <addaction name="action_batch_processing"/>
980
+ <addaction name="action_save_masks_predictions"/>
981
+ <addaction name="action_save_measurements"/>
982
+ </widget>
983
+ <widget class="QMenu" name="menuEdit">
984
+ <property name="title">
985
+ <string>Edit</string>
986
+ </property>
987
+ <addaction name="action_edit_config"/>
988
+ <addaction name="action_load_config"/>
989
+ </widget>
990
+ <widget class="QMenu" name="menuHelp">
991
+ <property name="title">
992
+ <string>Models</string>
993
+ </property>
994
+ <addaction name="actionAdd_custom_model"/>
995
+ <addaction name="actionRemove_model"/>
996
+ </widget>
997
+ <widget class="QMenu" name="menuHelp_2">
998
+ <property name="title">
999
+ <string>Help</string>
1000
+ </property>
1001
+ </widget>
1002
+ <addaction name="menuFile"/>
1003
+ <addaction name="menuEdit"/>
1004
+ <addaction name="menuHelp"/>
1005
+ <addaction name="menuHelp_2"/>
1006
+ </widget>
1007
+ <widget class="QStatusBar" name="statusbar"/>
1008
+ <action name="action_load_image">
1009
+ <property name="text">
1010
+ <string>Open Image/Stack</string>
1011
+ </property>
1012
+ </action>
1013
+ <action name="action_save_masks_predictions">
1014
+ <property name="text">
1015
+ <string>Save Segmentation Results</string>
1016
+ </property>
1017
+ </action>
1018
+ <action name="action_save_measurements">
1019
+ <property name="text">
1020
+ <string>Save measurements (CSV)</string>
1021
+ </property>
1022
+ </action>
1023
+ <action name="actionAdd_custom_model">
1024
+ <property name="text">
1025
+ <string>Add model</string>
1026
+ </property>
1027
+ </action>
1028
+ <action name="actionRemove_model">
1029
+ <property name="text">
1030
+ <string>Remove model</string>
1031
+ </property>
1032
+ </action>
1033
+ <action name="action_batch_processing">
1034
+ <property name="text">
1035
+ <string>Open Folder (Batch Mode)</string>
1036
+ </property>
1037
+ </action>
1038
+ <action name="action_edit_config">
1039
+ <property name="text">
1040
+ <string>Edit config...</string>
1041
+ </property>
1042
+ </action>
1043
+ <action name="action_load_config">
1044
+ <property name="text">
1045
+ <string>Load config...</string>
1046
+ </property>
1047
+ </action>
1048
+ </widget>
1049
+ <customwidgets>
1050
+ <customwidget>
1051
+ <class>PlotWidget</class>
1052
+ <extends>QWidget</extends>
1053
+ <header>pyqtgraph</header>
1054
+ <container>1</container>
1055
+ </customwidget>
1056
+ </customwidgets>
1057
+ <resources/>
1058
+ <connections/>
1059
+ </ui>
src/fiberpose/resources/fiberpose.png ADDED
src/fiberpose/resources/test.png ADDED

Git LFS Details

  • SHA256: af7480b7a796be5d235fb2edd23dc5d46fd2982d9f71f5b587db624f632009a0
  • Pointer size: 131 Bytes
  • Size of remote file: 414 kB
src/fiberpose/ridge_detector.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ Steger ridge/line detection (exact math) with Numba speedups.
4
+
5
+ - RidgeDetector class with public detect_ridges()
6
+ - Public API returns detected polylines as plain NumPy arrays
7
+ - Convolution and candidate kernels are JIT-compiled with numba without fastmath to preserve quality
8
+ - Contour linking is traced in numba; Python only assembles the output polylines
9
+
10
+ Usage:
11
+ det = RidgeDetector()
12
+ polylines = det.detect_ridges(img, sigma=2.0, low=8, high=15, polarity="dark")
13
+
14
+ """
15
+
16
+ from __future__ import annotations
17
+ from typing import List, Tuple
18
+ import math
19
+ import numpy as np
20
+ import numba as nb
21
+
22
+
23
+ # -------------------------
24
+ # Numba kernels
25
+ # -------------------------
26
+
27
+ @nb.njit(cache=True)
28
+ def _mirror_r_jit(r: int, h: int) -> int:
29
+ if r < 0:
30
+ return -r
31
+ if r >= h:
32
+ return h - r + h - 2
33
+ return r
34
+
35
+ @nb.njit(cache=True)
36
+ def _mirror_c_jit(c: int, w: int) -> int:
37
+ if c < 0:
38
+ return -c
39
+ if c >= w:
40
+ return w - c + w - 2
41
+ return c
42
+
43
+ @nb.njit(cache=True)
44
+ def _convolve_rows_flat(image: np.ndarray, mask: np.ndarray, n: int, w: int, h: int) -> np.ndarray:
45
+ out = np.empty((w * h,), dtype=np.float32)
46
+
47
+ # inner
48
+ for r in range(n, h - n):
49
+ base = r * w
50
+ for c in range(w):
51
+ l = base + c
52
+ s = 0.0
53
+ for j in range(-n, n + 1):
54
+ s += float(image[l + j * w]) * float(mask[j + n])
55
+ out[l] = np.float32(s)
56
+
57
+ # borders top
58
+ for r in range(0, n):
59
+ base = r * w
60
+ for c in range(w):
61
+ l = base + c
62
+ s = 0.0
63
+ for j in range(-n, n + 1):
64
+ rr = _mirror_r_jit(r + j, h)
65
+ s += float(image[rr * w + c]) * float(mask[j + n])
66
+ out[l] = np.float32(s)
67
+
68
+ # borders bottom
69
+ for r in range(h - n, h):
70
+ base = r * w
71
+ for c in range(w):
72
+ l = base + c
73
+ s = 0.0
74
+ for j in range(-n, n + 1):
75
+ rr = _mirror_r_jit(r + j, h)
76
+ s += float(image[rr * w + c]) * float(mask[j + n])
77
+ out[l] = np.float32(s)
78
+
79
+ return out
80
+
81
+ @nb.njit(cache=True)
82
+ def _convolve_cols_flat(tmp: np.ndarray, mask: np.ndarray, n: int, w: int, h: int) -> np.ndarray:
83
+ out = np.empty((w * h,), dtype=np.float32)
84
+
85
+ # inner
86
+ for r in range(h):
87
+ base = r * w
88
+ for c in range(n, w - n):
89
+ l = base + c
90
+ s = 0.0
91
+ for j in range(-n, n + 1):
92
+ s += float(tmp[l + j]) * float(mask[j + n])
93
+ out[l] = np.float32(s)
94
+
95
+ # borders
96
+ for r in range(h):
97
+ base = r * w
98
+ for c in range(0, n):
99
+ l = base + c
100
+ s = 0.0
101
+ for j in range(-n, n + 1):
102
+ cc = _mirror_c_jit(c + j, w)
103
+ s += float(tmp[base + cc]) * float(mask[j + n])
104
+ out[l] = np.float32(s)
105
+
106
+ for c in range(w - n, w):
107
+ l = base + c
108
+ s = 0.0
109
+ for j in range(-n, n + 1):
110
+ cc = _mirror_c_jit(c + j, w)
111
+ s += float(tmp[base + cc]) * float(mask[j + n])
112
+ out[l] = np.float32(s)
113
+
114
+ return out
115
+
116
+ @nb.njit(cache=True)
117
+ def _solve_linear_jit(a: float, b: float) -> Tuple[int, float]:
118
+ if a == 0.0:
119
+ return 0, 0.0
120
+ return 1, -b / a
121
+
122
+ @nb.njit(cache=True)
123
+ def _eigen_2x2_jit(drr: float, drc: float, dcc: float) -> Tuple[float, float, float, float]:
124
+ """
125
+ Returns (e1, e2, v0x, v0y) where (v0x, v0y) is eigenvector for the principal eigenvalue
126
+ following the same selection logic as the Java port.
127
+ """
128
+ if drc != 0.0:
129
+ theta = 0.5 * (dcc - drr) / drc
130
+ t = 1.0 / (abs(theta) + math.sqrt(theta * theta + 1.0))
131
+ if theta < 0.0:
132
+ t = -t
133
+ c = 1.0 / math.sqrt(t * t + 1.0)
134
+ s = t * c
135
+ e1 = drr - t * drc
136
+ e2 = dcc + t * drc
137
+ else:
138
+ c = 1.0
139
+ s = 0.0
140
+ e1 = drr
141
+ e2 = dcc
142
+
143
+ n1 = c
144
+ n2 = -s
145
+
146
+ # choose ordering like original (by abs)
147
+ if abs(e1) > abs(e2):
148
+ return e1, e2, n1, n2
149
+ elif abs(e1) < abs(e2):
150
+ # swapped
151
+ return e2, e1, -n2, n1
152
+ else:
153
+ if e1 < e2:
154
+ return e1, e2, n1, n2
155
+ else:
156
+ return e2, e1, -n2, n1
157
+
158
+ @nb.njit(cache=True)
159
+ def _ridge_candidates_jit(dr, dc, drr, drc, dcc, w: int, h: int,
160
+ low: float, high: float, mode: int,
161
+ pixel_boundary: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
162
+ N = w * h
163
+ ismax = np.zeros((N,), dtype=np.uint8)
164
+ ev = np.zeros((N,), dtype=np.float32)
165
+ nx = np.zeros((N,), dtype=np.float32)
166
+ ny = np.zeros((N,), dtype=np.float32)
167
+ px = np.zeros((N,), dtype=np.float32)
168
+ py = np.zeros((N,), dtype=np.float32)
169
+
170
+ for r in range(h):
171
+ for c in range(w):
172
+ l = r * w + c
173
+
174
+ e1, _, v0x, v0y = _eigen_2x2_jit(float(drr[l]), float(drc[l]), float(dcc[l]))
175
+
176
+ val = -e1 if mode == 1 else e1 # 1=light, 2=dark
177
+ if val <= 0.0:
178
+ continue
179
+
180
+ ev[l] = np.float32(val)
181
+
182
+ n1 = v0x
183
+ n2 = v0y
184
+
185
+ a = float(drr[l]) * n1 * n1 + 2.0 * float(drc[l]) * n1 * n2 + float(dcc[l]) * n2 * n2
186
+ b = float(dr[l]) * n1 + float(dc[l]) * n2
187
+
188
+ ok, t = _solve_linear_jit(a, b)
189
+ if ok == 0:
190
+ continue
191
+
192
+ p1 = t * n1
193
+ p2 = t * n2
194
+
195
+ if abs(p1) <= pixel_boundary and abs(p2) <= pixel_boundary:
196
+ if val >= low:
197
+ ismax[l] = 2 if val >= high else 1
198
+ nx[l] = np.float32(n1)
199
+ ny[l] = np.float32(n2)
200
+ px[l] = np.float32(r + p1)
201
+ py[l] = np.float32(c + p2)
202
+
203
+ return ismax, ev, nx, ny, px, py
204
+
205
+ # -------------------------
206
+ # Numba kernels for link_contours
207
+ # -------------------------
208
+
209
+ @nb.njit(cache=True, fastmath=True, boundscheck=True)
210
+ def _trace_one_direction(
211
+ x0, y0,
212
+ dir_flag, # 1 = forward, 2 = backward
213
+ ismax, px, py,
214
+ alpha_arr, oct4_arr,
215
+ label, indx, cross_done,
216
+ w, h,
217
+ DIRTAB, CLEARTAB,
218
+ max_angle_diff,
219
+ line_id,
220
+ out_x, out_y,
221
+ out_start
222
+ ):
223
+ """
224
+ Traces one direction starting at (x0,y0) excluding the seed itself.
225
+ Writes points to flat arrays starting at out_start.
226
+ Returns the next free output index.
227
+ """
228
+ x = x0
229
+ y = y0
230
+ p = x * w + y
231
+
232
+ last_oct = int(oct4_arr[p]) # 0..3
233
+ if dir_flag == 2:
234
+ last_oct += 4
235
+
236
+ out_i = out_start
237
+
238
+ while True:
239
+ p = x * w + y
240
+ pxx = px[p]
241
+ pyy = py[p]
242
+
243
+ alpha_p = alpha_arr[p]
244
+ octant = int(oct4_arr[p]) # 0..3
245
+
246
+ # unwrap octant to 0..7
247
+ if octant == 0 and 3 <= last_oct <= 5:
248
+ octant = 4
249
+ elif octant == 1 and 4 <= last_oct <= 6:
250
+ octant = 5
251
+ elif octant == 2 and 4 <= last_oct <= 7:
252
+ octant = 6
253
+ elif octant == 3 and (last_oct == 0 or last_oct >= 6):
254
+ octant = 7
255
+ last_oct = octant
256
+
257
+ # choose next among 3 candidates
258
+ nextismax = 0
259
+ nexti = 1
260
+ mindiff = 1e30
261
+
262
+ for i in range(3):
263
+ xx = x + int(DIRTAB[octant, i, 0])
264
+ yy = y + int(DIRTAB[octant, i, 1])
265
+ if xx < 0 or xx >= h or yy < 0 or yy >= w:
266
+ continue
267
+ pp = xx * w + yy
268
+ if ismax[pp] == 0:
269
+ continue
270
+
271
+ npx = px[pp]
272
+ npy = py[pp]
273
+ dx = npx - pxx
274
+ dy = npy - pyy
275
+ dist = np.sqrt(dx*dx + dy*dy)
276
+
277
+ na = alpha_arr[pp]
278
+ diff = abs(alpha_p - na)
279
+ if diff >= 0.5*np.pi:
280
+ diff = np.pi - diff
281
+
282
+ score = dist + diff
283
+ if score < mindiff:
284
+ mindiff = score
285
+ nexti = i
286
+ nextismax = 1
287
+
288
+ # clear double responses
289
+ for i in range(2):
290
+ xx = x + int(CLEARTAB[octant, i, 0])
291
+ yy = y + int(CLEARTAB[octant, i, 1])
292
+ if 0 <= xx < h and 0 <= yy < w:
293
+ pp = xx * w + yy
294
+ if ismax[pp] > 0:
295
+ na = alpha_arr[pp]
296
+ diff = abs(alpha_p - na)
297
+ if diff >= 0.5*np.pi:
298
+ diff = np.pi - diff
299
+ if diff < max_angle_diff:
300
+ label[pp] = line_id
301
+ idx = indx[pp]
302
+ if idx != 0:
303
+ cross_done[idx - 1] = True
304
+
305
+ if nextismax == 0:
306
+ break
307
+
308
+ # step
309
+ x += int(DIRTAB[octant, nexti, 0])
310
+ y += int(DIRTAB[octant, nexti, 1])
311
+ pp = x * w + y
312
+
313
+ if out_i >= out_x.shape[0]:
314
+ return out_i
315
+
316
+
317
+ # append point (excluding seed)
318
+ out_x[out_i] = px[pp]
319
+ out_y[out_i] = py[pp]
320
+
321
+ out_i += 1
322
+
323
+ if label[pp] > 0:
324
+ break
325
+
326
+ label[pp] = line_id
327
+ idx = indx[pp]
328
+ if idx != 0:
329
+ cross_done[idx - 1] = True
330
+
331
+ return out_i
332
+
333
+
334
+ @nb.njit(cache=True, fastmath=True, boundscheck=True)
335
+ def _link_contours_trace_numba(
336
+ cross_x, cross_y, cross_val, cross_done,
337
+ ismax, px, py,
338
+ alpha_arr, oct4_arr,
339
+ indx,
340
+ w, h,
341
+ DIRTAB, CLEARTAB,
342
+ max_angle_diff
343
+ ):
344
+ area = cross_x.shape[0]
345
+ label = np.zeros((w*h,), dtype=np.int32)
346
+
347
+ # Worst-case points: each ridge pixel at most once per line, but safe upper bound is area*2
348
+ max_points = area * 2 + 8
349
+ pts_x = np.empty((max_points,), dtype=np.float32)
350
+ pts_y = np.empty((max_points,), dtype=np.float32)
351
+
352
+ # line offsets (start index into flat arrays)
353
+ line_offsets = np.empty((area + 1,), dtype=np.int32)
354
+ line_count = 0
355
+ out_i = 0
356
+
357
+ indx_max = 0
358
+ while True:
359
+ while indx_max < area and cross_done[indx_max]:
360
+ indx_max += 1
361
+ if indx_max == area:
362
+ break
363
+ maxv = float(cross_val[indx_max])
364
+ if maxv == 0.0:
365
+ break
366
+
367
+ x0 = int(cross_x[indx_max])
368
+ y0 = int(cross_y[indx_max])
369
+ pos0 = x0*w + y0
370
+
371
+ line_id = line_count + 1
372
+ label[pos0] = line_id
373
+ idx0 = indx[pos0]
374
+ if idx0 != 0:
375
+ cross_done[idx0 - 1] = True
376
+
377
+ if out_i >= pts_x.shape[0]:
378
+ break # or return what you have
379
+
380
+
381
+ # seed point
382
+ line_offsets[line_count] = out_i
383
+ pts_x[out_i] = px[pos0]
384
+ pts_y[out_i] = py[pos0]
385
+
386
+ alpha0 = alpha_arr[pos0] # [0,π)
387
+ out_i += 1
388
+
389
+ # clear double responses around seed (uses oct4)
390
+ octant0 = int(oct4_arr[pos0])
391
+ for i in range(2):
392
+ xx = x0 + int(CLEARTAB[octant0, i, 0])
393
+ yy = y0 + int(CLEARTAB[octant0, i, 1])
394
+ if 0 <= xx < h and 0 <= yy < w:
395
+ p = xx*w + yy
396
+ if ismax[p] > 0:
397
+ na = alpha_arr[p]
398
+ diff = abs(alpha0 - na)
399
+ if diff >= 0.5*np.pi:
400
+ diff = np.pi - diff
401
+ if diff < max_angle_diff:
402
+ label[p] = line_id
403
+ idxp = indx[p]
404
+ if idxp != 0:
405
+ cross_done[idxp - 1] = True
406
+
407
+ # Trace backward first and reverse it in place, then trace forward, so points run end to end.
408
+ tmp_start = out_i
409
+ tmp_end = _trace_one_direction(
410
+ x0, y0, 2,
411
+ ismax, px, py,
412
+ alpha_arr, oct4_arr,
413
+ label, indx, cross_done,
414
+ w, h,
415
+ DIRTAB, CLEARTAB,
416
+ max_angle_diff,
417
+ line_id,
418
+ pts_x, pts_y,
419
+ tmp_start
420
+ )
421
+ tmp_len = tmp_end - tmp_start
422
+
423
+ # reverse the backward segment in-place (so it becomes prepended)
424
+ for k in range(tmp_len // 2):
425
+ a = tmp_start + k
426
+ b = tmp_start + (tmp_len - 1 - k)
427
+ # swap x,y
428
+ tx = pts_x[a]; pts_x[a] = pts_x[b]; pts_x[b] = tx
429
+ ty = pts_y[a]; pts_y[a] = pts_y[b]; pts_y[b] = ty
430
+
431
+ out_i = tmp_end
432
+
433
+ # forward direction appends after seed+backward
434
+ out_i = _trace_one_direction(
435
+ x0, y0, 1,
436
+ ismax, px, py,
437
+ alpha_arr, oct4_arr,
438
+ label, indx, cross_done,
439
+ w, h,
440
+ DIRTAB, CLEARTAB,
441
+ max_angle_diff,
442
+ line_id,
443
+ pts_x, pts_y,
444
+ out_i
445
+ )
446
+
447
+ # keep only lines with >=2 points
448
+ line_len = out_i - line_offsets[line_count]
449
+ if line_len > 1:
450
+ line_count += 1
451
+ else:
452
+ # drop seed point
453
+ out_i = line_offsets[line_count]
454
+ label[pos0] = 0
455
+
456
+ line_offsets[line_count] = out_i
457
+
458
+ # trim outputs
459
+ pts_x = pts_x[:out_i]
460
+ pts_y = pts_y[:out_i]
461
+ line_offsets = line_offsets[:line_count+1]
462
+
463
+ return pts_x, pts_y, line_offsets
464
+
465
+
466
+
467
+ # -------------------------
468
+ # Detector
469
+ # -------------------------
470
+
471
+ class RidgeDetector:
472
+ """Represent ridge detector state used across processing and visualization workflows."""
473
+ DERIV_R, DERIV_C, DERIV_RR, DERIV_RC, DERIV_CC = 1, 2, 3, 4, 5
474
+ MODE_LIGHT, MODE_DARK = 1, 2
475
+
476
+ MAX_SIZE_MASK_0 = 3.09023230616781
477
+ MAX_SIZE_MASK_1 = 3.46087178201605
478
+ MAX_SIZE_MASK_2 = 3.82922419517181
479
+
480
+ SQRT_2_PI_INV = 0.398942280401432677939946059935
481
+ PIXEL_BOUNDARY = 0.6
482
+ MAX_ANGLE_DIFFERENCE = math.pi / 6.0
483
+
484
+ _DIRTAB = np.array([
485
+ [[ 1, 0],[ 1,-1],[ 1, 1]],
486
+ [[ 1, 1],[ 1, 0],[ 0, 1]],
487
+ [[ 0, 1],[ 1, 1],[-1, 1]],
488
+ [[-1, 1],[ 0, 1],[-1, 0]],
489
+ [[-1, 0],[-1, 1],[-1,-1]],
490
+ [[-1,-1],[-1, 0],[ 0,-1]],
491
+ [[ 0,-1],[-1,-1],[ 1,-1]],
492
+ [[ 1,-1],[ 0,-1],[ 1, 0]],
493
+ ], dtype=np.int32)
494
+
495
+ _CLEARTAB = np.array([
496
+ [[ 0, 1],[ 0,-1]],
497
+ [[-1, 1],[ 1,-1]],
498
+ [[-1, 0],[ 1, 0]],
499
+ [[-1,-1],[ 1, 1]],
500
+ [[ 0,-1],[ 0, 1]],
501
+ [[ 1,-1],[-1, 1]],
502
+ [[ 1, 0],[-1, 0]],
503
+ [[ 1, 1],[-1,-1]],
504
+ ], dtype=np.int32)
505
+
506
+ # -------------------------
507
+ # Public API
508
+ # -------------------------
509
+
510
+ @classmethod
511
+ def detect_ridges(
512
+ cls,
513
+ image2d: np.ndarray,
514
+ *,
515
+ sigma: float = 1.5,
516
+ low: float = 5.0,
517
+ high: float = 10.0,
518
+ polarity: str = "dark",
519
+ ) -> List[np.ndarray]:
520
+ img = np.asarray(image2d, dtype=np.float32)
521
+ if img.ndim != 2:
522
+ raise ValueError("image must be 2D grayscale")
523
+
524
+ h, w = img.shape
525
+ mode = cls.MODE_DARK if polarity.lower() == "dark" else cls.MODE_LIGHT
526
+
527
+ dr, dc, drr, drc, dcc = cls._gauss_derivatives(img, sigma)
528
+ ismax, ev, nx, ny, px, py = cls._ridge_candidates(dr, dc, drr, drc, dcc, w, h, low, high, mode)
529
+
530
+ alpha, oct4 = cls._precompute_angles(nx, ny)
531
+ return cls._link_contours(ismax, ev, px, py, w, h, alpha, oct4)
532
+
533
+ # -------------------------
534
+ # Helpers
535
+ # -------------------------
536
+
537
+ @staticmethod
538
+ def _mask_size(maxv: float, sigma: float) -> int:
539
+ return int(math.ceil(maxv * sigma))
540
+
541
+
542
+
543
+
544
+ @staticmethod
545
+ def _phi0(x: float, sigma: float) -> float:
546
+ return 0.5 * (1.0 + math.erf(x / (sigma * math.sqrt(2.0))))
547
+
548
+ @classmethod
549
+ def _phi1(cls, x: float, sigma: float) -> float:
550
+ t = x / sigma
551
+ return cls.SQRT_2_PI_INV / sigma * math.exp(-0.5 * t * t)
552
+
553
+ @classmethod
554
+ def _phi2(cls, x: float, sigma: float) -> float:
555
+ t = x / sigma
556
+ return -x * cls.SQRT_2_PI_INV / (sigma ** 3.0) * math.exp(-0.5 * t * t)
557
+
558
+ @classmethod
559
+ def _gauss_mask_0(cls, sigma: float) -> Tuple[np.ndarray, int]:
560
+ n = cls._mask_size(cls.MAX_SIZE_MASK_0, sigma)
561
+ h = np.zeros((2 * n + 1,), dtype=np.float64)
562
+ for i in range(-n + 1, n):
563
+ h[n + i] = cls._phi0(-i + 0.5, sigma) - cls._phi0(-i - 0.5, sigma)
564
+ h[0] = 1.0 - cls._phi0(n - 0.5, sigma)
565
+ h[2 * n] = cls._phi0(-n + 0.5, sigma)
566
+ return h, n
567
+
568
+ @classmethod
569
+ def _gauss_mask_1(cls, sigma: float) -> Tuple[np.ndarray, int]:
570
+ n = cls._mask_size(cls.MAX_SIZE_MASK_1, sigma)
571
+ h = np.zeros((2 * n + 1,), dtype=np.float64)
572
+ for i in range(-n + 1, n):
573
+ h[n + i] = cls._phi1(-i + 0.5, sigma) - cls._phi1(-i - 0.5, sigma)
574
+ h[0] = -cls._phi1(n - 0.5, sigma)
575
+ h[2 * n] = cls._phi1(-n + 0.5, sigma)
576
+ return h, n
577
+
578
+ @classmethod
579
+ def _gauss_mask_2(cls, sigma: float) -> Tuple[np.ndarray, int]:
580
+ n = cls._mask_size(cls.MAX_SIZE_MASK_2, sigma)
581
+ h = np.zeros((2 * n + 1,), dtype=np.float64)
582
+ for i in range(-n + 1, n):
583
+ h[n + i] = cls._phi2(-i + 0.5, sigma) - cls._phi2(-i - 0.5, sigma)
584
+ h[0] = -cls._phi2(n - 0.5, sigma)
585
+ h[2 * n] = cls._phi2(-n + 0.5, sigma)
586
+ return h, n
587
+
588
+ # -------------------------
589
+ # Convolution (Numba-accelerated)
590
+ # -------------------------
591
+
592
+ @classmethod
593
+ def _convolve_gauss(cls, image_flat: np.ndarray, w: int, h: int, sigma: float, deriv: int) -> np.ndarray:
594
+ if deriv == cls.DERIV_R:
595
+ hr, nr = cls._gauss_mask_1(sigma); hc, nc = cls._gauss_mask_0(sigma)
596
+ elif deriv == cls.DERIV_C:
597
+ hr, nr = cls._gauss_mask_0(sigma); hc, nc = cls._gauss_mask_1(sigma)
598
+ elif deriv == cls.DERIV_RR:
599
+ hr, nr = cls._gauss_mask_2(sigma); hc, nc = cls._gauss_mask_0(sigma)
600
+ elif deriv == cls.DERIV_RC:
601
+ hr, nr = cls._gauss_mask_1(sigma); hc, nc = cls._gauss_mask_1(sigma)
602
+ elif deriv == cls.DERIV_CC:
603
+ hr, nr = cls._gauss_mask_0(sigma); hc, nc = cls._gauss_mask_2(sigma)
604
+ else:
605
+ raise ValueError("unknown derivative type")
606
+
607
+ # Numba prefers contiguous arrays
608
+ hr = np.ascontiguousarray(hr)
609
+ hc = np.ascontiguousarray(hc)
610
+
611
+ tmp = _convolve_rows_flat(image_flat, hr, nr, w, h)
612
+ out = _convolve_cols_flat(tmp, hc, nc, w, h)
613
+ return out
614
+
615
+ @classmethod
616
+ def _gauss_derivatives(cls, img: np.ndarray, sigma: float):
617
+ h, w = img.shape
618
+ flat = np.ascontiguousarray(img.reshape(-1))
619
+
620
+ dr = cls._convolve_gauss(flat, w, h, sigma, cls.DERIV_R)
621
+ dc = cls._convolve_gauss(flat, w, h, sigma, cls.DERIV_C)
622
+ drr = cls._convolve_gauss(flat, w, h, sigma, cls.DERIV_RR)
623
+ drc = cls._convolve_gauss(flat, w, h, sigma, cls.DERIV_RC)
624
+ dcc = cls._convolve_gauss(flat, w, h, sigma, cls.DERIV_CC)
625
+ return dr, dc, drr, drc, dcc
626
+
627
+ # -------------------------
628
+ # Ridge candidates (Numba-accelerated)
629
+ # -------------------------
630
+
631
+ @classmethod
632
+ def _ridge_candidates(cls, dr, dc, drr, drc, dcc, w, h, low, high, mode):
633
+ # mode is 1/2 already. Keep pixel boundary exact.
634
+ return _ridge_candidates_jit(dr, dc, drr, drc, dcc, w, h, low, high, mode, cls.PIXEL_BOUNDARY)
635
+
636
+ # -------------------------
637
+ # Linking
638
+ # -------------------------
639
+
640
+
641
+ @staticmethod
642
+ def _threshold_runs(ismax: np.ndarray, minv: int, w: int, h: int) -> List[Tuple[int, int, int]]:
643
+ """
644
+ ismax is flattened (w*h,).
645
+ Returns list of (r, cb, ce) with ismax[r, cb:ce+1] >= minv.
646
+ """
647
+ m = (ismax.reshape(h, w) >= minv) # bool (h,w)
648
+
649
+ # Find transitions per row: start where False->True, end where True->False
650
+ # Pad with False at both ends so runs touching borders are handled.
651
+ mp = np.pad(m, ((0, 0), (1, 1)), mode="constant", constant_values=False)
652
+
653
+ starts = np.flatnonzero((~mp[:, :-1]) & (mp[:, 1:])) # indices in flattened (h*(w+1))
654
+ ends = np.flatnonzero((mp[:, :-1]) & (~mp[:, 1:]))
655
+
656
+ # Convert flattened indices to (row, col) in the padded grid
657
+ Wp = w + 1
658
+ rs = starts // Wp
659
+ cs = starts % Wp
660
+ re = ends // Wp
661
+ ce = (ends % Wp) - 1 # inclusive end in original coords
662
+
663
+ # starts/ends are aligned per row because of padding; rs==re always
664
+ # Build python list of tuples (row, cb, ce)
665
+ return list(zip(rs.astype(int).tolist(), cs.astype(int).tolist(), ce.astype(int).tolist()))
666
+
667
+
668
+ @staticmethod
669
+ def _precompute_angles(nx, ny):
670
+ # Flatten to 1D to match the kernel indexing (p = x*w + y)
671
+ nx1 = np.asarray(nx, np.float32).reshape(-1)
672
+ ny1 = np.asarray(ny, np.float32).reshape(-1)
673
+
674
+ # alpha = atan2(nx, -ny) normalized to [0, π)
675
+ alpha = np.arctan2(nx1, -ny1).astype(np.float32)
676
+ alpha = np.where(alpha < 0.0, alpha + 2.0*np.pi, alpha)
677
+ alpha = np.where(alpha >= np.pi, alpha - np.pi, alpha) # now [0,π)
678
+
679
+ # oct4 = round(4/pi*alpha) mod 4
680
+ oct4 = (np.floor((4.0/np.pi) * alpha + 0.5).astype(np.int32) & 3).astype(np.uint8)
681
+
682
+ return alpha, oct4
683
+
684
+ @classmethod
685
+ def _link_contours(cls, ismax, ev, px, py, w, h, alpha_arr, oct4_arr) -> List[np.ndarray]:
686
+
687
+ indx = np.zeros((w * h,), dtype=np.int32)
688
+
689
+ runs = cls._threshold_runs(ismax, 2, w, h)
690
+ area = sum((ce - cb + 1) for (_, cb, ce) in runs)
691
+
692
+ if area == 0:
693
+ return []
694
+
695
+ cross_x = np.empty((area,), dtype=np.int16)
696
+ cross_y = np.empty((area,), dtype=np.int16)
697
+ cross_val = np.empty((area,), dtype=np.float64)
698
+ cross_done = np.zeros((area,), dtype=np.bool_)
699
+ k = 0
700
+ for r, cb, ce in runs:
701
+ base = r * w
702
+ for c in range(cb, ce + 1):
703
+ pos = base + c
704
+ cross_x[k] = r
705
+ cross_y[k] = c
706
+ cross_val[k] = float(ev[pos])
707
+ k += 1
708
+
709
+ order = np.argsort(-cross_val, kind="quicksort")
710
+ cross_x = cross_x[order]; cross_y = cross_y[order]; cross_val = cross_val[order]
711
+
712
+ for i in range(area):
713
+ pos = int(cross_x[i]) * w + int(cross_y[i])
714
+ indx[pos] = i + 1
715
+
716
+
717
+ # --- NUMBA TRACE HERE ---
718
+ DIRTAB = np.asarray(cls._DIRTAB, dtype=np.int8)
719
+ CLEARTAB = np.asarray(cls._CLEARTAB, dtype=np.int8)
720
+
721
+ pts_x, pts_y, offsets = _link_contours_trace_numba(
722
+ cross_x.astype(np.int32),
723
+ cross_y.astype(np.int32),
724
+ cross_val.astype(np.float32),
725
+ cross_done, # bool ok
726
+ ismax.astype(np.uint8), # or np.int8
727
+ px.astype(np.float32),
728
+ py.astype(np.float32),
729
+ alpha_arr.astype(np.float32),
730
+ oct4_arr.astype(np.uint8),
731
+ indx.astype(np.int32),
732
+ w, h,
733
+ DIRTAB, CLEARTAB,
734
+ float(cls.MAX_ANGLE_DIFFERENCE),
735
+ )
736
+
737
+ # --- WRAP NUMBA OUTPUTS TO PY OBJECTS ---
738
+ lines = []
739
+ for i in range(len(offsets) - 1):
740
+ a = int(offsets[i]); b = int(offsets[i+1])
741
+ if b - a <= 1:
742
+ continue
743
+ points_xy = np.empty((b - a, 2), np.float32)
744
+ points_xy[:, 0] = pts_y[a:b]
745
+ points_xy[:, 1] = pts_x[a:b]
746
+ lines.append(points_xy)
747
+
748
+ return lines
src/fiberpose/utils.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared numeric and image helper utilities used across Fiberpose modules."""
2
+
3
+ import colorsys
4
+ import numpy as np
5
+ from numba import njit
6
+
7
+
8
+
9
+ def label_to_rgb(label: int) -> tuple[int, int, int]:
10
+ """Deterministically map a positive label ID to a vivid RGB color."""
11
+ if label <= 0:
12
+ return (0, 0, 0)
13
+ hue = (label * 0.6180339887498949) % 1.0 # golden ratio multiplier for good spacing
14
+ sat = 0.55 + 0.35 * (((label * 0.2171) % 1.0))
15
+ val = 0.85
16
+ r, g, b = colorsys.hsv_to_rgb(hue, sat, val)
17
+ return int(round(r * 255)), int(round(g * 255)), int(round(b * 255))
18
+
19
+
20
+ def labels_to_color(labels: np.ndarray | None) -> np.ndarray | None:
21
+ """Render a label-id map into an RGB visualization image."""
22
+ if labels is None:
23
+ return None
24
+ labels_i64 = np.asarray(labels, dtype=np.int64)
25
+ if labels_i64.ndim != 2:
26
+ return None
27
+ if labels_i64.size == 0:
28
+ return np.zeros(labels_i64.shape + (3,), dtype=np.uint8)
29
+ # One color per distinct id (label_to_rgb maps ids <= 0 to black), then a single gather.
30
+ ids, inverse = np.unique(labels_i64, return_inverse=True)
31
+ palette = np.array([label_to_rgb(int(v)) for v in ids], dtype=np.uint8).reshape(-1, 3)
32
+ return palette[inverse.reshape(labels_i64.shape)]
33
+
34
+ # ------------- image helpers -------------
35
+ def to_uint8_for_view(img: np.ndarray | None) -> np.ndarray | None:
36
+ if img is None:
37
+ return None
38
+ arr = img.astype(np.float32, copy=False)
39
+ if np.isnan(arr).any() or np.isinf(arr).any():
40
+ arr = np.nan_to_num(arr, nan=0.0, posinf=0.0, neginf=0.0)
41
+ amin, amax = float(arr.min()), float(arr.max())
42
+ if amax <= amin:
43
+ return np.zeros(arr.shape, dtype=np.uint8)
44
+ arr = (arr - amin) / (amax - amin)
45
+ return (arr * 255.0).clip(0, 255).astype(np.uint8)
46
+
47
+
48
+ def ensure_rgb_u8(img: np.ndarray | None) -> np.ndarray | None:
49
+ if img is None:
50
+ return None
51
+ if img.ndim == 2:
52
+ u8 = to_uint8_for_view(img)
53
+ return np.stack([u8, u8, u8], axis=-1)
54
+ if img.ndim == 3:
55
+ if img.shape[2] == 1:
56
+ ch = to_uint8_for_view(img[..., 0])
57
+ return np.stack([ch, ch, ch], axis=-1)
58
+ if img.dtype != np.uint8:
59
+ return to_uint8_for_view(img)[..., :3]
60
+ return img[..., :3]
61
+ return ensure_rgb_u8(to_uint8_for_view(img))
62
+
63
+ # ------------- core math helpers -------------
64
+ @njit(cache=True)
65
+ def _normalize(v, eps=1e-12):
66
+ n = np.sqrt(np.sum(v * v))
67
+ return v / (n + eps)
68
+
69
+ @njit(cache=True)
70
+ def _bilinear(arr, y, x):
71
+ """Bilinear sample arr at (y, x) with clamped borders. arr is HxW."""
72
+ h, w = arr.shape
73
+ y0 = int(np.floor(y))
74
+ x0 = int(np.floor(x))
75
+ y1 = y0 + 1
76
+ x1 = x0 + 1
77
+
78
+ y0c = 0 if y0 < 0 else (h - 1 if y0 >= h else y0)
79
+ y1c = 0 if y1 < 0 else (h - 1 if y1 >= h else y1)
80
+ x0c = 0 if x0 < 0 else (w - 1 if x0 >= w else x0)
81
+ x1c = 0 if x1 < 0 else (w - 1 if x1 >= w else x1)
82
+
83
+ wy = y - y0
84
+ wx = x - x0
85
+ a = arr[y0c, x0c]
86
+ b = arr[y0c, x1c]
87
+ c = arr[y1c, x0c]
88
+ d = arr[y1c, x1c]
89
+ return (1-wy) * ((1-wx)*a + wx*b) + wy * ((1-wx)*c + wx*d)
90
+
91
+ @njit(cache=True)
92
+ def _sample_vec2(gx, gy, y, x):
93
+ """Sample gradient vector [dy, dx] at (y,x)."""
94
+ return np.array([_bilinear(gy, y, x), _bilinear(gx, y, x)])
95
+
96
+ @njit(cache=True)
97
+ def _tangent2d(centerline, k):
98
+ """Unit tangent at index k using central/one-sided differences. centerline is Nx2 in (y,x)."""
99
+ N = len(centerline)
100
+ if k == 0:
101
+ t = centerline[1] - centerline[0]
102
+ elif k == N-1:
103
+ t = centerline[-1] - centerline[-2]
104
+ else:
105
+ t = centerline[k+1] - centerline[k-1]
106
+ return _normalize(t)
107
+
108
+ @njit(cache=True)
109
+ def _rot90_ccw(v):
110
+ """Rotate (y,x) by +90° in image coordinates."""
111
+ return np.array([-v[1], v[0]])
112
+
113
+ # ------------- normals from DT -------------
114
+ @njit(cache=True)
115
+ def normals_from_dt_2d(centerline, dt, gx, gy, alpha=0.5, iters=3, tau_g=1e-3, eps=1e-8):
116
+ """
117
+ centerline: (N,2) float array of (y,x) points (same pixel coords as dt)
118
+ dt: HxW float distance transform
119
+ gx, gy: HxW gradients of dt (e.g., gx, gy = np.gradient(dt))
120
+ alpha: probe step as fraction of local radius (h = alpha * r)
121
+ iters: fixed-point iterations per point
122
+ tau_g: threshold on |(g+ - g-)| below which we fall back to n0/previous
123
+ returns: (N,2) unit normals (y,x) with continuity enforced
124
+ """
125
+ N = len(centerline)
126
+ normals = np.zeros((N, 2), dtype=np.float64)
127
+ n_iter = max(1, iters)
128
+
129
+ for k in range(N):
130
+ y, x = centerline[k]
131
+ r = _bilinear(dt, y, x)
132
+ h = alpha * max(r, 1e-6) # always probe a tiny bit, even if r~0
133
+
134
+ # initial guess n0 from tangent (rotate by 90°)
135
+ t = _tangent2d(centerline, k)
136
+ n = _rot90_ccw(t)
137
+
138
+ # prefer previous orientation if available (continuity)
139
+ if k > 0 and np.dot(n, normals[k-1]) < 0:
140
+ n = -n
141
+
142
+ # fixed-point refinement
143
+ for _ in range(n_iter):
144
+ yp, xp = y + h * n[0], x + h * n[1]
145
+ ym, xm = y - h * n[0], x - h * n[1]
146
+ gp = _sample_vec2(gx, gy, yp, xp) # ∇DT at +h along n
147
+ gm = _sample_vec2(gx, gy, ym, xm) # ∇DT at -h along n
148
+ d = 0.5 * (gp - gm) # averaged direction (normal candidate)
149
+ mag = np.linalg.norm(d)
150
+ if mag < tau_g:
151
+ break
152
+ n_new = d / (mag + eps)
153
+ # keep orientation continuous along the curve
154
+ if k > 0 and np.dot(n_new, normals[k-1]) < 0:
155
+ n_new = -n_new
156
+ n = n_new
157
+
158
+ normals[k] = _normalize(n)
159
+
160
+ return normals
161
+
162
+ # ------------- geometry helpers -------------
163
+ def resample_polyline_xy(points_xy: np.ndarray, step: float) -> np.ndarray:
164
+ """Resample an open polyline (N,2) in XY to ~equal arc-length spacing of 'step'."""
165
+ pts = np.asarray(points_xy, dtype=np.float64).reshape(-1, 2)
166
+ if len(pts) < 2:
167
+ return pts.copy()
168
+
169
+ seg = pts[1:] - pts[:-1]
170
+ seg_len = np.linalg.norm(seg, axis=1)
171
+ cum = np.concatenate([[0.0], np.cumsum(seg_len)])
172
+ L = cum[-1]
173
+ if L <= 1e-6:
174
+ return pts[:1].copy()
175
+
176
+ s_targets = np.arange(0.0, L + 1e-9, float(step))
177
+ if s_targets[-1] < L:
178
+ s_targets = np.append(s_targets, L)
179
+
180
+ out = []
181
+ k = 0
182
+ for s in s_targets:
183
+ while k + 1 < len(cum) and cum[k+1] < s:
184
+ k += 1
185
+ if k + 1 >= len(cum):
186
+ out.append(pts[-1])
187
+ else:
188
+ ds = cum[k+1] - cum[k]
189
+ if ds <= 1e-12:
190
+ out.append(pts[k].copy())
191
+ else:
192
+ a = (s - cum[k]) / ds
193
+ out.append(pts[k] * (1 - a) + pts[k+1] * a)
194
+ return np.asarray(out, dtype=np.float64)
src/fiberpose/web/__init__.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio web interface: ``fiberpose --web``.
2
+
3
+ ``build_demo(config)`` only describes the page; the caller decides how to serve it.
4
+ Analysis settings come from the same config file as the GUI and CLI.
5
+ Host, port and proxy path come from Gradio's own environment variables
6
+ (``GRADIO_SERVER_NAME``, ``GRADIO_SERVER_PORT``, ``GRADIO_ROOT_PATH``);
7
+ ``FIBERPOSE_MAX_UPLOAD`` caps the upload size (default ``50mb``).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from dataclasses import replace
14
+
15
+ import gradio as gr
16
+
17
+ from ..api import FiberposeError
18
+ from ..domain import AppConfig
19
+ from ..paths import EXAMPLE_IMAGE_PATH
20
+ from . import callbacks as cb
21
+
22
+ __all__ = ["build_demo", "launch"]
23
+
24
+
25
+ def _download(path: str | None):
26
+ """Update for a save button: offer `path`, or stay disabled without one."""
27
+ return gr.DownloadButton(value=path, interactive=bool(path))
28
+
29
+
30
+ def build_demo(config: AppConfig | None = None) -> gr.Blocks:
31
+ config = config or AppConfig(use_gpu=False)
32
+
33
+ def run(path, pixel_size, unit, invert, edge_threshold, previous):
34
+ if not path:
35
+ raise gr.Error("Upload an image first.")
36
+ settings = replace(config, watershed_grad_threshold=edge_threshold)
37
+ try:
38
+ session = cb.analyze_file(path, settings, pixel_size, unit, invert, previous)
39
+ except FiberposeError as exc:
40
+ raise gr.Error(str(exc)) from exc
41
+ if session.result.message:
42
+ gr.Info(session.result.message)
43
+ figure, svg = cb.charts(session)
44
+ archive = cb.results_zip(session) # also writes the CSV it contains
45
+ csv = session.path("measurements.csv") if session.result.summary else None
46
+ return session, cb.summary_table(session), figure, *map(_download, (svg, csv, archive))
47
+
48
+ def show(session, view):
49
+ path = cb.view_png(session, view)
50
+ return path, _download(path) # the same file is displayed and offered by "Save view"
51
+
52
+ with gr.Blocks(title="Fiberpose") as demo:
53
+ gr.Markdown(
54
+ "# Fiberpose\nSegmentation and morphometry of fibrous microstructures. Upload a micrograph "
55
+ "(or click the example) and press **Analyze**. [Source code](https://github.com/vikba/Fiberpose)"
56
+ )
57
+ session = gr.State() # this browser tab's analysed image (callbacks.Session)
58
+ with gr.Row(equal_height=True): # settings, each above the image it applies to
59
+ with gr.Row(variant="panel"): # segmentation settings
60
+ pixel_size = gr.Number(1.0, label="Pixel size", minimum=0, min_width=80)
61
+ unit = gr.Dropdown(["px", "nm", "µm", "mm"], value="px", label="Unit", allow_custom_value=True, min_width=80)
62
+ edge_threshold = gr.Number(
63
+ config.watershed_grad_threshold, label="Edge threshold", minimum=0, maximum=1, step=0.05,
64
+ min_width=80, info="min |∇DT|; lower = wider.",
65
+ )
66
+ invert = gr.Checkbox(label="Invert", info="for dark fibers", min_width=80)
67
+ with gr.Row(variant="panel"):
68
+ view = gr.Radio(cb.VIEWS, value="Diameters", label="View")
69
+ with gr.Row(equal_height=True):
70
+ image = gr.Image(type="filepath", label="Image", height=480)
71
+ output = gr.Image(label="Result", interactive=False, height=480)
72
+ with gr.Row():
73
+ with gr.Column(): # under the input
74
+ with gr.Row():
75
+ button = gr.Button("Analyze", variant="primary")
76
+ gr.HTML() # empty half: keeps the button at half width
77
+ gr.Examples([[str(EXAMPLE_IMAGE_PATH)]], inputs=image)
78
+ summary = gr.Markdown()
79
+ with gr.Column(): # under the result
80
+ with gr.Row():
81
+ save_view = gr.DownloadButton("Save view (PNG)", size="sm", interactive=False)
82
+ save_charts = gr.DownloadButton("Save charts (SVG)", size="sm", interactive=False)
83
+ save_csv = gr.DownloadButton("Save measurements (CSV)", size="sm", interactive=False)
84
+ save_all = gr.DownloadButton("Save results (ZIP)", size="sm", interactive=False)
85
+ plots = gr.Plot(label="Distributions")
86
+
87
+ inputs = [image, pixel_size, unit, invert, edge_threshold, session]
88
+ for trigger in (button.click, edge_threshold.submit): # the threshold reuses the model prediction
89
+ analysed = trigger(run, inputs, [session, summary, plots, save_charts, save_csv, save_all])
90
+ analysed.success(show, [session, view], [output, save_view])
91
+ view.change(show, [session, view], [output, save_view])
92
+ return demo
93
+
94
+
95
+ def launch(config: AppConfig | None = None) -> None:
96
+ build_demo(config).launch(
97
+ max_file_size=os.environ.get("FIBERPOSE_MAX_UPLOAD", "50mb"), footer_links=[]
98
+ )
src/fiberpose/web/callbacks.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What the web page computes: plain functions on a ``Session``, no Gradio."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import tempfile
7
+ import zipfile
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ import imageio.v3 as iio
12
+ import matplotlib
13
+ import numpy as np
14
+ from matplotlib.figure import Figure
15
+
16
+ from ..api import AnalysisResult, analyze
17
+ from ..domain import AppConfig
18
+ from ..io_export import BatchResultExporter
19
+ from ..render import render
20
+
21
+ # (shown label, render() view name)
22
+ VIEWS = [("Diameters", "Diameters"), ("Orientations", "Orientations"), ("Overlay", "Overlay"),
23
+ ("Outline", "Segmentation outline"), ("DT", "DT")]
24
+
25
+ LABELS = { # summary key -> name shown on the page
26
+ "diam_mean": "Mean diameter", "diam_median": "Median diameter", "diam_mode": "Mode diameter",
27
+ "diam_sd": "Diameter SD", "mean_angle_deg": "Mean angle", "std_angle_deg": "Angle SD",
28
+ "orientation_index": "Orientation index", "sample_count": "Samples",
29
+ "fragments_with_centerlines": "Fibers measured",
30
+ }
31
+ ACCENT = "#f97316"
32
+
33
+
34
+ @dataclass
35
+ class Session:
36
+ """One analysed image and the folder its downloadable files are written to."""
37
+
38
+ result: AnalysisResult
39
+ source: str # path of the input image
40
+ folder: tempfile.TemporaryDirectory # deleted together with the session
41
+
42
+ def path(self, suffix: str) -> str:
43
+ return os.path.join(self.folder.name, f"{Path(self.source).stem}_{suffix}")
44
+
45
+
46
+ def analyze_file(
47
+ path: str, config: AppConfig, pixel_size: float, unit: str, invert: bool, previous: Session | None = None
48
+ ) -> Session:
49
+ """Run the pipeline on an image file; a `previous` session of the same file skips its unchanged stages."""
50
+ same = previous.result if previous and previous.source == path else None
51
+ image = same.frame.orig_img if same else iio.imread(path) # read from disk to keep the bit depth
52
+ result = analyze(image, config, pixel_size=pixel_size or 1.0, unit=unit, invert=invert, previous=same)
53
+ return Session(result, path, tempfile.TemporaryDirectory(prefix="fiberpose_"))
54
+
55
+
56
+ def view_png(session: Session | None, view: str) -> str | None:
57
+ """PNG of `view`; measurement views fall back to the overlay when nothing was measured."""
58
+ if session is None:
59
+ return None
60
+ path = session.path(f"{view.replace(' ', '_').lower()}.png")
61
+ if not os.path.exists(path):
62
+ image = render(session.result.frame, view)
63
+ iio.imwrite(path, render(session.result.frame, "Overlay") if image is None else image)
64
+ return path
65
+
66
+
67
+ def summary_table(session: Session) -> str:
68
+ """Markdown table of the summary: readable names, two decimals, units."""
69
+ result, rows = session.result, []
70
+ for key, label in LABELS.items():
71
+ value = result.summary.get(key)
72
+ if value is not None:
73
+ unit = result.unit if key.startswith("diam") else "°" if "angle" in key else ""
74
+ rows.append(f"| {label} | {value:.2f} {unit} |" if isinstance(value, float) else f"| {label} | {value} |")
75
+ return "\n".join(["| Summary | |", "|---|---|", *rows]) if rows else ""
76
+
77
+
78
+ def charts(session: Session) -> tuple[Figure, str]:
79
+ """Diameter and orientation histograms, as a figure for the page and an SVG file."""
80
+ result = session.result
81
+ plots = (
82
+ (result.diameters, f"Diameter ({result.unit})", "median", result.summary.get("diam_median")),
83
+ (result.angles_deg, "Orientation (deg)", "mean", result.summary.get("mean_angle_deg")),
84
+ )
85
+ with matplotlib.rc_context({"font.size": 12, "axes.spines.top": False, "axes.spines.right": False}):
86
+ fig = Figure(figsize=(8, 7), layout="constrained")
87
+ for ax, (values, label, statistic, marker) in zip(fig.subplots(2, 1), plots):
88
+ ax.hist(values[np.isfinite(values)], bins=40, color=ACCENT)
89
+ ax.set(xlabel=label, ylabel="Samples")
90
+ if marker is not None:
91
+ ax.axvline(marker, color="0.25", linestyle="--", label=f"{statistic} {marker:.2f}")
92
+ ax.legend(frameon=False)
93
+ path = session.path("charts.svg")
94
+ fig.savefig(path)
95
+ return fig, path
96
+
97
+
98
+ def results_zip(session: Session) -> str:
99
+ """Everything in one archive: every view, the charts, the label map and the measurements table."""
100
+ files = [view_png(session, view) for _label, view in VIEWS] + [charts(session)[1], session.path("labels.tif")]
101
+ iio.imwrite(files[-1], session.result.labels)
102
+ if session.result.summary: # the same CSV the desktop app exports
103
+ files.append(session.path("measurements.csv"))
104
+ BatchResultExporter()._write_samples_csv(session.result.frame, files[-1])
105
+ path = session.path("results.zip")
106
+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as archive:
107
+ for file in files:
108
+ archive.write(file, os.path.basename(file))
109
+ return path