-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1840 lines (1533 loc) · 83.9 KB
/
app.py
File metadata and controls
1840 lines (1533 loc) · 83.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
import sys
import os
import cv2
import numpy as np
import time
import tempfile
import torch
import traceback
import warnings
from PyQt6.QtWidgets import (
QApplication, QWidget, QLabel, QPushButton, QFileDialog, QVBoxLayout,
QHBoxLayout, QMessageBox, QDialog, QProgressBar, QLineEdit, QListWidget,
QListWidgetItem, QColorDialog, QGridLayout
)
from PyQt6.QtGui import QPixmap, QImage, QColor
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer
from segmenter_sam2 import Segmenter
from point_selection_strategies import ToolSelectionStrategy
from plas.segmenter_plas import SuperpixelLabelExpander
from app_modules import LabelDialog, OverlapDialog
# Reduce noisy external warnings (safe to ignore)
# SIP/PyQt deprecation noise
warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*sipPyTypeDict\(\).*")
# SAM2 optional extension warning (post-processing fallback)
warnings.filterwarnings("ignore", category=UserWarning, message=r".*cannot import name '_C' from 'sam2'.*")
# PyTorch SDPA backend: avoid flash/mem-efficient attempts and related warnings
try:
if hasattr(torch.backends, "cuda"):
torch.backends.cuda.enable_flash_sdp(False)
torch.backends.cuda.enable_mem_efficient_sdp(False)
torch.backends.cuda.enable_math_sdp(True)
except Exception:
pass
# Silence specific SDPA kernel selection chatter
warnings.filterwarnings("ignore", category=UserWarning, message=r".*Flash attention kernel not used.*")
warnings.filterwarnings("ignore", category=UserWarning, message=r".*Memory Efficient attention has been runtime disabled.*")
warnings.filterwarnings("ignore", category=UserWarning, message=r".*Memory efficient kernel not used because.*")
warnings.filterwarnings("ignore", category=UserWarning, message=r".*CuDNN attention kernel not used.*")
warnings.filterwarnings("ignore", category=UserWarning, message=r".*Expected query, key and value to all be of dtype.*scaled_dot_product_attention.*")
def load_stylesheet(file_path):
"""Load stylesheet from a file"""
try:
with open(file_path, 'r') as f:
return f.read()
except Exception as e:
print(f"Error loading stylesheet: {e}")
return ""
# Subclass QLabel to capture mouse clicks on the image
class ClickableLabel(QLabel):
clicked = pyqtSignal(object)
right_clicked = pyqtSignal(object) # New signal for right-click
mouse_moved = pyqtSignal(object) # New signal for mouse move
def __init__(self, parent=None):
super().__init__(parent)
self.setMouseTracking(True)
self.interactions_enabled = False
def mousePressEvent(self, event):
if self.interactions_enabled:
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit(event.pos())
elif event.button() == Qt.MouseButton.RightButton:
self.right_clicked.emit(event.pos())
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if (self.interactions_enabled):
self.mouse_moved.emit(event.pos())
super().mouseMoveEvent(event)
# Thread to suggest the next point using the adaptive interactive selection strategy
class PointSuggestionThread(QThread):
result_ready = pyqtSignal(tuple)
heatmap_ready = pyqtSignal(object, object) # (A_map, next_point)
error_occurred = pyqtSignal(str)
def __init__(self, strategy, segmenter, image, expanded_masks=None, last_mask=None, last_feature=None, actual_last_point=None, parent=None):
super().__init__(parent)
self.strategy = strategy
self.segmenter = segmenter
self.image = image
self.expanded_masks = expanded_masks or []
self.last_mask = last_mask
self.last_feature = last_feature
self.actual_last_point = actual_last_point
def run(self):
try:
next_point = self.strategy.get_next_point(
last_mask=self.last_mask,
actual_last_point=self.actual_last_point
)
# If the strategy has a last acquisition map, emit it for main-thread display
A_map = getattr(self.strategy, '_last_acquisition_map', None)
if A_map is not None:
self.heatmap_ready.emit(A_map, next_point)
self.result_ready.emit(next_point)
except Exception as e:
self.error_occurred.emit(str(e))
import traceback
traceback.print_exc()
# Thread to expand the user-selected point into a mask using an existing segmenter
class MaskExpansionThread(QThread):
result_ready = pyqtSignal(object)
def __init__(self, segmenter, points, labels):
super().__init__()
self.segmenter = segmenter
self.points = points
self.labels = labels
def run(self):
mask = self.segmenter.propagate_points(self.points, self.labels, update_expanded_mask=True)
self.result_ready.emit(mask)
class ImageViewer(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Image Viewer")
self.setGeometry(100, 100, 1200, 800)
# Image display
self.image_label = ClickableLabel(self)
self.image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.image_label.setFixedSize(1000, 700)
self.image_label.clicked.connect(self.on_image_clicked)
self.image_label.right_clicked.connect(self.on_image_right_clicked)
self.image_label.interactions_enabled = False
# Buttons
stylesheet = load_stylesheet("app_modules/button_styles.qss")
app.setStyleSheet(stylesheet)
self.select_button = QPushButton("Select Folder", self)
self.select_button.clicked.connect(self.select_folder)
self.select_button.setFixedSize(150, 40)
self.select_button.setProperty("class", "select-folder-button")
self.select_button.enterEvent = lambda e: self.on_cursor_over_button()
self.start_button = QPushButton("Start", self)
self.start_button.clicked.connect(self.start_labeling)
self.start_button.setFixedSize(150, 40)
self.start_button.setEnabled(False)
self.start_button.setProperty("class", "start-button")
self.start_button.enterEvent = lambda e: self.on_cursor_over_button()
# Navigation buttons
self.prev_button = QPushButton("<", self)
self.prev_button.clicked.connect(self.prev_image)
self.prev_button.setFixedSize(40, 40)
self.prev_button.setEnabled(False)
self.prev_button.setProperty("class", "navigation-button")
self.prev_button.enterEvent = lambda e: self.on_cursor_over_button()
self.next_button = QPushButton(">", self)
self.next_button.clicked.connect(self.next_image)
self.next_button.setFixedSize(40, 40)
self.next_button.setEnabled(False)
self.next_button.setProperty("class", "navigation-button")
self.next_button.enterEvent = lambda e: self.on_cursor_over_button()
# New buttons for point selection
self.switch_button = QPushButton("Negative", self)
self.switch_button.clicked.connect(self.switch_point_type)
self.switch_button.setFixedSize(150, 40)
self.switch_button.setEnabled(False)
self.switch_button.setProperty("class", "switch-button-negative")
self.switch_button.enterEvent = lambda e: self.on_cursor_over_button()
self.finish_button = QPushButton("✓", self)
self.finish_button.clicked.connect(self.on_finish_button_clicked)
self.finish_button.setFixedSize(40, 40)
self.finish_button.setEnabled(False)
self.finish_button.setProperty("class", "finish-button")
self.finish_button.enterEvent = lambda e: self.on_cursor_over_button()
# Toggle mask visibility button
self.toggle_masks_button = QPushButton("👁️", self)
self.toggle_masks_button.clicked.connect(self.toggle_masks_visibility)
self.toggle_masks_button.setFixedSize(40, 40)
self.toggle_masks_button.setEnabled(False)
self.toggle_masks_button.setProperty("class", "toggle-masks-button")
self.toggle_masks_button.enterEvent = lambda e: self.on_cursor_over_button()
# Create a horizontal layout for the bottom buttons
bottom_button_layout = QHBoxLayout()
bottom_button_layout.addStretch()
bottom_button_layout.addWidget(self.start_button)
bottom_button_layout.addWidget(self.switch_button)
bottom_button_layout.addWidget(self.finish_button)
bottom_button_layout.addWidget(self.toggle_masks_button)
bottom_button_layout.addStretch()
# Create a container widget for the image and navigation buttons
image_container = QWidget()
image_container.setFixedSize(1080, 700) # Increased width to accommodate buttons
image_container_layout = QGridLayout(image_container)
image_container_layout.setContentsMargins(0, 0, 0, 0)
image_container_layout.setSpacing(0)
# Add image label to the center
image_container_layout.addWidget(self.image_label, 0, 1) # Changed to column 1
# Add navigation buttons to corners
image_container_layout.addWidget(self.prev_button, 0, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
image_container_layout.addWidget(self.next_button, 0, 2, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
# Main layout: image on left, bottom buttons below
main_layout = QVBoxLayout()
# Create a horizontal layout for the top row (select folder button)
top_layout = QHBoxLayout()
top_layout.addWidget(self.select_button)
top_layout.addStretch()
main_layout.addLayout(top_layout)
main_layout.addWidget(image_container, alignment=Qt.AlignmentFlag.AlignCenter)
main_layout.addLayout(bottom_button_layout)
self.setLayout(main_layout)
# Variables
self.image_list = []
self.current_index = 0
self.current_image = None
self.overlay_image = None
self.displayed_pixmap = None
self.segmenter = None
self.plas_segmenter = None # Initialize PLAS segmenter
self.labels = {}
self.expanded_masks = []
self.combined_mask_overlay = None
self.image_label.mouse_moved.connect(self.on_mouse_moved)
# New variables for multiple points
self.positive_points = []
self.negative_points = []
self.current_point_type = "positive" # or "negative"
self.is_selecting_points = False
# Initially hide the point selection buttons
self.switch_button.hide()
self.finish_button.hide()
self.toggle_masks_button.hide()
# Initialize additional variables
self.current_image_path = None
self.current_label = None
self.expanded_areas_mask = None
self.current_mask = None
self.is_expanding = False
self.current_mask_area = 0
self.total_image_area = 0
self.coverage_ratio = 0
self.last_actual_click = None # Track the user's actual last click
self.current_mode = "creation" # or "selection"
self.is_over_mask = False
self.current_mask_index = None
self.masks_visible = True
# Initialize the point selection strategy
self.point_strategy = None
def select_folder(self):
folder = QFileDialog.getExistingDirectory(self, "Select Folder with Images")
if folder:
self.image_list = [
os.path.join(folder, f)
for f in os.listdir(folder)
if f.lower().endswith((".png", ".jpg", ".jpeg", ".bmp", ".gif"))
]
self.image_list.sort()
self.current_index = 0
# Reset all labeling-related state when selecting a new folder
self.segmenter = None # Reset segmenter for a new folder
self.plas_segmenter = None # Reset PLAS segmenter
self.point_strategy = None # Reset point strategy
self.expanded_masks = []
self.combined_mask_overlay = None
self.suggested_point = None
# Reset points and labeling state
self.positive_points = []
self.negative_points = []
self.is_selecting_points = False
self.last_actual_click = None # Reset tracking
# Reset UI to initial state
self.image_label.interactions_enabled = False
self.switch_button.hide()
self.finish_button.hide()
self.toggle_masks_button.hide()
self.toggle_masks_button.setEnabled(False)
self.start_button.setEnabled(True)
if self.image_list:
# Load and display the first image of the new folder
current_image_path = self.image_list[self.current_index]
image = cv2.imread(current_image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
self.current_image = image
self.show_image()
# Enable navigation buttons
self.next_button.setEnabled(True)
self.prev_button.setEnabled(True)
def start_labeling(self):
if not self.image_list or self.current_index >= len(self.image_list):
return
# Enable image interactions and show point selection buttons
self.image_label.interactions_enabled = True
self.switch_button.show()
self.switch_button.setEnabled(False) # Initially disabled
self.finish_button.show()
self.finish_button.setEnabled(False) # Will be enabled after first positive point
self.start_button.setEnabled(False) # Disable Start button until Next Image is pressed
self.is_selecting_points = True
# Show the toggle masks button but disable it until first mask is created
self.toggle_masks_button.show()
self.toggle_masks_button.setEnabled(False)
# Create a modal progress dialog
wait_dialog = QDialog(self)
wait_dialog.setWindowTitle("Generating Proposed Point")
wait_dialog.setModal(True)
wait_layout = QVBoxLayout()
wait_label = QLabel("Please wait while the proposed point is being generated...")
wait_layout.addWidget(wait_label)
progress_bar = QProgressBar(wait_dialog)
progress_bar.setRange(0, 0) # Indeterminate mode
wait_layout.addWidget(progress_bar)
wait_dialog.setLayout(wait_layout)
wait_dialog.resize(400, 150)
wait_dialog.show()
QApplication.processEvents()
QTimer.singleShot(100, lambda: self.initialize_segmenter_and_start_thread(wait_dialog))
wait_dialog.exec()
import sys
def print_memory_usage(self):
"""Print the memory usage of key objects in GB."""
expanded_masks_size = sys.getsizeof(self.expanded_masks)
combined_mask_overlay_size = sys.getsizeof(self.combined_mask_overlay) if self.combined_mask_overlay is not None else 0
# Convert sizes to MB
expanded_masks_mb = expanded_masks_size / (1024 ** 2)
combined_mask_overlay_mb = combined_mask_overlay_size / (1024 ** 2)
print(f"Memory Usage:")
print(f" - expanded_masks: {expanded_masks_mb:.4f} MB")
print(f" - combined_mask_overlay: {combined_mask_overlay_mb:.4f} MB")
def initialize_segmenter_and_start_thread(self, wait_dialog):
sam2_checkpoint = "checkpoints/sam2.1_hiera_large.pt"
# sam_checkpoint = "checkpoints/vit_b_coralscop.pth"
sam2_cfg = "configs/sam2.1/sam2.1_hiera_l.yaml"
current_image_path = self.image_list[self.current_index]
image = cv2.imread(current_image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
self.current_image = image
if self.segmenter is None:
# Segmenter(image=None, sam2_checkpoint_path=None, sam2_config_path=None, device='cuda')
# The second arg in app previously pointed to a SAM1 checkpoint; Segmenter expects SAM2 checkpoint and config.
# Pass correct positions: (image=None, sam2_checkpoint_path, sam2_config_path, device)
self.segmenter = Segmenter(
image=None,
sam2_checkpoint_path=sam2_checkpoint,
sam2_config_path=sam2_cfg,
device="cuda" if torch.cuda.is_available() else "cpu",
)
# Generate masks for the current image
self.segmenter.set_image(self.current_image)
# Initialize PLAS segmenter for superpixel-based expansion
self.plas_segmenter = SuperpixelLabelExpander("cuda" if torch.cuda.is_available() else "cpu")
# Initialize the point selection strategy
wait_dialog.setWindowTitle("Initializing Point Selection Strategy")
wait_layout = wait_dialog.layout()
wait_layout.itemAt(0).widget().setText("Setting up interactive point selection...")
QApplication.processEvents()
# Get generated masks and features for the strategy
generated_masks = self.segmenter.masks
print(f"Found {len(generated_masks)} potential objects")
# Extract features for all masks
features = []
for mask_data in generated_masks:
# Use a simple approach for features - could be improved
mask = mask_data['segmentation']
# Simple feature: area and position
area = np.sum(mask)
if area > 0:
y_indices, x_indices = np.where(mask)
centroid_y = np.mean(y_indices)
centroid_x = np.mean(x_indices)
# Create a simple feature vector
feature = np.array([area, centroid_y, centroid_x, mask_data.get('predicted_iou', 0.5)])
features.append(feature)
else:
features.append(np.zeros(4))
features = np.array(features)
# Initialize the strategy
self.point_strategy = ToolSelectionStrategy()
# Setup expects only (image, generated_masks)
self.point_strategy.setup_simple(self.current_image, generated_masks)
# Store generated masks in the strategy for the random phase
self.point_strategy.generated_masks = generated_masks
# Get the first suggested point
self.point_thread = PointSuggestionThread(
self.point_strategy,
self.segmenter,
self.current_image,
expanded_masks=self.expanded_masks,
last_mask=None,
last_feature=None,
actual_last_point=None
)
self.point_thread.result_ready.connect(lambda next_point: self.on_point_suggestion_complete(next_point, wait_dialog))
self.point_thread.error_occurred.connect(lambda error: self.on_point_suggestion_error(error, wait_dialog))
self.point_thread.heatmap_ready.connect(lambda A_map, next_point: self.display_acquisition_heatmap_main_thread(A_map, next_point))
self.point_thread.start()
def display_acquisition_heatmap_main_thread(self, A_map, next_point):
return
# This slot runs in the main thread and is safe for Matplotlib GUI
try:
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 8))
plt.imshow(A_map, origin='upper', cmap='viridis')
if next_point is not None:
y, x = next_point
plt.scatter(x, y, s=100, facecolors='none', edgecolors='red', linewidth=2)
plt.axis('off')
plt.colorbar(label='Acquisition Score')
plt.title('Adaptive Interactive Strategy - Acquisition Map')
plt.show(block=False)
plt.pause(0.001)
except Exception as e:
print(f"Error displaying heatmap: {e}")
def on_point_suggestion_complete(self, next_point, wait_dialog):
wait_dialog.accept()
if next_point:
self.suggested_point = next_point
else:
print("No valid point proposed.")
self.suggested_point = None
self.show_image(overlay_point=self.suggested_point)
def on_point_suggestion_error(self, error_msg, wait_dialog):
wait_dialog.accept()
print(f"Error in point suggestion: {error_msg}")
# Fall back to center of image
if hasattr(self, 'current_image') and self.current_image is not None:
h, w = self.current_image.shape[:2]
self.suggested_point = (h // 2, w // 2)
else:
self.suggested_point = None
self.show_image(overlay_point=self.suggested_point)
def on_image_clicked(self, pos):
if self.current_image is None or self.displayed_pixmap is None:
return
# Convert click position to image coordinates
current_point = self.get_image_coordinates(pos)
if current_point is None:
return
# Check which mode we're in
if hasattr(self, 'current_mode'):
# Don't do anything on clicks in visualization mode
if self.current_mode == "visualization":
return
elif self.current_mode == "selection":
mask_index = self.get_mask_at_position(current_point)
if mask_index is not None:
# Show context menu for the selected mask
self.current_mask_index = mask_index
self.show_mask_context_menu(pos, mask_index)
return
elif self.current_mode == "creation":
# In creation mode, always allow point placement
# Check if we're clicking over an existing mask for potential merging
mask_index = self.get_mask_at_position(current_point)
# Add the point first
if self.current_point_type == "positive":
self.positive_points.append(current_point)
print(f"Positive point added at: {current_point}")
self.finish_button.setEnabled(True)
self.switch_button.setEnabled(True)
# Track actual user click for adaptive strategy
self.last_actual_click = current_point
else:
self.negative_points.append(current_point)
print(f"Negative point added at: {current_point}")
# Track actual user click for adaptive strategy
self.last_actual_click = current_point
# Check if this click overlaps with existing masks (for positive points only)
overlap_info = None
if self.current_point_type == "positive":
# Check if the clicked point overlaps with any existing mask
overlap_info = self.check_point_overlap(current_point)
# Check if we need to handle overlap
if overlap_info:
# Remove the point we just added since we'll handle it through overlap dialog
if self.current_point_type == "positive":
self.positive_points.pop()
else:
self.negative_points.pop()
self.handle_point_overlap(current_point, overlap_info)
else:
# Normal point placement behavior
self.update_preview_with_points()
else:
# Fallback if mode is not set
if self.current_point_type == "positive":
self.positive_points.append(current_point)
print(f"Positive point added at: {current_point}")
self.finish_button.setEnabled(True)
self.switch_button.setEnabled(True)
# Track actual user click for adaptive strategy
self.last_actual_click = current_point
else:
self.negative_points.append(current_point)
print(f"Negative point added at: {current_point}")
# Track actual user click for adaptive strategy
self.last_actual_click = current_point
# Update preview with the new point
self.update_preview_with_points()
def on_image_right_clicked(self, pos):
"""Handle right-click on image - show context menu for masks"""
if self.current_image is None or self.displayed_pixmap is None:
return
# Convert click position to image coordinates
current_point = self.get_image_coordinates(pos)
if current_point is None:
return
# Only show context menu in creation mode and if we're over a mask
if (hasattr(self, 'current_mode') and self.current_mode == "creation" and
self.masks_visible):
mask_index = self.get_mask_at_position(current_point)
if mask_index is not None:
# Show context menu for the selected mask
self.current_mask_index = mask_index
self.show_mask_context_menu(pos, mask_index)
def update_preview_with_points(self):
"""Update display with current points and preview mask"""
# Start with original image and add cached overlay if masks are visible
overlay_image = self.current_image.copy()
if self.masks_visible and self.combined_mask_overlay is not None:
overlay_image = cv2.addWeighted(overlay_image, 1.0, self.combined_mask_overlay, 0.8, 0)
# Draw all current points
for point in self.positive_points:
cv2.circle(overlay_image, point, 4, (0, 255, 0), -1) # Green for positive
for point in self.negative_points:
cv2.circle(overlay_image, point, 4, (255, 0, 0), -1) # Red for negative
# Show dynamic expansion with current points
if self.positive_points or self.negative_points:
points = np.array(self.positive_points + self.negative_points)
labels = np.array([1] * len(self.positive_points) + [0] * len(self.negative_points))
preview_mask = self.segmenter.propagate_points(points, labels, update_expanded_mask=False)
if preview_mask is not None:
colored_preview = np.zeros_like(overlay_image)
colored_preview[preview_mask > 0] = (128, 128, 128) # Gray for preview
overlay_image = cv2.addWeighted(overlay_image, 1.0, colored_preview, 0.4, 0)
# Show suggested point cross when updating preview with points
if hasattr(self, 'suggested_point') and self.suggested_point:
row, col = self.suggested_point
cv2.line(overlay_image, (col, row - 6), (col, row + 6), (255, 255, 0), 2)
cv2.line(overlay_image, (col - 6, row), (col + 6, row), (255, 255, 0), 2)
self.update_display(overlay_image)
def delete_mask(self, mask_index):
"""Delete a mask and update the display"""
if not (0 <= mask_index < len(self.expanded_masks)):
return
mask, label, _ = self.expanded_masks[mask_index]
# Remove from expanded masks
self.expanded_masks.pop(mask_index)
# Regenerate the combined mask overlay
self.regenerate_combined_mask_overlay()
# Reset selection state
self.current_mask_index = None
self.current_mode = "creation"
self.is_over_mask = False
self.setCursor(Qt.CursorShape.ArrowCursor)
# Print informative message
print(f"Deleted mask with label '{label}'")
# Update the display
self.update_display_with_current_state()
def change_mask_label(self, mask_index):
"""Change the label of a mask"""
if not (0 <= mask_index < len(self.expanded_masks)):
return
mask, old_label, _ = self.expanded_masks[mask_index]
# Show label dialog to pick a new label
dialog = LabelDialog(self.labels, self)
if dialog.exec() == QDialog.DialogCode.Accepted:
new_label = dialog.selected_label
if new_label is None:
new_label = dialog.new_label_edit.text()
if new_label and dialog.chosen_color:
self.labels[new_label] = dialog.chosen_color
if new_label and new_label in self.labels:
color = self.labels[new_label]
# Update the mask in the list
self.expanded_masks[mask_index] = (mask, new_label, color)
# Update the combined overlay
self.regenerate_combined_mask_overlay()
print(f"Changed mask label from '{old_label}' to '{new_label}'")
# Update the display
self.update_display_with_current_state()
def regenerate_combined_mask_overlay(self):
"""Regenerate the combined mask overlay from all masks"""
if not self.expanded_masks:
self.combined_mask_overlay = None
return
self.combined_mask_overlay = np.zeros_like(self.current_image)
for mask, _, color in self.expanded_masks:
colored_mask = np.zeros_like(self.current_image)
colored_mask[mask > 0] = [color.red(), color.green(), color.blue()]
self.combined_mask_overlay[mask > 0] = colored_mask[mask > 0]
def show_mask_context_menu(self, pos, mask_index):
"""Show context menu for the selected mask"""
from PyQt6.QtWidgets import QMenu
from PyQt6.QtGui import QAction # Import QAction from QtGui instead of QtWidgets
if mask_index is None or mask_index >= len(self.expanded_masks):
return
mask, label, color = self.expanded_masks[mask_index]
# Create context menu
context_menu = QMenu(self)
# Add actions
delete_action = QAction(f"Delete '{label}' mask", self)
change_label_action = QAction(f"Change label (current: '{label}')", self)
# Add actions to menu
context_menu.addAction(delete_action)
context_menu.addAction(change_label_action)
# Connect actions to handlers
delete_action.triggered.connect(lambda: self.delete_mask(mask_index))
change_label_action.triggered.connect(lambda: self.change_mask_label(mask_index))
# Show context menu at cursor position
context_menu.exec(self.mapToGlobal(pos))
def on_mask_expansion_complete(self, mask, stored_positive_points):
if mask is None:
print("No mask generated.")
self.is_expanding = False # Reset expansion state
self.finish_button.setEnabled(True) # Re-enable the finish button
return
dialog = LabelDialog(self.labels, self)
if dialog.exec() == QDialog.DialogCode.Accepted:
label = dialog.selected_label
if label is None:
label = dialog.new_label_edit.text()
if label and dialog.chosen_color:
self.labels[label] = dialog.chosen_color
color = self.labels.get(label)
if color:
# Update current_mask and current_label for future reference
self.current_mask = mask
self.current_label = label
# Keep storing in expanded_masks for future reference
self.expanded_masks.append((mask, label, color))
# Enable the toggle masks button after first mask is created
if not self.toggle_masks_button.isEnabled():
self.toggle_masks_button.setEnabled(True)
# Create overlay image BEFORE using it
overlay_image = self.current_image.copy()
# Update the combined overlay for efficient display
if self.combined_mask_overlay is None:
self.combined_mask_overlay = np.zeros_like(self.current_image)
colored_mask = np.zeros_like(overlay_image)
colored_mask[mask > 0] = [color.red(), color.green(), color.blue()]
self.combined_mask_overlay[mask > 0] = colored_mask[mask > 0]
# Update display with the new combined overlay and suggested point
overlay_image = cv2.addWeighted(self.current_image, 1.0, self.combined_mask_overlay, 0.8, 0)
self.update_display(overlay_image)
# Calculate and display coverage statistics
self.current_mask_area = np.sum(mask)
self.total_image_area = self.current_image.shape[0] * self.current_image.shape[1]
self.coverage_ratio = self.current_mask_area / self.total_image_area
print(f"Added mask with label '{label}' - Coverage: {self.coverage_ratio:.2%}")
# Reset expansion state regardless of dialog result
self.is_expanding = False
# Re-enable the finish button for the next mask
self.finish_button.setEnabled(True)
# Instead of automatically starting a new labeling cycle, just prepare for the next one
# This way the user can place points for the next mask at their own pace
self.switch_button.setEnabled(False)
if self.current_point_type == "negative":
self.switch_point_type() # Reset to positive if it was negative
# Get next suggested point using the point selection strategy
if hasattr(self, 'point_strategy') and self.point_strategy is not None:
# Update the strategy with the last created mask
if mask is not None:
# Extract simple features for the created mask
area = np.sum(mask)
if area > 0:
y_indices, x_indices = np.where(mask)
centroid_y = np.mean(y_indices)
centroid_x = np.mean(x_indices)
# Create a simple feature vector
last_feature = np.array([area, centroid_y, centroid_x, 0.5])
# Start a new thread to get the next suggested point
# Convert user click from (x, y) to (y, x) format for the strategy
actual_click_yx = None
if self.last_actual_click:
x, y = self.last_actual_click
actual_click_yx = (y, x) # Convert (x, y) to (y, x)
self.point_thread = PointSuggestionThread(
self.point_strategy,
self.segmenter,
self.current_image,
expanded_masks=self.expanded_masks,
last_mask=mask,
last_feature=last_feature,
actual_last_point=actual_click_yx
)
self.point_thread.result_ready.connect(lambda next_point: self.on_next_point_ready(next_point))
self.point_thread.error_occurred.connect(lambda error: self.on_next_point_error(error))
self.point_thread.heatmap_ready.connect(lambda A_map, next_point: self.display_acquisition_heatmap_main_thread(A_map, next_point))
self.point_thread.start()
# Reset the actual click tracking after using it
self.last_actual_click = None
def on_next_point_ready(self, next_point):
"""Handle when the next suggested point is ready"""
if next_point:
self.suggested_point = next_point
else:
print("No valid next point proposed.")
self.suggested_point = None
# If the strategy stored an acquisition map, display it on the main thread for debugging
try:
if hasattr(self, 'point_strategy') and self.point_strategy is not None:
strat = self.point_strategy
A_map = getattr(strat, '_last_acquisition_map', None)
last_pt = getattr(strat, '_last_selected_point', None)
# if A_map is not None and hasattr(strat, 'display_acquisition_heatmap_main_thread'):
# try:
# strat.display_acquisition_heatmap_main_thread(A_map, next_point if next_point is not None else last_pt)
# except Exception:
# pass
except Exception:
pass
# Update the display with the new suggested point
self.update_display_with_current_state()
def on_next_point_error(self, error_msg):
"""Handle errors when getting next point"""
print(f"Error getting next point: {error_msg}")
# Fall back to center of image or keep current point
if not hasattr(self, 'suggested_point') or self.suggested_point is None:
if hasattr(self, 'current_image') and self.current_image is not None:
h, w = self.current_image.shape[:2]
self.suggested_point = (h // 2, w // 2)
else:
self.suggested_point = None
def toggle_masks_visibility(self):
"""Toggle the visibility of all masks"""
self.masks_visible = not self.masks_visible
# Update button appearance and mode
if self.masks_visible:
self.toggle_masks_button.setText("👁️❌")
# Return to creation mode when showing masks
self.current_mode = "creation"
else:
# When hiding masks, switch to visualization mode
self.toggle_masks_button.setText("👁️")
self.current_mode = "visualization"
self.is_over_mask = False
self.current_mask_index = None
self.setCursor(Qt.CursorShape.ArrowCursor)
# Update the display
if self.current_image is not None:
self.update_display_with_current_state()
def get_mask_at_position(self, pos):
"""Determine which mask (if any) is at the given position"""
if not self.expanded_masks or not self.masks_visible:
return None
x, y = pos
# Check each mask in reverse order (newest first)
for i in range(len(self.expanded_masks) - 1, -1, -1):
mask, _, _ = self.expanded_masks[i]
# Check if the position is within this mask
if 0 <= y < mask.shape[0] and 0 <= x < mask.shape[1] and mask[y, x]:
return i
return None
def check_point_overlap(self, point):
"""Check if a point overlaps with any existing mask and return mask info"""
if not self.expanded_masks:
return None
x, y = point
# Check each mask
for i, (mask, label, color) in enumerate(self.expanded_masks):
# Check if the point is within this mask
if 0 <= y < mask.shape[0] and 0 <= x < mask.shape[1] and mask[y, x]:
return {
'mask_index': i,
'mask': mask,
'label': label,
'color': color
}
return None
def handle_point_overlap(self, clicked_point, overlap_info):
"""Handle when user clicks on a point that overlaps with existing masks"""
overlapping_mask = overlap_info['mask']
overlapping_label = overlap_info['label']
# Show dialog to user
dialog = OverlapDialog(self.suggested_point, overlapping_label, self)
if dialog.exec() == QDialog.DialogCode.Accepted:
if dialog.result_choice == "same_object":
self.handle_same_object_merge(clicked_point, overlap_info)
elif dialog.result_choice == "different_object":
self.handle_different_object_overlap(clicked_point, overlap_info)
# If canceled, do nothing
def handle_same_object_merge(self, clicked_point, overlap_info):
"""Handle when user says the point belongs to the same object - union masks"""
# Add the point and create mask as normal
self.positive_points.append(clicked_point)
self.last_actual_click = clicked_point
# Generate the new mask
points = np.array(self.positive_points + self.negative_points)
labels = np.array([1] * len(self.positive_points) + [0] * len(self.negative_points))
new_mask = self.segmenter.propagate_points(points, labels, update_expanded_mask=False)
if new_mask is not None:
# Union with the existing mask
existing_mask = overlap_info['mask']
existing_label = overlap_info['label']
existing_color = overlap_info['color']
mask_index = overlap_info['mask_index']
# Create union of masks
union_mask = np.logical_or(existing_mask, new_mask).astype(np.uint8)
# Replace only the selected mask (mask_index) with the union, keep other masks of the same label
if 0 <= mask_index < len(self.expanded_masks):
self.expanded_masks[mask_index] = (union_mask, existing_label, existing_color)
else:
# Fallback: if index is invalid, just append
self.expanded_masks.append((union_mask, existing_label, existing_color))
# Regenerate combined overlay
self.regenerate_combined_mask_overlay()
print(f"Merged masks for label '{existing_label}'")
# Inform the point strategy about the updated expanded mask.
try:
if hasattr(self, 'point_strategy') and self.point_strategy is not None:
# Update expanded_masks in the strategy if present
if hasattr(self.point_strategy, 'expanded_masks'):
if len(self.point_strategy.expanded_masks) > mask_index:
self.point_strategy.expanded_masks[mask_index] = union_mask
else:
self.point_strategy.expanded_masks.append(union_mask)
except Exception:
pass
# Clear points and reset UI
self.positive_points = []
self.negative_points = []
self.finish_button.setEnabled(True)
self.switch_button.setEnabled(False)
if self.current_point_type == "negative":
self.switch_point_type()
# Start next point suggestion
self.start_next_point_suggestion(union_mask)
def handle_different_object_overlap(self, clicked_point, overlap_info):
"""Handle when user says it's a different object - resolve overlap"""
# Add the point and create mask as normal
self.positive_points.append(clicked_point)
self.last_actual_click = clicked_point
# Generate the new mask
points = np.array(self.positive_points + self.negative_points)
labels = np.array([1] * len(self.positive_points) + [0] * len(self.negative_points))
new_mask = self.segmenter.propagate_points(points, labels, update_expanded_mask=False)
if new_mask is not None:
# Get label for the new mask
dialog = LabelDialog(self.labels, self)
if dialog.exec() == QDialog.DialogCode.Accepted:
new_label = dialog.selected_label
if new_label is None:
new_label = dialog.new_label_edit.text()
if new_label and dialog.chosen_color:
self.labels[new_label] = dialog.chosen_color
new_color = self.labels.get(new_label)
if new_color:
# Use the merge_overlapping_masks function to resolve overlap
self.resolve_mask_overlap(new_mask, new_label, new_color, overlap_info)
def resolve_mask_overlap(self, new_mask, new_label, new_color, overlap_info):
"""Resolve overlapping masks by keeping non-overlapping parts and handling overlap properly"""