bioimageflow-segmentation-tools 0.1.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,795 @@
1
+ """Lightweight classical segmentation tools."""
2
+
3
+ from collections import deque
4
+ from pathlib import Path
5
+ from typing import Annotated, Any
6
+
7
+ from bioimageflow_core import (
8
+ Arguments,
9
+ Category,
10
+ Connectable,
11
+ GENERAL_ENV,
12
+ GUIMeta,
13
+ ImageSpec,
14
+ IOModel,
15
+ Layout,
16
+ ProcessingTool,
17
+ Semantic,
18
+ Template,
19
+ )
20
+
21
+
22
+ def _neighbors(index: tuple[int, ...], shape: tuple[int, ...]) -> list[tuple[int, ...]]:
23
+ neighbors = []
24
+ for axis, coordinate in enumerate(index):
25
+ if coordinate > 0:
26
+ lower = list(index)
27
+ lower[axis] -= 1
28
+ neighbors.append(tuple(lower))
29
+ if coordinate + 1 < shape[axis]:
30
+ upper = list(index)
31
+ upper[axis] += 1
32
+ neighbors.append(tuple(upper))
33
+ return neighbors
34
+
35
+
36
+ def _label_connected(mask: Any) -> Any:
37
+ import numpy as np
38
+
39
+ foreground = np.asarray(mask, dtype=bool)
40
+ labels = np.zeros(foreground.shape, dtype=np.uint32)
41
+ next_label = 1
42
+
43
+ for start in np.argwhere(foreground):
44
+ start_index = tuple(int(v) for v in start)
45
+ if labels[start_index] != 0:
46
+ continue
47
+
48
+ queue: deque[tuple[int, ...]] = deque([start_index])
49
+ labels[start_index] = next_label
50
+ while queue:
51
+ current = queue.popleft()
52
+ for neighbor in _neighbors(current, foreground.shape):
53
+ if foreground[neighbor] and labels[neighbor] == 0:
54
+ labels[neighbor] = next_label
55
+ queue.append(neighbor)
56
+
57
+ next_label += 1
58
+
59
+ return labels
60
+
61
+
62
+ def _relabel_sequential(labels: Any, min_size: int = 0) -> tuple[Any, int]:
63
+ import numpy as np
64
+
65
+ source = np.asarray(labels)
66
+ output = np.zeros(source.shape, dtype=np.uint32)
67
+ next_label = 1
68
+ for label in np.unique(source):
69
+ label_int = int(label)
70
+ if label_int == 0:
71
+ continue
72
+ mask = source == label_int
73
+ if int(mask.sum()) < min_size:
74
+ continue
75
+ output[mask] = next_label
76
+ next_label += 1
77
+ return output, next_label - 1
78
+
79
+
80
+ def _write_labels(path: Path, labels: Any) -> None:
81
+ import imageio.v3 as iio
82
+ import numpy as np
83
+
84
+ path.parent.mkdir(parents=True, exist_ok=True)
85
+ array = np.asarray(labels)
86
+ kwargs = {"photometric": "minisblack"} if array.ndim >= 3 else {}
87
+ iio.imwrite(str(path), array, **kwargs)
88
+
89
+
90
+ def _label_skimage(mask: Any) -> Any:
91
+ import numpy as np
92
+ from skimage import measure
93
+
94
+ return np.asarray(measure.label(mask)).astype("uint32", copy=False)
95
+
96
+
97
+ def _distance_transform(mask: Any) -> Any:
98
+ try:
99
+ from scipy import ndimage as ndi
100
+
101
+ return ndi.distance_transform_edt(mask)
102
+ except ImportError:
103
+ from skimage.morphology import medial_axis
104
+
105
+ _, distance = medial_axis(mask, return_distance=True)
106
+ return distance
107
+
108
+
109
+ def _distance_watershed(mask: Any, min_distance: int) -> tuple[Any, int]:
110
+ import numpy as np
111
+ from skimage import measure
112
+ from skimage.feature import peak_local_max
113
+ from skimage.segmentation import watershed
114
+
115
+ foreground = np.asarray(mask, dtype=bool)
116
+ if not foreground.any():
117
+ return np.zeros(foreground.shape, dtype=np.uint32), 0
118
+
119
+ distance = _distance_transform(foreground)
120
+ peak_coordinates = peak_local_max(
121
+ distance,
122
+ labels=foreground,
123
+ min_distance=max(1, int(min_distance)),
124
+ exclude_border=False,
125
+ )
126
+ markers = np.zeros(foreground.shape, dtype=np.uint32)
127
+ for marker_label, coordinate in enumerate(peak_coordinates, start=1):
128
+ markers[tuple(int(value) for value in coordinate)] = marker_label
129
+ if markers.max() == 0:
130
+ markers = np.asarray(measure.label(foreground)).astype("uint32", copy=False)
131
+
132
+ labels = np.asarray(watershed(-distance, markers, mask=foreground)).astype(
133
+ "uint32", copy=False
134
+ )
135
+ return labels, int(labels.max())
136
+
137
+
138
+ class ThresholdSegment(ProcessingTool):
139
+ """Threshold an image and label connected foreground components."""
140
+
141
+ display_name = "Threshold Segment"
142
+ documentation = (
143
+ "Create a binary foreground mask from an intensity threshold and label "
144
+ "each connected object."
145
+ )
146
+ category = Category.SEGMENTATION
147
+ tags = ["segmentation", "threshold", "classical"]
148
+ environment = GENERAL_ENV
149
+
150
+ class Inputs(IOModel):
151
+ input_image: Annotated[
152
+ Path,
153
+ ImageSpec(
154
+ semantics={Semantic.INTENSITY, Semantic.PROBABILITY},
155
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
156
+ ),
157
+ GUIMeta(
158
+ display_name="Input image",
159
+ description="Intensity or probability image to threshold.",
160
+ connectable=Connectable.BY_DEFAULT,
161
+ ),
162
+ ]
163
+ threshold: Annotated[
164
+ float,
165
+ GUIMeta(
166
+ display_name="Threshold",
167
+ description="Pixels greater than or equal to this value become foreground.",
168
+ group="general",
169
+ ),
170
+ ] = 0.5
171
+ above: Annotated[
172
+ bool,
173
+ GUIMeta(
174
+ display_name="Use values above threshold",
175
+ description="When false, pixels less than or equal to the threshold become foreground.",
176
+ group="general",
177
+ ),
178
+ ] = True
179
+
180
+ class Outputs(IOModel):
181
+ labels: Annotated[
182
+ Path,
183
+ ImageSpec(
184
+ semantics={Semantic.LABEL},
185
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
186
+ ),
187
+ GUIMeta(
188
+ display_name="Label image",
189
+ description="Connected foreground components as integer labels.",
190
+ ),
191
+ ] = Template("{input_image.stem}_threshold_labels{ext}")
192
+ object_count: Annotated[
193
+ int,
194
+ GUIMeta(
195
+ display_name="Object count",
196
+ description="Number of connected foreground objects.",
197
+ ),
198
+ ]
199
+
200
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
201
+ import imageio.v3 as iio
202
+
203
+ image = iio.imread(str(arguments.input_image))
204
+ if arguments.above:
205
+ foreground = image >= arguments.threshold
206
+ else:
207
+ foreground = image <= arguments.threshold
208
+ labels = _label_connected(foreground)
209
+ object_count = int(labels.max())
210
+
211
+ labels_path = Path(arguments.labels)
212
+ _write_labels(labels_path, labels)
213
+ return self.Outputs(labels=labels_path, object_count=object_count)
214
+
215
+
216
+ class OtsuThresholdSegment(ProcessingTool):
217
+ """Threshold an image with scikit-image's global Otsu threshold."""
218
+
219
+ display_name = "Otsu Threshold Segment"
220
+ documentation = "Compute a global Otsu threshold and label foreground components."
221
+ category = Category.SEGMENTATION
222
+ tags = ["segmentation", "threshold", "otsu", "classical"]
223
+ environment = GENERAL_ENV
224
+
225
+ class Inputs(IOModel):
226
+ input_image: Annotated[
227
+ Path,
228
+ ImageSpec(
229
+ semantics={Semantic.INTENSITY, Semantic.PROBABILITY},
230
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
231
+ ),
232
+ GUIMeta(
233
+ display_name="Input image",
234
+ description="Intensity or probability image to threshold.",
235
+ connectable=Connectable.BY_DEFAULT,
236
+ ),
237
+ ]
238
+ above: Annotated[
239
+ bool,
240
+ GUIMeta(
241
+ display_name="Use values above threshold",
242
+ description="When false, pixels below or equal to Otsu become foreground.",
243
+ group="general",
244
+ ),
245
+ ] = True
246
+
247
+ class Outputs(IOModel):
248
+ labels: Annotated[
249
+ Path,
250
+ ImageSpec(
251
+ semantics={Semantic.LABEL},
252
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
253
+ ),
254
+ GUIMeta(
255
+ display_name="Label image",
256
+ description="Connected foreground components as integer labels.",
257
+ ),
258
+ ] = Template("{input_image.stem}_otsu_labels{ext}")
259
+ object_count: Annotated[int, GUIMeta(display_name="Object count")]
260
+ threshold: Annotated[float, GUIMeta(display_name="Otsu threshold")]
261
+
262
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
263
+ import imageio.v3 as iio
264
+ from skimage.filters import threshold_otsu
265
+
266
+ image = iio.imread(str(arguments.input_image))
267
+ threshold = float(threshold_otsu(image))
268
+ foreground = image > threshold if getattr(arguments, "above", True) else image <= threshold
269
+ labels = _label_skimage(foreground)
270
+ labels_path = Path(arguments.labels)
271
+ _write_labels(labels_path, labels)
272
+ return self.Outputs(
273
+ labels=labels_path,
274
+ object_count=int(labels.max()),
275
+ threshold=threshold,
276
+ )
277
+
278
+
279
+ class LocalThresholdSegment(ProcessingTool):
280
+ """Threshold an image with scikit-image's Sauvola local threshold."""
281
+
282
+ display_name = "Local Threshold Segment"
283
+ documentation = "Compute a Sauvola adaptive threshold and label foreground."
284
+ category = Category.SEGMENTATION
285
+ tags = ["segmentation", "threshold", "sauvola", "local", "classical"]
286
+ environment = GENERAL_ENV
287
+
288
+ class Inputs(IOModel):
289
+ input_image: Annotated[
290
+ Path,
291
+ ImageSpec(
292
+ semantics={Semantic.INTENSITY, Semantic.PROBABILITY},
293
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
294
+ ),
295
+ GUIMeta(
296
+ display_name="Input image",
297
+ description="Intensity or probability image to threshold.",
298
+ connectable=Connectable.BY_DEFAULT,
299
+ ),
300
+ ]
301
+ block_size: Annotated[
302
+ int,
303
+ GUIMeta(
304
+ display_name="Block size",
305
+ description="Odd local window size for Sauvola thresholding.",
306
+ min=3,
307
+ step=2,
308
+ group="general",
309
+ ),
310
+ ] = 15
311
+ k: Annotated[
312
+ float,
313
+ GUIMeta(
314
+ display_name="Sauvola k",
315
+ description="Sauvola sensitivity parameter.",
316
+ group="general",
317
+ ),
318
+ ] = 0.2
319
+ offset: Annotated[
320
+ float,
321
+ GUIMeta(
322
+ display_name="Threshold offset",
323
+ description="Value subtracted from the local threshold.",
324
+ group="general",
325
+ ),
326
+ ] = 0.0
327
+ above: Annotated[
328
+ bool,
329
+ GUIMeta(
330
+ display_name="Use values above threshold",
331
+ description="When false, pixels below or equal to threshold become foreground.",
332
+ group="general",
333
+ ),
334
+ ] = True
335
+
336
+ class Outputs(IOModel):
337
+ labels: Annotated[
338
+ Path,
339
+ ImageSpec(
340
+ semantics={Semantic.LABEL},
341
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
342
+ ),
343
+ GUIMeta(
344
+ display_name="Label image",
345
+ description="Connected foreground components as integer labels.",
346
+ ),
347
+ ] = Template("{input_image.stem}_local_threshold_labels{ext}")
348
+ object_count: Annotated[int, GUIMeta(display_name="Object count")]
349
+
350
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
351
+ import imageio.v3 as iio
352
+ from skimage.filters import threshold_sauvola
353
+
354
+ block_size = int(getattr(arguments, "block_size", 15))
355
+ if block_size < 3 or block_size % 2 == 0:
356
+ raise ValueError("block_size must be an odd integer greater than or equal to 3.")
357
+ image = iio.imread(str(arguments.input_image))
358
+ threshold = threshold_sauvola(
359
+ image,
360
+ window_size=block_size,
361
+ k=getattr(arguments, "k", 0.2),
362
+ )
363
+ threshold = threshold - float(getattr(arguments, "offset", 0.0))
364
+ foreground = image > threshold if getattr(arguments, "above", True) else image <= threshold
365
+ labels = _label_skimage(foreground)
366
+ labels_path = Path(arguments.labels)
367
+ _write_labels(labels_path, labels)
368
+ return self.Outputs(labels=labels_path, object_count=int(labels.max()))
369
+
370
+
371
+ class WatershedSegment(ProcessingTool):
372
+ """Split foreground regions using marker-controlled watershed semantics."""
373
+
374
+ display_name = "Watershed Segment"
375
+ documentation = (
376
+ "Segment thresholded foreground regions. When marker labels are supplied, "
377
+ "foreground pixels are assigned to the nearest marker by graph distance."
378
+ )
379
+ category = Category.SEGMENTATION
380
+ tags = ["segmentation", "watershed", "classical"]
381
+ environment = GENERAL_ENV
382
+
383
+ class Inputs(IOModel):
384
+ input_image: Annotated[
385
+ Path,
386
+ ImageSpec(
387
+ semantics={Semantic.INTENSITY, Semantic.PROBABILITY, Semantic.BINARY},
388
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
389
+ ),
390
+ GUIMeta(
391
+ display_name="Input image",
392
+ description="Image used to define the foreground region.",
393
+ connectable=Connectable.BY_DEFAULT,
394
+ ),
395
+ ]
396
+ markers_image: Annotated[
397
+ Path | str | None,
398
+ ImageSpec(
399
+ semantics={Semantic.LABEL},
400
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
401
+ ),
402
+ GUIMeta(
403
+ display_name="Markers image",
404
+ description="Optional marker label image used to split foreground regions.",
405
+ connectable=Connectable.NOT_BY_DEFAULT,
406
+ group="general",
407
+ ),
408
+ ] = ""
409
+ threshold: Annotated[
410
+ float,
411
+ GUIMeta(
412
+ display_name="Foreground threshold",
413
+ description="Pixels greater than or equal to this value are segmented.",
414
+ group="general",
415
+ ),
416
+ ] = 0.5
417
+
418
+ class Outputs(IOModel):
419
+ labels: Annotated[
420
+ Path,
421
+ ImageSpec(
422
+ semantics={Semantic.LABEL},
423
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
424
+ ),
425
+ GUIMeta(
426
+ display_name="Label image",
427
+ description="Watershed segmentation label image.",
428
+ ),
429
+ ] = Template("{input_image.stem}_watershed_labels{ext}")
430
+ object_count: Annotated[
431
+ int,
432
+ GUIMeta(
433
+ display_name="Object count",
434
+ description="Number of watershed objects.",
435
+ ),
436
+ ]
437
+
438
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
439
+ import imageio.v3 as iio
440
+ import numpy as np
441
+ from skimage import measure
442
+ from skimage.segmentation import watershed
443
+
444
+ image = iio.imread(str(arguments.input_image))
445
+ foreground = image >= arguments.threshold
446
+ markers_value = getattr(arguments, "markers_image", "")
447
+ if markers_value is None or str(markers_value) == "":
448
+ markers = np.asarray(measure.label(foreground)).astype(
449
+ "uint32", copy=False
450
+ )
451
+ else:
452
+ markers = iio.imread(str(markers_value))
453
+ if markers.shape != foreground.shape:
454
+ raise ValueError(
455
+ "markers_image must have the same shape as input_image "
456
+ f"({markers.shape} != {foreground.shape})"
457
+ )
458
+
459
+ labels = watershed(
460
+ -image.astype("float32", copy=False), markers, mask=foreground
461
+ )
462
+ labels = labels.astype("uint32", copy=False)
463
+ object_count = int(np.count_nonzero(np.unique(labels)))
464
+
465
+ labels_path = Path(arguments.labels)
466
+ _write_labels(labels_path, labels)
467
+ return self.Outputs(labels=labels_path, object_count=object_count)
468
+
469
+
470
+ class DistanceWatershedSegment(ProcessingTool):
471
+ """Split foreground using marker-free distance-transform watershed."""
472
+
473
+ display_name = "Distance Watershed Segment"
474
+ documentation = "Use distance-transform peaks as watershed markers for foreground."
475
+ category = Category.SEGMENTATION
476
+ tags = ["segmentation", "watershed", "distance", "classical"]
477
+ environment = GENERAL_ENV
478
+
479
+ class Inputs(IOModel):
480
+ input_image: Annotated[
481
+ Path,
482
+ ImageSpec(
483
+ semantics={Semantic.INTENSITY, Semantic.PROBABILITY, Semantic.BINARY},
484
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
485
+ ),
486
+ GUIMeta(
487
+ display_name="Input image",
488
+ description="Image thresholded to define watershed foreground.",
489
+ connectable=Connectable.BY_DEFAULT,
490
+ ),
491
+ ]
492
+ threshold: Annotated[
493
+ float,
494
+ GUIMeta(
495
+ display_name="Foreground threshold",
496
+ description="Pixels greater than or equal to this value are segmented.",
497
+ group="general",
498
+ ),
499
+ ] = 0.5
500
+ min_distance: Annotated[
501
+ int,
502
+ GUIMeta(
503
+ display_name="Minimum marker distance",
504
+ description="Minimum distance between local distance peaks.",
505
+ min=1,
506
+ step=1,
507
+ group="general",
508
+ ),
509
+ ] = 5
510
+
511
+ class Outputs(IOModel):
512
+ labels: Annotated[
513
+ Path,
514
+ ImageSpec(
515
+ semantics={Semantic.LABEL},
516
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
517
+ ),
518
+ GUIMeta(
519
+ display_name="Label image",
520
+ description="Distance watershed label image.",
521
+ ),
522
+ ] = Template("{input_image.stem}_distance_watershed_labels{ext}")
523
+ object_count: Annotated[int, GUIMeta(display_name="Object count")]
524
+
525
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
526
+ import imageio.v3 as iio
527
+
528
+ image = iio.imread(str(arguments.input_image))
529
+ labels, object_count = _distance_watershed(
530
+ image >= getattr(arguments, "threshold", 0.5),
531
+ min_distance=getattr(arguments, "min_distance", 5),
532
+ )
533
+ labels_path = Path(arguments.labels)
534
+ _write_labels(labels_path, labels)
535
+ return self.Outputs(labels=labels_path, object_count=object_count)
536
+
537
+
538
+ class SplitTouchingObjects(ProcessingTool):
539
+ """Split clumped labels with distance-transform watershed semantics."""
540
+
541
+ display_name = "Split Touching Objects"
542
+ documentation = "Split touching foreground inside each label image mask."
543
+ category = Category.SEGMENTATION
544
+ tags = ["segmentation", "labels", "watershed", "postprocessing", "classical"]
545
+ environment = GENERAL_ENV
546
+
547
+ class Inputs(IOModel):
548
+ labels: Annotated[
549
+ Path,
550
+ ImageSpec(
551
+ semantics={Semantic.LABEL},
552
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
553
+ ),
554
+ GUIMeta(
555
+ display_name="Label image",
556
+ description="Input clumped label image.",
557
+ connectable=Connectable.BY_DEFAULT,
558
+ ),
559
+ ]
560
+ min_distance: Annotated[
561
+ int,
562
+ GUIMeta(
563
+ display_name="Minimum marker distance",
564
+ description="Minimum distance between local distance peaks.",
565
+ min=1,
566
+ step=1,
567
+ group="general",
568
+ ),
569
+ ] = 5
570
+
571
+ class Outputs(IOModel):
572
+ output_labels: Annotated[
573
+ Path,
574
+ ImageSpec(
575
+ semantics={Semantic.LABEL},
576
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
577
+ ),
578
+ GUIMeta(
579
+ display_name="Output labels",
580
+ description="Split label image with sequential label IDs.",
581
+ ),
582
+ ] = Template("{labels.stem}_split{ext}")
583
+ object_count: Annotated[int, GUIMeta(display_name="Object count")]
584
+
585
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
586
+ import imageio.v3 as iio
587
+ import numpy as np
588
+
589
+ source = iio.imread(str(arguments.labels))
590
+ output = np.zeros(source.shape, dtype=np.uint32)
591
+ next_label = 1
592
+ for label in np.unique(source):
593
+ label_int = int(label)
594
+ if label_int == 0:
595
+ continue
596
+ split, _ = _distance_watershed(
597
+ source == label_int,
598
+ min_distance=getattr(arguments, "min_distance", 5),
599
+ )
600
+ for split_label in np.unique(split):
601
+ if int(split_label) == 0:
602
+ continue
603
+ output[split == split_label] = next_label
604
+ next_label += 1
605
+
606
+ output_path = Path(arguments.output_labels)
607
+ _write_labels(output_path, output)
608
+ return self.Outputs(output_labels=output_path, object_count=next_label - 1)
609
+
610
+
611
+ class FilterLabels(ProcessingTool):
612
+ """Filter labels by area, border contact, intensity, and shape constraints."""
613
+
614
+ display_name = "Filter Labels"
615
+ documentation = "Remove labels by area, border contact, intensity, or shape."
616
+ category = Category.SEGMENTATION
617
+ tags = ["segmentation", "labels", "filter", "postprocessing", "classical"]
618
+ environment = GENERAL_ENV
619
+
620
+ class Inputs(IOModel):
621
+ labels: Annotated[
622
+ Path,
623
+ ImageSpec(
624
+ semantics={Semantic.LABEL},
625
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
626
+ ),
627
+ GUIMeta(
628
+ display_name="Label image",
629
+ description="Input label image to filter.",
630
+ connectable=Connectable.BY_DEFAULT,
631
+ ),
632
+ ]
633
+ min_area: Annotated[int, GUIMeta(display_name="Minimum area", min=0)] = 0
634
+ max_area: Annotated[int, GUIMeta(display_name="Maximum area", min=0)] = 0
635
+ remove_border_touching: Annotated[
636
+ bool,
637
+ GUIMeta(display_name="Remove border-touching labels"),
638
+ ] = False
639
+ intensity_image: Annotated[
640
+ Path | str | None,
641
+ ImageSpec(semantics={Semantic.INTENSITY}, layouts={Layout.PLANAR}),
642
+ GUIMeta(
643
+ display_name="Intensity image",
644
+ description="Optional image used for mean-intensity filtering.",
645
+ connectable=Connectable.NOT_BY_DEFAULT,
646
+ ),
647
+ ] = ""
648
+ min_mean_intensity: Annotated[
649
+ float,
650
+ GUIMeta(display_name="Minimum mean intensity"),
651
+ ] = 0.0
652
+ min_solidity: Annotated[float, GUIMeta(display_name="Minimum solidity")] = 0.0
653
+ max_eccentricity: Annotated[
654
+ float,
655
+ GUIMeta(display_name="Maximum eccentricity"),
656
+ ] = 1.0
657
+
658
+ class Outputs(IOModel):
659
+ output_labels: Annotated[
660
+ Path,
661
+ ImageSpec(
662
+ semantics={Semantic.LABEL},
663
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
664
+ ),
665
+ GUIMeta(
666
+ display_name="Output labels",
667
+ description="Filtered label image with sequential label IDs.",
668
+ ),
669
+ ] = Template("{labels.stem}_filtered{ext}")
670
+ object_count: Annotated[int, GUIMeta(display_name="Object count")]
671
+
672
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
673
+ import imageio.v3 as iio
674
+ import numpy as np
675
+ from skimage.measure import regionprops
676
+
677
+ source = iio.imread(str(arguments.labels))
678
+ intensity = None
679
+ intensity_path = getattr(arguments, "intensity_image", "")
680
+ if intensity_path is not None and str(intensity_path) != "":
681
+ intensity = iio.imread(str(intensity_path))
682
+ if intensity.shape != source.shape:
683
+ raise ValueError("intensity_image must have the same shape as labels.")
684
+
685
+ output = np.zeros(source.shape, dtype=np.uint32)
686
+ next_label = 1
687
+ for region in regionprops(source, intensity_image=intensity):
688
+ if region.area < getattr(arguments, "min_area", 0):
689
+ continue
690
+ max_area = getattr(arguments, "max_area", 0)
691
+ if max_area and region.area > max_area:
692
+ continue
693
+ if getattr(arguments, "remove_border_touching", False) and _touches_border(
694
+ region.bbox,
695
+ source.shape,
696
+ ):
697
+ continue
698
+ if (
699
+ intensity is not None
700
+ and region.mean_intensity < getattr(arguments, "min_mean_intensity", 0.0)
701
+ ):
702
+ continue
703
+ if source.ndim == 2 and getattr(region, "solidity", 1.0) < getattr(
704
+ arguments,
705
+ "min_solidity",
706
+ 0.0,
707
+ ):
708
+ continue
709
+ if source.ndim == 2 and getattr(region, "eccentricity", 0.0) > getattr(
710
+ arguments,
711
+ "max_eccentricity",
712
+ 1.0,
713
+ ):
714
+ continue
715
+ output[source == region.label] = next_label
716
+ next_label += 1
717
+
718
+ output_path = Path(arguments.output_labels)
719
+ _write_labels(output_path, output)
720
+ return self.Outputs(output_labels=output_path, object_count=next_label - 1)
721
+
722
+
723
+ class PostprocessLabels(ProcessingTool):
724
+ """Filter and relabel a label image."""
725
+
726
+ display_name = "Postprocess Labels"
727
+ documentation = (
728
+ "Remove labels below a minimum size and relabel remaining labels sequentially."
729
+ )
730
+ category = Category.SEGMENTATION
731
+ tags = ["segmentation", "labels", "postprocessing", "classical"]
732
+ environment = GENERAL_ENV
733
+
734
+ class Inputs(IOModel):
735
+ labels: Annotated[
736
+ Path,
737
+ ImageSpec(
738
+ semantics={Semantic.LABEL},
739
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
740
+ ),
741
+ GUIMeta(
742
+ display_name="Label image",
743
+ description="Input label image to postprocess.",
744
+ connectable=Connectable.BY_DEFAULT,
745
+ ),
746
+ ]
747
+ min_size: Annotated[
748
+ int,
749
+ GUIMeta(
750
+ display_name="Minimum label size",
751
+ description="Labels with fewer pixels/voxels than this value are removed.",
752
+ min=0,
753
+ step=1,
754
+ group="general",
755
+ ),
756
+ ] = 0
757
+
758
+ class Outputs(IOModel):
759
+ output_labels: Annotated[
760
+ Path,
761
+ ImageSpec(
762
+ semantics={Semantic.LABEL},
763
+ layouts={Layout.PLANAR, Layout.VOLUMETRIC},
764
+ ),
765
+ GUIMeta(
766
+ display_name="Output labels",
767
+ description="Filtered label image with sequential label IDs.",
768
+ ),
769
+ ] = Template("{labels.stem}_postprocessed{ext}")
770
+ object_count: Annotated[
771
+ int,
772
+ GUIMeta(
773
+ display_name="Object count",
774
+ description="Number of labels retained.",
775
+ ),
776
+ ]
777
+
778
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
779
+ import imageio.v3 as iio
780
+
781
+ labels = iio.imread(str(arguments.labels))
782
+ relabeled, object_count = _relabel_sequential(labels, arguments.min_size)
783
+
784
+ output_path = Path(arguments.output_labels)
785
+ _write_labels(output_path, relabeled)
786
+ return self.Outputs(output_labels=output_path, object_count=object_count)
787
+
788
+
789
+ def _touches_border(bbox: tuple[int, ...], shape: tuple[int, ...]) -> bool:
790
+ ndim = len(shape)
791
+ starts = bbox[:ndim]
792
+ stops = bbox[ndim:]
793
+ return any(start == 0 for start in starts) or any(
794
+ stop == size for stop, size in zip(stops, shape, strict=True)
795
+ )