-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy path_widgets.py
More file actions
4600 lines (3982 loc) · 198 KB
/
Copy path_widgets.py
File metadata and controls
4600 lines (3982 loc) · 198 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Implements the widgets used in the annotation plugins."""
import gc
import json
import multiprocessing as mp
import os
import pickle
from pathlib import Path
from typing import Optional
import elf.parallel
import h5py
import napari
import numpy as np
import z5py
from bioimage_cpp.utils import segmentation_overlap
from magicgui import magic_factory
from magicgui.widgets import ComboBox, Container, create_widget
# We have disabled the thread workers for now because they result in a
# massive slowdown in napari >= 0.5.
# See also https://forum.image.sc/t/napari-thread-worker-leads-to-massive-slowdown/103786
# from napari.qt.threading import thread_worker
from napari.utils import progress
from napari.utils.notifications import show_info
from qtpy import QtWidgets
from qtpy.QtCore import QObject, Signal, Qt
from superqt import QCollapsible, QLabeledRangeSlider
from .. import util
from ..v1 import instance_segmentation
from ..v1.multi_dimensional_segmentation import (
PROJECTION_MODES,
export_tracking_result_to_ctc,
export_tracking_result_to_geff,
export_tracking_result_to_trackmate_xml,
get_napari_track_data,
merge_instance_segmentation_3d,
segment_mask_in_volume,
track_across_frames,
)
from . import util as vutil
from ._state import AnnotatorState
from ._tooltips import get_tooltip
#
# Convenience functionality for creating QT UI and manipulating the napari viewer.
#
def _select_layer(viewer, layer_name):
viewer.layers.selection.select_only(viewer.layers[layer_name])
# Create a collapsible around the widget
def _make_collapsible(widget, title, tooltip=None):
parent_widget = QtWidgets.QWidget()
parent_widget.setLayout(QtWidgets.QVBoxLayout())
collapsible = QCollapsible(title, parent_widget)
if tooltip:
collapsible.setToolTip(tooltip)
# Also set it on the header toggle button, since that is what the user hovers (Qt does not
# fall back to the parent's tooltip for child widgets).
toggle_btn = getattr(collapsible, "_toggle_btn", None)
if toggle_btn is not None:
toggle_btn.setToolTip(tooltip)
collapsible.addWidget(widget)
parent_widget.layout().addWidget(collapsible)
return parent_widget
# Base class for a widget with convenience functionality for adding parameters.
class _WidgetBase(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setLayout(QtWidgets.QVBoxLayout())
def _add_boolean_param(self, name, value, title=None, tooltip=None):
checkbox = QtWidgets.QCheckBox(name if title is None else title)
checkbox.setChecked(value)
checkbox.stateChanged.connect(lambda val: setattr(self, name, val))
if tooltip:
checkbox.setToolTip(tooltip)
return checkbox
def _update_batched_visibility(self):
"""Hide the 'Batched' checkbox while embeddings are tiled (batched prompting is unsupported
with tiling). No-op for widgets without a batched checkbox."""
checkbox = getattr(self, "batched_checkbox", None)
if checkbox is None:
return
is_tiled = _embeddings_are_tiled(AnnotatorState())
if is_tiled and getattr(self, "batched", False):
checkbox.setChecked(False) # reset to single-object (also updates 'self.batched')
checkbox.setVisible(not is_tiled)
def _add_string_param(
self,
name,
value,
title=None,
placeholder=None,
layout=None,
tooltip=None,
):
if layout is None:
layout = QtWidgets.QHBoxLayout()
label = QtWidgets.QLabel(title or name)
if tooltip:
label.setToolTip(tooltip)
layout.addWidget(label)
param = QtWidgets.QLineEdit()
param.setText(value)
if placeholder is not None:
param.setPlaceholderText(placeholder)
param.textChanged.connect(lambda val: setattr(self, name, val))
if tooltip:
param.setToolTip(tooltip)
layout.addWidget(param)
return param, layout
def _add_float_param(
self,
name,
value,
title=None,
min_val=0.0,
max_val=1.0,
decimals=2,
step=0.01,
layout=None,
tooltip=None,
):
if layout is None:
layout = QtWidgets.QHBoxLayout()
label = QtWidgets.QLabel(title or name)
if tooltip:
label.setToolTip(tooltip)
layout.addWidget(label)
param = QtWidgets.QDoubleSpinBox()
param.setRange(min_val, max_val)
param.setDecimals(decimals)
param.setValue(value)
param.setSingleStep(step)
param.valueChanged.connect(lambda val: setattr(self, name, val))
if tooltip:
param.setToolTip(tooltip)
layout.addWidget(param)
return param, layout
def _add_int_param(
self,
name,
value,
min_val,
max_val,
title=None,
step=1,
layout=None,
tooltip=None,
):
if layout is None:
layout = QtWidgets.QHBoxLayout()
label = QtWidgets.QLabel(title or name)
if tooltip:
label.setToolTip(tooltip)
layout.addWidget(label)
param = QtWidgets.QSpinBox()
param.setRange(min_val, max_val)
param.setValue(value)
param.setSingleStep(step)
param.valueChanged.connect(lambda val: setattr(self, name, val))
if tooltip:
param.setToolTip(tooltip)
layout.addWidget(param)
return param, layout
def _make_int_field(self, name, value, min_val, max_val, step=1, title=None, tooltip=None):
# A single labeled int spinbox wrapped in its own widget, so it can be placed inside a row
# next to other fields and shown / hidden independently (e.g. the z fields, which only apply
# to 3d data). Returns the spinbox and the wrapping widget.
field = QtWidgets.QWidget()
field_layout = QtWidgets.QVBoxLayout()
field_layout.setContentsMargins(0, 0, 0, 0)
param, _ = self._add_int_param(
name, value, min_val=min_val, max_val=max_val, step=step,
layout=field_layout, title=title, tooltip=tooltip,
)
field.setLayout(field_layout)
return param, field
def _add_choice_param(
self,
name,
value,
options,
title=None,
layout=None,
update=None,
tooltip=None,
):
if layout is None:
layout = QtWidgets.QHBoxLayout()
label = QtWidgets.QLabel(title or name)
if tooltip:
label.setToolTip(tooltip)
layout.addWidget(label)
# Create the dropdown menu via QComboBox, set the available values.
dropdown = QtWidgets.QComboBox()
dropdown.addItems(options)
if update is None:
dropdown.currentIndexChanged.connect(
lambda index: setattr(self, name, options[index])
)
else:
dropdown.currentIndexChanged.connect(update)
# Set the correct value for the value.
dropdown.setCurrentIndex(dropdown.findText(value))
if tooltip:
dropdown.setToolTip(tooltip)
layout.addWidget(dropdown)
return dropdown, layout
def _add_shape_param(
self, names, values, min_val, max_val, step=1, title=None, tooltip=None
):
layout = QtWidgets.QHBoxLayout()
x_layout = QtWidgets.QVBoxLayout()
x_param, _ = self._add_int_param(
names[0],
values[0],
min_val=min_val,
max_val=max_val,
layout=x_layout,
step=step,
title=title[0] if title is not None else title,
tooltip=tooltip,
)
layout.addLayout(x_layout)
y_layout = QtWidgets.QVBoxLayout()
y_param, _ = self._add_int_param(
names[1],
values[1],
min_val=min_val,
max_val=max_val,
layout=y_layout,
step=step,
title=title[1] if title is not None else title,
tooltip=tooltip,
)
layout.addLayout(y_layout)
return x_param, y_param, layout
def _add_path_param(
self,
name,
value,
select_type,
title=None,
placeholder=None,
tooltip=None,
):
assert select_type in ("directory", "file", "both")
layout = QtWidgets.QHBoxLayout()
label = QtWidgets.QLabel(title or name)
if tooltip:
label.setToolTip(tooltip)
layout.addWidget(label)
path_textbox = QtWidgets.QLineEdit()
path_textbox.setText("" if value is None else str(value))
if placeholder is not None:
path_textbox.setPlaceholderText(placeholder)
# An empty path means that no optional path was selected. Keep this as ``None`` in the
# widget state instead of an empty (or whitespace-only) string: downstream model loading
# distinguishes ``None`` (use the registered model) from a custom checkpoint path.
path_textbox.textChanged.connect(
lambda val: setattr(self, name, val if val.strip() else None)
)
if tooltip:
path_textbox.setToolTip(tooltip)
layout.addWidget(path_textbox)
def add_path_button(select_type, tooltip=None):
# Adjust button text.
button_text = f"Select {select_type.capitalize()}"
path_button = QtWidgets.QPushButton(button_text)
# Call appropriate function based on select_type.
path_button.clicked.connect(
lambda: getattr(self, f"_get_{select_type}_path")(
name, path_textbox
)
)
if tooltip:
path_button.setToolTip(tooltip)
layout.addWidget(path_button)
if select_type == "both":
add_path_button("file")
add_path_button("directory")
else:
add_path_button(select_type)
return path_textbox, layout
def _get_directory_path(self, name, textbox, tooltip=None):
directory = QtWidgets.QFileDialog.getExistingDirectory(
self, "Select Directory", "", QtWidgets.QFileDialog.ShowDirsOnly
)
if tooltip:
directory.setToolTip(tooltip)
if directory and Path(directory).is_dir():
textbox.setText(str(directory))
else:
# Handle the case where the selected path is not a directory
print("Invalid directory selected. Please try again.")
def _get_file_path(self, name, textbox, tooltip=None):
file_path, _ = QtWidgets.QFileDialog.getOpenFileName(
self, "Select File", "", "All Files (*)"
)
if tooltip:
file_path.setToolTip(tooltip)
if file_path and Path(file_path).is_file():
textbox.setText(str(file_path))
else:
# Handle the case where the selected path is not a file
print("Invalid file selected. Please try again.")
def _align_widths(self, widgets):
# Give a set of widgets a uniform (max) fixed width so rows line up symmetrically.
widgets = [w for w in widgets if w is not None]
if not widgets:
return
width = max(w.sizeHint().width() for w in widgets)
for w in widgets:
w.setFixedWidth(width)
def _get_model_size_options(self):
# The available model sizes depend on the selected family: the base SAM2 family supports all
# sizes, while finetuned families may only be available for specific sizes (e.g. 'Microscopy'
# is an 'hvit_t' model). We store the UI labels mapped to the corresponding model names.
sizes = self.model_family_config[self.model_family]["sizes"]
self.model_size_options = [self._model_size_map[k] for k in sizes]
self.model_size_mapping = {self._model_size_map[k]: f"hvit_{k}" for k in sizes}
# We ensure an assorted order of model sizes ('tiny' to 'large').
self.model_size_options.sort(
key=lambda x: ["tiny", "small", "base", "large"].index(x)
)
def _update_model_type(self):
# Sync the selected family; both the available sizes and the model-type suffix depend on it.
self.model_family = self.model_family_dropdown.currentText() or self.model_family
# Get currently selected model size (before clearing dropdown)
current_selection = self.model_size_dropdown.currentText()
self._get_model_size_options() # Update model size options dynamically
# NOTE: We need to prevent recursive updates for this step temporarily.
self.model_size_dropdown.blockSignals(True)
# Let's clear and recreate the dropdown.
self.model_size_dropdown.clear()
self.model_size_dropdown.addItems(self.model_size_options)
# We restore the previous selection, if still valid.
if current_selection in self.model_size_options:
self.model_size = current_selection
else:
if (
self.model_size_options
): # Default to the first available model size
self.model_size = self.model_size_options[0]
# Let's map the selection to the correct model type (eg. "tiny" -> "hvit_t").
size_key = next(
(
k
for k, v in self._model_size_map.items()
if v == self.model_size
),
"t",
)
# Append the family suffix (e.g. 'tiny' + 'Microscopy' -> 'hvit_t_cells'; base -> 'hvit_t').
suffix = self.model_family_config[self.model_family]["suffix"]
self.model_type = f"hvit_{size_key}{suffix}"
self.model_size_dropdown.setCurrentText(
self.model_size
) # Apply the selected text to the dropdown
# We force a refresh for UI here.
self.model_size_dropdown.update()
# NOTE: And finally, we should re-enable signals again.
self.model_size_dropdown.blockSignals(False)
def _create_model_section(
self,
default_model: Optional[str] = None,
create_layout: bool = True,
):
# The widget encodes its default as the synthetic 'vit_<size><suffix>' selector string. For
# SAM2 model ids ('hvit_...') this is just the id without the leading 'h', so we derive it
# from the single-source 'DEFAULT_MODEL' (e.g. 'hvit_t_cells' -> 'vit_t_cells' -> Microscopy/tiny).
if default_model is None:
from ..v2.util import DEFAULT_MODEL
default_model = DEFAULT_MODEL[1:]
# Create a list of supported dropdown values and correspond them to suffixes (used to parse
# the synthetic default-model string). Additional SAM2 families can be added here in future.
self.supported_dropdown_maps = {
"Natural Images": "_sam2",
"Microscopy": "_cells",
}
# Per-family backend config: the model-type suffix appended after 'hvit_{size}' and the
# available model sizes. The base SAM2 family supports all sizes; finetuned families (e.g.
# 'Microscopy', the joint SAM2 + UniSAM2 'hvit_t_cells' model) may exist only for some sizes.
self.model_family_config = {
"Natural Images": {"suffix": "", "sizes": ["t", "s", "b", "l"]},
"Microscopy": {"suffix": "_cells", "sizes": ["t"]},
}
# NOTE: The available SAM2 model sizes are 'tiny', 'small', 'base' and 'large'.
self._model_size_map = {
"t": "tiny",
"s": "small",
"b": "base",
"l": "large",
}
self._default_model_choice = default_model
# Let's set the literally default model choice depending on 'micro-sam'.
self.model_family = {
v: k for k, v in self.supported_dropdown_maps.items()
}[self._default_model_choice[5:]]
kwargs = {}
if create_layout:
layout = QtWidgets.QVBoxLayout()
kwargs["layout"] = layout
# NOTE: We stick to the base variant for each model family.
# i.e. 'Natural Images (SAM)', 'Light Microscopy', 'Electron Microscopy', 'Medical_Imaging', 'Histopathology'.
self.model_family_dropdown, layout = self._add_choice_param(
"model_family",
self.model_family,
list(self.supported_dropdown_maps.keys()),
title="Model:",
tooltip=get_tooltip("embedding", "model_family"),
**kwargs,
)
self.model_family_dropdown.currentTextChanged.connect(
self._update_model_type
)
return layout
def _create_model_size_section(self):
# Create UI for the model size.
# This combines with the chosen 'self.model_family' and depends on 'self._default_model_choice'.
self.model_size = self._model_size_map[self._default_model_choice[4]]
# Now, we get the available sizes per model family.
self._get_model_size_options()
self.model_size_dropdown, layout = self._add_choice_param(
"model_size",
self.model_size,
self.model_size_options,
title="model size:",
tooltip=get_tooltip("embedding", "model_size"),
)
self.model_size_dropdown.currentTextChanged.connect(
self._update_model_type
)
return layout
def _validate_model_type_and_custom_weights(self):
# Map the selected family + size to the SAM2 `model_type`, appending the family suffix
# (e.g. 'tiny' + 'Microscopy' -> 'hvit_t_cells'; 'tiny' + base family -> 'hvit_t').
suffix = self.model_family_config.get(self.model_family, {}).get("suffix", "")
self.model_type = f"hvit_{self.model_size[0]}{suffix}"
# For 'custom_weights', we remove the displayed text on top of the drop-down menu.
if self.custom_weights:
# NOTE: We prevent recursive updates for this step temporarily.
self.model_family_dropdown.blockSignals(True)
self.model_family_dropdown.setCurrentIndex(
-1
) # This removes the displayed text.
self.model_family_dropdown.update()
# NOTE: And re-enable signals again.
self.model_family_dropdown.blockSignals(False)
def _validate_model_support(self):
if getattr(self, "sam2_only", False) and not self.model_type.startswith("hvit_"):
return _generate_message(
"error",
"The tracking annotator only supports micro-sam2/SAM2 models. "
f"Got unsupported model '{self.model_type}'.",
)
return False
def _validate_vfm_requirements(self):
# For gated VFM models (DINOv3 via 'transformers', UNI / UNI2-h via 'timm') check that the backend
# package is importable and HuggingFace access is set up, surfacing a clear message if not. DINOv2
# ('torch_hub') is ungated and auto-downloads, so it is not checked. A no-op for SAM models.
import importlib
from ..models.vfm import is_vfm_model, VFM_MODELS
if not is_vfm_model(self.model_type):
return False
backend = VFM_MODELS[self.model_type]["backend"]
if backend == "torch_hub": # DINOv2: ungated, weights auto-download.
return False
package = "transformers" if backend == "hf" else "timm"
try:
importlib.import_module(package)
except ImportError:
return _generate_message(
"error",
f"The model '{self.model_type}' requires the '{package}' package, which is not installed. "
f"Install it (e.g. 'pip install {package}') and try again."
)
# These weights are gated on HuggingFace; warn (but allow continuing, e.g. if already cached).
try:
from huggingface_hub import get_token
has_token = get_token() is not None
except Exception:
has_token = False
if not has_token:
return _generate_message(
"info",
f"'{self.model_type}' is a gated model on Hugging Face. Request access on its Hugging Face "
"page and authenticate via 'huggingface-cli login' or the 'HF_TOKEN' environment variable. "
"If the weights are already downloaded you can continue; otherwise the download will fail."
)
return False
# Custom signals for managing progress updates.
class PBarSignals(QObject):
pbar_total = Signal(int)
pbar_update = Signal(int)
pbar_description = Signal(str)
pbar_stop = Signal()
pbar_reset = Signal()
class InfoDialog(QtWidgets.QDialog):
def __init__(self, title, message, buttons=("OK", "Cancel")):
super().__init__()
self.setWindowTitle(title)
# Label of the button the user clicked (None if the dialog was closed without a button).
self.clicked_label = None
# The first button accepts the dialog; the rest reject it.
self._accept_label = buttons[0]
layout = QtWidgets.QVBoxLayout()
layout.addWidget(QtWidgets.QLabel(message))
# Buttons side-by-side; the first is the default so Enter triggers it.
button_box = QtWidgets.QHBoxLayout()
for i, label in enumerate(buttons):
button = QtWidgets.QPushButton(label)
button.clicked.connect(lambda checked=False, lbl=label: self.button_clicked(lbl))
if i == 0:
button.setDefault(True)
button.setFocus()
button_box.addWidget(button)
layout.addLayout(button_box)
self.setLayout(layout)
def button_clicked(self, label):
self.clicked_label = label
if label == self._accept_label:
self.accept()
else:
self.reject()
# Set up the progress bar. We handle this via custom signals that are passed as callbacks to the
# function that does the actual work. We need callbacks for initializing the progress bar,
# updating it and for stopping the progress bar.
def _create_pbar_for_threadworker():
pbar = progress()
pbar_signals = PBarSignals()
pbar_signals.pbar_total.connect(
lambda total: setattr(pbar, "total", total)
)
pbar_signals.pbar_update.connect(lambda update: pbar.update(update))
pbar_signals.pbar_description.connect(
lambda description: pbar.set_description(description)
)
pbar_signals.pbar_stop.connect(lambda: pbar.close())
pbar_signals.pbar_reset.connect(lambda: pbar.reset())
return pbar, pbar_signals
def _reset_tracking_state(viewer):
"""Reset the tracking state.
This helper function is needed by the widgets clear_track and by commit_track.
"""
state = AnnotatorState()
# Reset the lineage and track id.
state.current_track_id = 1
state.lineage = {1: []}
# Reset the layer properties.
viewer.layers["point_prompts"].property_choices["track_id"] = ["1"]
viewer.layers["prompts"].property_choices["track_id"] = ["1"]
# Reset the choices in the track_id menu (index 2: prompt, track_state, track_id).
state.annotator._tracking_widget[2].value = "1"
state.annotator._tracking_widget[2].choices = ["1"]
#
# Widgets implemented with magicgui.
#
@magic_factory(call_button="Clear Annotations [Shift + C]")
def clear(viewer: "napari.viewer.Viewer") -> None:
"""Widget for clearing the current annotations.
Args:
viewer: The napari viewer.
"""
vutil.clear_annotations(viewer)
# Perform garbage collection.
gc.collect()
@magic_factory(call_button="Clear Annotations [Shift + C]")
def clear_volume(
viewer: "napari.viewer.Viewer", all_slices: bool = True
) -> None:
"""Widget for clearing the current annotations in 3D.
Args:
viewer: The napari viewer.
all_slices: Choose whether to clear the annotations for all or only the current slice.
"""
state = AnnotatorState()
if all_slices:
vutil.clear_annotations(viewer)
else:
i = int(viewer.dims.point[0])
vutil.clear_annotations_slice(viewer, i=i)
# If it's a SAM2 promptable segmentation workflow,
# we should reset the prompts after clear annotations has been clicked.
if state.interactive_segmenter is not None:
state.interactive_segmenter.reset_predictor()
# Perform garbage collection.
gc.collect()
@magic_factory(call_button="Clear Annotations [Shift + C]")
def clear_track(
viewer: "napari.viewer.Viewer", all_frames: bool = True
) -> None:
"""Widget for clearing all tracking annotations and state.
Args:
viewer: The napari viewer.
all_frames: Choose whether to clear the annotations for all or only the current frame.
"""
if all_frames:
_reset_tracking_state(viewer)
vutil.clear_annotations(viewer)
else:
i = int(viewer.dims.point[0])
vutil.clear_annotations_slice(viewer, i=i)
# Perform garbage collection.
gc.collect()
def _mask_matched_objects(seg, prev_seg, preservation_threshold):
prev_ids = np.unique(prev_seg)
ovlp = segmentation_overlap(prev_seg, seg)
mask_ids, prev_mask_ids = [], []
for prev_id in prev_ids:
ovlp_table = ovlp.overlaps_for_label_a(prev_id)
seg_ids, overlaps = ovlp_table["label"], ovlp_table["count"]
if seg_ids[0] != 0 and overlaps[0] >= preservation_threshold:
mask_ids.append(seg_ids[0])
prev_mask_ids.append(prev_id)
preserve_mask = np.logical_or(
np.isin(seg, mask_ids), np.isin(prev_seg, prev_mask_ids)
)
return preserve_mask
def _commit_impl(viewer, layer, preserve_mode, preservation_threshold):
state = AnnotatorState()
# Check whether all layers exist as expected or create new ones automatically.
state.annotator._require_layers(layer_choices=[layer, "committed_objects"])
# Check if we have a z_range. If yes, use it to set a bounding box.
if state.z_range is None:
bb = np.s_[:]
else:
z_min, z_max = state.z_range
bb = np.s_[z_min : (z_max + 1)] # noqa
# Cast the dtype of the segmentation we work with correctly.
# Otherwise we run into type conversion errors later.
dtype = viewer.layers["committed_objects"].data.dtype
seg = viewer.layers[layer].data[bb].astype(dtype)
shape = seg.shape
# We parallelize these operations because they take quite long for large volumes.
# Compute the max id in the commited objects.
# id_offset = int(viewer.layers["committed_objects"].data.max())
full_shape = viewer.layers["committed_objects"].data.shape
id_offset = int(
elf.parallel.max(
viewer.layers["committed_objects"].data,
block_shape=util.get_block_shape(full_shape),
)
)
# Compute the mask for the current object.
# mask = seg != 0
mask = np.zeros(seg.shape, dtype="bool")
mask = elf.parallel.apply_operation(
seg, 0, np.not_equal, out=mask, block_shape=util.get_block_shape(shape)
)
if preserve_mode != "none":
prev_seg = viewer.layers["committed_objects"].data[bb]
# The mode 'pixels' corresponds to a naive implementation where only committed pixels are preserved.
preserve_mask = prev_seg != 0
# If the preserve mask is empty we don't need to do anything else here, because we don't have prev objects.
if preserve_mask.sum() != 0:
# In the mode 'objects' we preserve committed objects instead, by comparing the overlaps
# of already committed and newly committed objects.
if preserve_mode == "objects":
preserve_mask = _mask_matched_objects(
seg, prev_seg, preservation_threshold
)
mask[preserve_mask] = 0
# Write the current object to committed objects.
seg[mask] += id_offset
viewer.layers["committed_objects"].data[bb][mask] = seg[mask]
viewer.layers["committed_objects"].refresh()
# If it's a SAM2 promptable segmentation workflow, we should reset the prompts after commit has been clicked.
if state.interactive_segmenter is not None:
state.interactive_segmenter.reset_predictor()
return id_offset, seg, mask, bb
def _get_auto_segmentation_options(state, object_ids):
widget = state.widgets["autosegment"]
segmentation_options = {
"object_ids": [int(object_id) for object_id in object_ids]
}
if widget.with_decoder:
segmentation_options["boundary_distance_thresh"] = (
widget.boundary_distance_thresh
)
segmentation_options["center_distance_thresh"] = (
widget.center_distance_thresh
)
else:
segmentation_options["pred_iou_thresh"] = widget.pred_iou_thresh
segmentation_options["stability_score_thresh"] = (
widget.stability_score_thresh
)
segmentation_options["box_nms_thresh"] = widget.box_nms_thresh
segmentation_options["min_object_size"] = widget.min_object_size
if widget.volumetric:
segmentation_options["apply_to_volume"] = widget.apply_to_volume
segmentation_options["gap_closing"] = widget.gap_closing
segmentation_options["min_extent"] = widget.min_extent
return segmentation_options
def _get_promptable_segmentation_options(state, object_ids):
segmentation_options = {
"object_ids": [int(object_id) for object_id in object_ids]
}
is_tracking = False
if "segment_nd" in state.widgets:
widget = state.widgets["segment_nd"]
segmentation_options["projection"] = widget.projection
segmentation_options["iou_threshold"] = widget.iou_threshold
segmentation_options["box_extension"] = widget.box_extension
if widget.tracking:
segmentation_options["motion_smoothing"] = widget.motion_smoothing
is_tracking = True
return segmentation_options, is_tracking
def _commit_to_file(path, viewer, layer, seg, mask, bb, extra_attrs=None):
# NOTE: zarr-python is quite inefficient and writes empty blocks.
# So we have to use z5py here.
# Deal with issues z5py has with empty folders and require the json.
if os.path.exists(path):
required_json = os.path.join(path, ".zgroup")
if not os.path.exists(required_json):
with open(required_json, "w") as f:
json.dump({"zarr_format": 2}, f)
f = z5py.ZarrFile(path, "a")
state = AnnotatorState()
def _save_signature(f, data_signature):
embeds = state.widgets["embeddings"]
tile_shape, halo = _process_tiling_inputs(
embeds.tile_x, embeds.tile_y, embeds.halo_x, embeds.halo_y
)
signature = util._get_embedding_signature(
input_=None, # We don't need this because we pass the data signature.
predictor=state.predictor,
tile_shape=tile_shape,
halo=halo,
data_signature=data_signature,
)
for key, val in signature.items():
f.attrs[key] = val
# If the data signature is saved in the file already,
# then we check if saved data signature and data signature of our image agree.
# If not, this file was used for committing objects from another file.
if "data_signature" in f.attrs:
saved_signature = f.attrs["data_signature"]
current_signature = state.data_signature
if saved_signature != current_signature: # Signatures disagree.
msg = f"The commit_path {path} was already used for saving annotations for different image data:\n"
msg += f"The data signatures are different: {saved_signature} != {current_signature}.\n"
msg += "Press 'Ok' to remove the data already stored in that file and continue annotation.\n"
msg += "Otherwise please select a different file path."
skip_clear = _generate_message("info", msg)
if skip_clear:
return
else:
f = z5py.ZarrFile(path, "w")
_save_signature(f, current_signature)
# Otherwise (data signature not saved yet), write the current signature.
else:
_save_signature(f, state.data_signature)
# Write the segmentation.
full_shape = viewer.layers["committed_objects"].data.shape
block_shape = util.get_block_shape(full_shape)
ds = f.require_dataset(
"committed_objects",
shape=full_shape,
chunks=block_shape,
compression="gzip",
dtype=seg.dtype,
)
ds.n_threads = mp.cpu_count()
data = ds[bb]
data[mask] = seg[mask]
ds[bb] = data
# Write additional information to attrs.
if extra_attrs is not None:
f.attrs.update(extra_attrs)
# Get the commit history and the objects that are being commited.
commit_history = f.attrs.get("commit_history", [])
object_ids = np.unique(seg[mask])
# We committed an automatic segmentation.
if layer == "auto_segmentation":
# Save the settings of the segmentation widget.
segmentation_options = _get_auto_segmentation_options(
state, object_ids
)
commit_history.append({"auto_segmentation": segmentation_options})
# Write the commit history.
f.attrs["commit_history"] = commit_history
# If we run commit from the automatic segmentation we don't have
# any prompts and so don't need to commit anything else.
return
segmentation_options, is_tracking = _get_promptable_segmentation_options(
state, object_ids
)
commit_history.append({"current_object": segmentation_options})
def write_prompts(
object_id, prompts, point_prompts, point_labels, track_state=None
):
g = f.create_group(f"prompts/{object_id}")
if prompts is not None and len(prompts) > 0:
data = np.array(prompts)
g.create_dataset(
"prompts", data=data, shape=data.shape, chunks=data.shape
)
if point_prompts is not None and len(point_prompts) > 0:
g.create_dataset(
"point_prompts",
data=point_prompts,
shape=data.shape,
chunks=point_prompts.shape,
)
ds = g.create_dataset(
"point_labels",
data=point_labels,
shape=data.shape,
chunks=point_labels.shape,
)
if track_state is not None:
ds.attrs["track_state"] = track_state.tolist()
# Get the prompts from the layers.
prompts = viewer.layers["prompts"].data
point_layer = viewer.layers["point_prompts"]
point_prompts = point_layer.data
point_labels = point_layer.properties["label"]
if len(point_prompts) > 0:
point_labels = np.array(
[1 if label == "positive" else 0 for label in point_labels]
)
assert len(point_prompts) == len(
point_labels
), f"Number of point prompts and labels disagree: {len(point_prompts)} != {len(point_labels)}"
# Commit the prompts for all the objects in the commit.
if len(object_ids) == 1: # We only have a single object.
write_prompts(object_ids[0], prompts, point_prompts, point_labels)
elif (
is_tracking
): # We have multiple objects from tracking a lineage with divisions.
track_ids_points = np.array(point_layer.properties["track_id"])
track_ids_prompts = np.array(
viewer.layers["prompts"].properties["track_id"]
)
unique_track_ids = np.unique(track_ids_points)
assert len(unique_track_ids) == len(object_ids)
track_state = np.array(point_layer.properties["state"])
for track_id, object_id in zip(unique_track_ids, object_ids):
this_prompts = (
None
if len(prompts) == 0
else prompts[track_ids_prompts == track_id]
)
point_mask = track_ids_points == track_id
this_points, this_labels, this_track_state = (
point_prompts[point_mask],
point_labels[point_mask],
track_state[point_mask],
)
write_prompts(
object_id,
this_prompts,
this_points,
this_labels,
track_state=this_track_state,
)
else: # We have multiple objects, which are the result from batched interactive segmentation.
# Note: we can't match exact object ids to their prompts, for batched segmentation.
# We first write the objects from box prompts, then from point prompts.
n_prompts, n_points = len(prompts), len(point_prompts)