-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy path_widgets.py
More file actions
1717 lines (1411 loc) · 66.9 KB
/
Copy path_widgets.py
File metadata and controls
1717 lines (1411 loc) · 66.9 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 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 zarr
import z5py
from qtpy import QtWidgets
from qtpy.QtCore import QObject, Signal
from superqt import QCollapsible
from magicgui import magic_factory
from magicgui.widgets import ComboBox, Container, create_widget
from napari.qt.threading import thread_worker
from napari.utils import progress
from ._state import AnnotatorState
from . import util as vutil
from ._tooltips import get_tooltip
from .. import instance_segmentation, util
from ..multi_dimensional_segmentation import segment_mask_in_volume, merge_instance_segmentation_3d, PROJECTION_MODES
#
# 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):
parent_widget = QtWidgets.QWidget()
parent_widget.setLayout(QtWidgets.QVBoxLayout())
collapsible = QCollapsible(title, parent_widget)
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 _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 _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, 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,
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,
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(value)
if placeholder is not None:
path_textbox.setPlaceholderText(placeholder)
path_textbox.textChanged.connect(lambda val: setattr(self, name, val))
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(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(file_path)
else:
# Handle the case where the selected path is not a file
print("Invalid file selected. Please try again.")
# 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):
super().__init__()
self.setWindowTitle(title)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(QtWidgets.QLabel(message))
# Add buttons
button_box = QtWidgets.QHBoxLayout() # Use QHBoxLayout for buttons side-by-side
accept_button = QtWidgets.QPushButton("OK")
accept_button.clicked.connect(lambda: self.button_clicked(accept_button)) # Connect to clicked signal
button_box.addWidget(accept_button)
cancel_button = QtWidgets.QPushButton("Cancel")
cancel_button.clicked.connect(lambda: self.button_clicked(cancel_button)) # Connect to clicked signal
button_box.addWidget(cancel_button)
layout.addLayout(button_box)
self.setLayout(layout)
def button_clicked(self, button):
if button.text() == "OK":
self.accept() # Accept the dialog
else:
self.reject() # Reject the dialog (Cancel)
# 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.
state.widgets["tracking"][1].value = "1"
state.widgets["tracking"][1].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)
@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.
"""
if all_slices:
vutil.clear_annotations(viewer)
else:
i = viewer.dims.current_step[0]
vutil.clear_annotations_slice(viewer, i=i)
@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 = viewer.dims.current_step[0]
vutil.clear_annotations_slice(viewer, i=i)
def _commit_impl(viewer, layer, preserve_committed):
# Check if we have a z_range. If yes, use it to set a bounding box.
state = AnnotatorState()
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)]
seg = viewer.layers[layer].data[bb]
shape = seg.shape
# We parallelize these operatios 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_committed:
prev_seg = viewer.layers["committed_objects"].data[bb]
mask[prev_seg != 0] = 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()
return id_offset, seg, mask, bb
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")
# Write metadata about the model that's being used etc.
# Only if it's not written to the file yet.
if "data_signature" not in f.attrs:
state = AnnotatorState()
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=state.data_signature,
)
for key, val in signature.items():
f.attrs[key] = val
# 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)
# If we run commit from the automatic segmentation we don't have
# any prompts and so don't need to commit anything else.
if layer == "auto_segmentation":
# TODO write the settings for the auto segmentation widget.
return
def write_prompts(object_id, prompts, point_prompts):
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, chunks=data.shape)
if point_prompts is not None and len(point_prompts) > 0:
g.create_dataset("point_prompts", data=point_prompts, chunks=point_prompts.shape)
# TODO write the settings for the segmentation widget if necessary.
# Commit the prompts for all the objects in the commit.
object_ids = np.unique(seg[mask])
if len(object_ids) == 1: # We only have a single object.
write_prompts(object_ids[0], viewer.layers["prompts"].data, viewer.layers["point_prompts"].data)
else:
# TODO this logic has to be updated to be compatible with the new batched prompting
have_prompts = len(viewer.layers["prompts"].data) > 0
have_point_prompts = len(viewer.layers["point_prompts"].data) > 0
if have_prompts and not have_point_prompts:
prompts = viewer.layers["prompts"].data
point_prompts = None
elif not have_prompts and have_point_prompts:
prompts = None
point_prompts = viewer.layers["point_prompts"].data
else:
msg = "Got multiple objects from interactive segmentation with box and point prompts." if (
have_prompts and have_point_prompts
) else "Got multiple objects from interactive segmentation with neither box or point prompts."
raise RuntimeError(msg)
for i, object_id in enumerate(object_ids):
write_prompts(
object_id,
None if prompts is None else prompts[i:i+1],
None if point_prompts is None else point_prompts[i:i+1]
)
@magic_factory(
call_button="Commit [C]",
layer={"choices": ["current_object", "auto_segmentation"]},
commit_path={"mode": "d"}, # choose a directory
)
def commit(
viewer: "napari.viewer.Viewer",
layer: str = "current_object",
preserve_committed: bool = True,
commit_path: Optional[Path] = None,
) -> None:
"""Widget for committing the segmented objects from automatic or interactive segmentation.
Args:
viewer: The napari viewer.
layer: Select the layer to commit. Can be either 'current_object' to commit interacitve segmentation results.
Or 'auto_segmentation' to commit automatic segmentation results.
preserve_committed: If active already committted objects are not over-written by new commits.
commit_path: Select a file path where the committed results and prompts will be saved.
This feature is still experimental.
"""
_, seg, mask, bb = _commit_impl(viewer, layer, preserve_committed)
if commit_path is not None:
_commit_to_file(commit_path, viewer, layer, seg, mask, bb)
if layer == "current_object":
vutil.clear_annotations(viewer)
else:
viewer.layers["auto_segmentation"].data = np.zeros(
viewer.layers["auto_segmentation"].data.shape, dtype="uint32"
)
viewer.layers["auto_segmentation"].refresh()
_select_layer(viewer, "committed_objects")
@magic_factory(
call_button="Commit [C]",
layer={"choices": ["current_object"]},
commit_path={"mode": "d"}, # choose a directory
)
def commit_track(
viewer: "napari.viewer.Viewer",
layer: str = "current_object",
preserve_committed: bool = True,
commit_path: Optional[Path] = None,
) -> None:
"""Widget for committing the objects from interactive tracking.
Args:
viewer: The napari viewer.
layer: Select the layer to commit. Can be either 'current_object' to commit interacitve segmentation results.
Or 'auto_segmentation' to commit automatic segmentation results.
preserve_committed: If active already committted objects are not over-written by new commits.
commit_path: Select a file path where the committed results and prompts will be saved.
This feature is still experimental.
"""
# Commit the segmentation layer.
id_offset, seg, mask, bb = _commit_impl(viewer, layer, preserve_committed)
# Update the lineages.
state = AnnotatorState()
updated_lineage = {
parent + id_offset: [child + id_offset for child in children] for parent, children in state.lineage.items()
}
state.committed_lineages.append(updated_lineage)
if commit_path is not None:
_commit_to_file(
commit_path, viewer, layer, seg, mask, bb,
extra_attrs={"committed_lineages": state.committed_lineages}
)
if layer == "current_object":
vutil.clear_annotations(viewer)
# Reset the tracking state.
_reset_tracking_state(viewer)
def create_prompt_menu(points_layer, labels, menu_name="prompt", label_name="label"):
"""Create the menu for toggling point prompt labels."""
label_menu = ComboBox(label=menu_name, choices=labels, tooltip=get_tooltip("prompt_menu", "labels"))
label_widget = Container(widgets=[label_menu])
def update_label_menu(event):
new_label = str(points_layer.current_properties[label_name][0])
if new_label != label_menu.value:
label_menu.value = new_label
points_layer.events.current_properties.connect(update_label_menu)
def label_changed(new_label):
current_properties = points_layer.current_properties
current_properties[label_name] = np.array([new_label])
points_layer.current_properties = current_properties
points_layer.refresh_colors()
label_menu.changed.connect(label_changed)
return label_widget
@magic_factory(
call_button="Update settings",
cache_directory={"mode": "d"}, # choose a directory
)
def settings_widget(
cache_directory: Optional[Path] = util.get_cache_directory(),
) -> None:
"""Widget to update global micro_sam settings.
Args:
cache_directory: Select the path for the micro_sam cache directory. `$HOME/.cache/micro_sam`.
"""
os.environ["MICROSAM_CACHEDIR"] = str(cache_directory)
print(f"micro-sam cache directory set to: {cache_directory}")
def _generate_message(message_type, message) -> bool:
"""
Displays a message dialog based on the provided message type.
Args:
message_type (str): The type of message to display. Valid options are:
- "error": Displays a critical error message with an "Ok" button.
- "info": Displays an informational message in a separate dialog box.
The user can dismiss it by either clicking "Ok" or closing the dialog.
message (str): The message content to be displayed in the dialog.
Returns:
bool: A flag indicating whether the user aborted the operation based on the
message type. This flag is only set for "info" messages where the user
can choose to cancel (rejected).
Raises:
ValueError: If an invalid message type is provided.
"""
# Set button text and behavior based on message type
if message_type == "error":
QtWidgets.QMessageBox.critical(None, "Error", message, QtWidgets.QMessageBox.Ok)
abort = True
return abort
elif message_type == "info":
info_dialog = InfoDialog(title="Validation Message", message=message)
result = info_dialog.exec_()
if result == QtWidgets.QDialog.Rejected: # Check for cancel
abort = True # Set flag directly in calling function
return abort
def _validate_embeddings(viewer: "napari.viewer.Viewer"):
state = AnnotatorState()
if state.image_embeddings is None:
msg = "Image embeddings are not yet computed. Press 'Compute Embeddings' to compute them for your image."
return _generate_message("error", msg)
else:
return False
# This code is for checking the data signature of the current image layer and the data signature
# of the embeddings. However, the code has some disadvantages, for example assuming the position of the
# image layer and also having to compute the data signature every time.
# That's why we are not using this for now, but may want to revisit this in the future. See:
# https://github.com/computational-cell-analytics/micro-sam/issues/504
# embeddings_save_path = state.embedding_path
# embedding_data_signature = None
# image = None
# if isinstance(viewer.layers[0], napari.layers.Image): # Assuming the image layer is at index 0
# image = viewer.layers[0]
# else:
# # Handle the case where the first layer isn't an Image layer
# raise ValueError("Expected an Image layer in viewer.layers")
# img_signature = util._compute_data_signature(image.data)
# if embeddings_save_path is not None:
# # Check for existing embeddings
# if os.listdir(embeddings_save_path):
# try:
# with zarr.open(embeddings_save_path, "a") as f:
# # If data_signature exists, compare and return validation message
# if "data_signature" in f.attrs:
# embedding_data_signature = f.attrs["data_signature"]
# except RuntimeError as e:
# val_results = {
# "message_type": "error",
# "message": f"Failed to load image embeddings: {e}"
# }
# else:
# val_results = {"message_type": "info", "message": "No existing embeddings found at the specified path."}
# else: # load from state object
# embedding_data_signature = state.data_signature
# # compare image data signature with embedding data signature
# if img_signature != embedding_data_signature:
# val_results = {
# "message_type": "error",
# "message": f"The embeddings don't match with the image: {img_signature} {embedding_data_signature}"
# }
# else:
# val_results = None
# if val_results:
# return _generate_message(val_results["message_type"], val_results["message"])
# else:
# return False
def _validate_prompts(viewer: "napari.viewer.Viewer") -> bool:
if len(viewer.layers["prompts"].data) == 0 and len(viewer.layers["point_prompts"].data) == 0:
msg = "No prompts were given. Please provide prompts to run interactive segmentation."
return _generate_message("error", msg)
else:
return False
@magic_factory(call_button="Segment Object [S]")
def segment(viewer: "napari.viewer.Viewer", batched: bool = False) -> None:
"""Segment object(s) for the current prompts.
Args:
viewer: The napari viewer.
batched: Choose if you want to segment multiple objects with point prompts.
"""
if _validate_embeddings(viewer):
return None
if _validate_prompts(viewer):
return None
shape = viewer.layers["current_object"].data.shape
# get the current box and point prompts
boxes, masks = vutil.shape_layer_to_prompts(viewer.layers["prompts"], shape)
points, labels = vutil.point_layer_to_prompts(viewer.layers["point_prompts"], with_stop_annotation=False)
state = AnnotatorState()
predictor = state.predictor
image_embeddings = state.image_embeddings
seg = vutil.prompt_segmentation(
predictor, points, labels, boxes, masks, shape, image_embeddings=image_embeddings,
multiple_box_prompts=True, batched=batched, previous_segmentation=viewer.layers["current_object"].data,
scale_factor=state.scale_factor
)
# No prompts were given or prompts were invalid, skip segmentation.
if isinstance(seg, str):
msg = f"Interactive segmentation failed due to the following reason:\n {seg}"
_generate_message("error", msg)
return
viewer.layers["current_object"].data = seg
viewer.layers["current_object"].refresh()
@magic_factory(call_button="Segment Slice [S]")
def segment_slice(viewer: "napari.viewer.Viewer") -> None:
"""Segment object for to the current prompts.
Args:
viewer: The napari viewer.
"""
if _validate_embeddings(viewer):
return None
if _validate_prompts(viewer):
return None
shape = viewer.layers["current_object"].data.shape[1:]
z = viewer.dims.current_step[0]
state = AnnotatorState()
scale_factor = state.scale_factor
point_prompts = vutil.point_layer_to_prompts(viewer.layers["point_prompts"], i=z, scale_factor=scale_factor)
# This is a stop prompt, we do nothing.
if not point_prompts:
return
# TODO
boxes, masks = vutil.shape_layer_to_prompts(viewer.layers["prompts"], shape, i=z)
points, labels = point_prompts
# Set the correct slice if we have a scale factor.
if scale_factor is not None:
z = int(z / scale_factor[0])
seg = vutil.prompt_segmentation(
state.predictor, points, labels, boxes, masks, shape, multiple_box_prompts=False,
image_embeddings=state.image_embeddings, i=z, scale_factor=scale_factor,
)
# No prompts were given or prompts were invalid, skip segmentation.
if isinstance(seg, str):
msg = f"Interactive segmentation failed due to the following reason:\n {seg}"
_generate_message("error", msg)
return
viewer.layers["current_object"].data[z] = seg
viewer.layers["current_object"].refresh()
@magic_factory(call_button="Segment Frame [S]")
def segment_frame(viewer: "napari.viewer.Viewer") -> None:
"""Segment object for the current prompts.
Args:
viewer: The napari viewer.
"""
if _validate_embeddings(viewer):
return None
if _validate_prompts(viewer):
return None
state = AnnotatorState()
shape = state.image_shape[1:]
t = viewer.dims.current_step[0]
point_prompts = vutil.point_layer_to_prompts(viewer.layers["point_prompts"], i=t, track_id=state.current_track_id)
# this is a stop prompt, we do nothing
if not point_prompts:
return
boxes, masks = vutil.shape_layer_to_prompts(viewer.layers["prompts"], shape, i=t, track_id=state.current_track_id)
points, labels = point_prompts
seg = vutil.prompt_segmentation(
state.predictor, points, labels, boxes, masks, shape, multiple_box_prompts=False,
image_embeddings=state.image_embeddings, i=t, scale_factor=state.scale_factor,
)
# No prompts were given or prompts were invalid, skip segmentation.
if isinstance(seg, str):
msg = f"Interactive segmentation failed due to the following reason:\n {seg}"
_generate_message("error", msg)
return
# Clear the old segmentation for this track_id.
old_mask = viewer.layers["current_object"].data[t] == state.current_track_id
viewer.layers["current_object"].data[t][old_mask] = 0
# Set the new segmentation.
new_mask = seg.squeeze() == 1
viewer.layers["current_object"].data[t][new_mask] = state.current_track_id
viewer.layers["current_object"].refresh()
#
# Functionality and widget to compute the image embeddings.
#
def _process_tiling_inputs(tile_shape_x, tile_shape_y, halo_x, halo_y):
tile_shape = (tile_shape_x, tile_shape_y)
halo = (halo_x, halo_y)
# check if tile_shape/halo are not set: (0, 0)
if all(item in (0, None) for item in tile_shape):
tile_shape = None
# check if at least 1 param is given
elif tile_shape[0] == 0 or tile_shape[1] == 0:
max_val = max(tile_shape[0], tile_shape[1])
if max_val < 256: # at least tile shape >256
max_val = 256
tile_shape = (max_val, max_val)
# if both inputs given, check if smaller than 256
elif tile_shape[0] != 0 and tile_shape[1] != 0:
if tile_shape[0] < 256:
tile_shape = (256, tile_shape[1]) # Create a new tuple
if tile_shape[1] < 256:
tile_shape = (tile_shape[0], 256) # Create a new tuple with modified value
if all(item in (0, None) for item in halo):
if tile_shape is not None:
halo = (0, 0)
else:
halo = None
# check if at least 1 param is given
elif halo[0] != 0 or halo[1] != 0:
max_val = max(halo[0], halo[1])
# don't apply halo if there is no tiling
if tile_shape is None:
halo = None
else:
halo = (max_val, max_val)
return tile_shape, halo
class _LevelSelector(QtWidgets.QDialog):
selected_level = Signal(int)
def __init__(self, image):
super().__init__()
self.setWindowTitle("Select Level")
layout = QtWidgets.QVBoxLayout()
shapes = [data.shape for data in image.data]
message = "You have selected a multiscale image with scale levels:\n"
for level, shape in enumerate(shapes):
message += f"{level}: Shape: {' X '.join(map(str, shape))}\n"
message += "Please select the level to use for embedding computation."
layout.addWidget(QtWidgets.QLabel(message))
n_levels = len(shapes)
levels = [str(i) for i in range(n_levels)]
self.combo_box = QtWidgets.QComboBox(self)
self.combo_box.addItems(levels)
layout.addWidget(self.combo_box)
# Create a button to close the window.
close_button = QtWidgets.QPushButton("Close")
close_button.clicked.connect(self.button_clicked)
layout.addWidget(close_button)
self.setLayout(layout)
def button_clicked(self, button):
self.selected_level.emit(int(self.combo_box.currentText()))
self.accept()
class EmbeddingWidget(_WidgetBase):
def __init__(self, parent=None):
super().__init__(parent=parent)
# Create a nested layout for the sections.
# Section 1: Image and Model.
section1_layout = QtWidgets.QHBoxLayout()
section1_layout.addLayout(self._create_image_section())
section1_layout.addLayout(self._create_model_section())
self.layout().addLayout(section1_layout)
# Section 2: Settings (collapsible).
self.layout().addWidget(self._create_settings_widget())
# Section 3: The button to trigger the embedding computation.
self.run_button = QtWidgets.QPushButton("Compute Embeddings")
self.run_button.clicked.connect(self._initialize_image)
self.run_button.clicked.connect(self.__call__)
self.run_button.setToolTip(get_tooltip("embedding", "run_button"))
self.layout().addWidget(self.run_button)
def _initialize_image(self):
state = AnnotatorState()
image_shape = self.image_selection.get_value().data.shape
state.image_shape = image_shape
def _create_image_section(self):
image_section = QtWidgets.QVBoxLayout()
image_layer_widget = QtWidgets.QLabel("Image Layer:")
# image_layer_widget.setToolTip(get_tooltip("embedding", "image")) # this adds tooltip to label
image_section.addWidget(image_layer_widget)
# Setting a napari layer in QT, see:
# https://github.com/pyapp-kit/magicgui/blob/main/docs/examples/napari/napari_combine_qt.py
self.image_selection = create_widget(annotation=napari.layers.Image)
self.image_selection.native.setToolTip(get_tooltip("embedding", "image"))
image_section.addWidget(self.image_selection.native)
return image_section
def _update_model(self):
print("Computed embeddings for", self.model_type)
state = AnnotatorState()
# Update the widget itself. This is necessary because we may have loaded
# some settings from the embedding file and have to reflect them in the widget.
vutil._sync_embedding_widget(
self,
model_type=self.model_type,
save_path=self.embeddings_save_path,
checkpoint_path=self.custom_weights,
device=self.device,
tile_shape=[self.tile_x, self.tile_y],
halo=[self.halo_x, self.halo_y]
)
# Set the default settings for this model in the autosegment widget if it is part of
# the currently used plugin.
if "autosegment" in state.widgets:
with_decoder = state.decoder is not None
vutil._sync_autosegment_widget(
state.widgets["autosegment"], self.model_type, self.custom_weights, update_decoder=with_decoder
)
# Load the AMG/AIS state if we have a 3d segmentation plugin.
if state.widgets["autosegment"].volumetric and with_decoder:
state.amg_state = vutil._load_is_state(state.embedding_path)
elif state.widgets["autosegment"].volumetric and not with_decoder:
state.amg_state = vutil._load_amg_state(state.embedding_path)
# Set the default settings for this model in the nd-segmentation widget if it is part of
# the currently used plugin.
if "segment_nd" in state.widgets:
vutil._sync_ndsegment_widget(state.widgets["segment_nd"], self.model_type, self.custom_weights)
def _create_model_section(self):
self.model_type = util._DEFAULT_MODEL
self.model_options = list(util.models().urls.keys())
# Filter out the decoders from the model list.
self.model_options = [model for model in self.model_options if not model.endswith("decoder")]
layout = QtWidgets.QVBoxLayout()
self.model_dropdown, layout = self._add_choice_param(
"model_type", self.model_type, self.model_options, title="Model:", layout=layout,
tooltip=get_tooltip("embedding", "model")
)
return layout
def _create_settings_widget(self):
setting_values = QtWidgets.QWidget()
setting_values.setToolTip(get_tooltip("embedding", "settings"))
setting_values.setLayout(QtWidgets.QVBoxLayout())
# Create UI for the device.
self.device = "auto"
device_options = ["auto"] + util._available_devices()
self.device_dropdown, layout = self._add_choice_param("device", self.device, device_options,
tooltip=get_tooltip("embedding", "device"))
setting_values.layout().addLayout(layout)
# Create UI for the save path.
self.embeddings_save_path = None
self.embeddings_save_path_param, layout = self._add_path_param(
"embeddings_save_path", self.embeddings_save_path, "directory", title="embeddings save path:",
tooltip=get_tooltip("embedding", "embeddings_save_path")
)
setting_values.layout().addLayout(layout)
# Create UI for the custom weights.
self.custom_weights = None
self.custom_weights_param, layout = self._add_path_param(
"custom_weights", self.custom_weights, "file", title="custom weights path:",
tooltip=get_tooltip("embedding", "custom_weights")
)
setting_values.layout().addLayout(layout)