-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSLImTag.py
More file actions
2206 lines (1841 loc) · 100 KB
/
SLImTag.py
File metadata and controls
2206 lines (1841 loc) · 100 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
'''
SLImTAG: Simple Light-weight Image TAGging tool
SLImTAG is a simple and intuitive GUI tool for interactive image segmentation
integrating several tools such as brushes, connected component selection, and
magic wand selection (both classical and AI-based).
It supports multiple masks with color previews, undo history, and easy load
and save of masks.
v0.1 - 17 Apr 2026
Giulio Del Corso, Oscar Papini, Federico Volpini
'''
#%% Libraries
import os
import time
import shutil
# Numerical arrays manipulation
import numpy as np
from scipy.ndimage import binary_dilation, binary_erosion
from scipy.special import expit # sigmoid
# Image manipulation and TkIntert (ImageTk)
from PIL import Image, ImageDraw, ImageTk
# TkInter and CustomTkInter GUI
import tkinter as tk
from tkinter import filedialog
import customtkinter as ctk
# Custom utils
from slimtag_utils import MultiButtonDialog, MaskEditDialog, PreprocessingAdjustments, adjust_image
from slimtag_color_utils import rgb_to_hex, hex_to_rgb
# Torch and SAM (Segment anything model)
import torch
from segment_anything import sam_model_registry, SamPredictor
# Asynchronous threading import
import threading
# Suppress specific PyTorch warnings
import warnings
warnings.filterwarnings(
"ignore",
message="You are using `torch.load` with `weights_only=False`"
)
#%% User selected parameters
# TODO move these into configuration file
MAX_DISPLAY = 800 # Maximum display size for resizing images
UNDO_DEPTH = 10 # Maximum number of undo steps
MAX_ZOOM_PIXEL = 32 # minimum number of pixels of orig image visible at max zoom level
MIN_ZOOM_PIXEL = 6144 # maximum number of pixels of orig image visible at max zoom level
REFRESH_RATE_BRUSH = 0.05 # Refresh rate for the brush
PREVIEW_DIM = 250 # max dimension of preview canvas
# predefined high contrast colors for masks
MAX_MASKS = 20
HIGH_CONTRAST_COLORS = [
(158, 31, 99), (24, 105, 204), (150, 99, 177), (21, 194, 210),
(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255),
(0, 255, 255), (255, 128, 0), (128, 0, 255), (0, 255, 128),
(128, 255, 0), (255, 0, 128), (0, 128, 255), (128, 128, 0),
(128, 0, 0), (0, 128, 0), (0, 0, 128)
]
# OLD COLORS
#, (200, 200, 200), (255, 200, 200), (200, 255, 200), (200, 200, 255)
# TODO remove single button colors
# colors for different tool states
TOOL_OFF_COLOR = "#3A3A3A" # neutral grey when tool is off
BRUSH_ON_COLOR = "#4CAF50" # green
MAGIC_ON_COLOR = "#FF9800" # orange
CC_ON_COLOR = "#9C27B0" # purple
SMOOTH_ON_COLOR = "#2196F3" # blue
# colors for tools panel (light, dark)
# obtained from color above by overlaying the standard background with the color above at 15% alpha
TOOL_PANEL_COLOR = {
"brush": ("#C5D4C6", "#303F31"),
"wand": ("#E0D0BA", "#4B3B25"),
"ccomp": ("#D1BFD4", "#3C2A3F"),
"smooth": ("#BED0DE", "#293B49")
}
# as above, but with color at 5% alpha
TOOL_PANEL_SUBCOLOR = {
"brush": ("#D3D8D4", "#2C312D"),
"wand": ("#DDD7D0", "#363029"),
"ccomp": ("#D7D1D9", "#302A32"),
"smooth": ("#D2D8DD", "#2A3035")
}
# color at 10% alpha, if needed
# TOOL_PANEL_SUBCOLOR = {
# "brush": ("#CDD7CE", "#2E382F"),
# "wand": ("#DFD4C5", "#413627"),
# "ccomp": ("#D4C8D7", "#362A39"),
# "smooth": ("#C8D4DD", "#2A363F")
# }
STATUS_SYMBOL = "●"
STATUS_COLOR = {
"ready": ("#2ECC71", "#2ECC71"), # green
"loading":("#F1C40F", "#F1C40F"), # yellow
"error": ("#E74C3C", "#E74C3C"), # red
"idle": ("#95A5A6", "#95A5A6"), # gray
}
#%% SAM parameters
# TODO rework magic wand
# Choose the model type
MODEL_TYPE = "vit_b" # Lightweight
if MODEL_TYPE == "vit_b": # Lightweight
MODEL_WEIGHTS_PATH = "models/sam_vit_b_01ec64.pth"
elif MODEL_TYPE == "vit_l": # Standard
MODEL_WEIGHTS_PATH = "models/sam_vit_l_0b3195.pth"
elif MODEL_TYPE == "vit_h": # Advanced
MODEL_WEIGHTS_PATH = "models/sam_vit_h_4b8939.pth"
else:
raise Exception("Warning: select a correct model type.")
#%% CTK parameters
#ctk.set_appearance_mode("System") # System theme
#ctk.set_appearance_mode("dark") # force dark mode for testing
ctk.set_default_color_theme("color_palette.json") # CTK color theme
HIGHLIGHT_COLOR = ctk.ThemeManager.theme["CTkButton"]["border_color"]
#%% SLImTAG main class
class SegmentationApp(ctk.CTk):
def __init__(self):
super().__init__()
self.title("SLImTAG")
self.geometry("1300x900")
self.iconphoto(False, ImageTk.PhotoImage(file=os.path.join("images", "main_icon.png")))
# TODO move set_appearance_mode to preferences window
# optionsmenu "dark", "light" with default value: "dark"
self.appearance_mode = tk.StringVar(self, value="dark")
#%% Attributes
# Full image and mask
self.image_orig = None
self.mask_orig = None
# Displayed image and mask
self.image_disp = None
self.mask_disp = None
# current image preview (in sub canvas)
self.current_preview_canvas = None
self.preview_scale = 1.0
# Matrix of locked masks
self.mask_locked = None
# aux display variables
self.mask_pil = None
self.tk_ov = None
# to keep track of resizing window
self.resizing_event = None
# boolean switch to check if mask is modified and not saved
# TODO: for multiple images import
self.modified = False
# zoom & pan status
self.zoom = 1.0
self.zoom_max = 1.0
self.zoom_min = 1.0
self._pan_start = None
# labels for zoom and mouse position
self.pos_label_var = tk.StringVar(self, value="| x: 0 | y: 0 | z: 0 |")
self.zoom_label_var = tk.StringVar(self, value="Zoom: 100%")
# Original values for rescale
self.orig_h = None
self.orig_w = None
# Masks stuff
self.mask_labels = {}
self.mask_colors = {}
self.mask_widgets = {}
self.active_mask_id = None
self.mask_opacity = 150 # [0-255]
self.mask_outline = tk.BooleanVar(self, value=False) # use outlined masks instead of filled ones
# List images and index for folder segmentation
self.list_images = None
self.list_index = None
self.path_aux_save = None
self.path_original_image = None
self.images_num_label_var = tk.StringVar(self, value="Image 0 of 0")
# mouse position for events that need it
self.mouse = {'x': None, 'y': None}
# tools
self.tools = ["brush", "eraser", "polygon", "bbox", "cut", "clean", "bucket", "undo",
"smooth", "fill", "denoise", "interpolate",
"wand", "wand_all", "wand_multi", "wand_box",
"ruler", "area",
"custom_1", "custom_2", "custom_3", "custom_4"]
# tools buttons
self.tool_btn = {}
# tools status
self.tool_active = {tool: False for tool in self.tools}
# tools icons
self.tool_icon = {}
for tool in self.tools:
# TODO change wirh f"images/buttons/{tool}_light_on.png"
self.tool_icon[tool] = {"normal": ctk.CTkImage(light_image=Image.open(f"images/buttons/{tool}_light_on.png").convert("RGBA"),
dark_image=Image.open(f"images/buttons/{tool}_dark_on.png").convert("RGBA"),
size=(31, 31)),
"disabled": ctk.CTkImage(light_image=Image.open(f"images/buttons/{tool}_light_off.png").convert("RGBA"),
dark_image=Image.open(f"images/buttons/{tool}_dark_off.png").convert("RGBA"),
size=(31, 31))
}
# map tool -> corresponding options frame
self.tool_opt_map = {}
self.tool_opt_map.update(dict.fromkeys(["brush", "eraser"], "brush"))
self.tool_opt_map.update(dict.fromkeys(["wand", "wand_all", "wand_multi", "wand_box"], "wand"))
# TODO tool frame for each tool
self.tool_opt_map.update(dict.fromkeys(["polygon", "bbox", "cut", "clean", "bucket",
"smooth", "fill", "denoise", "interpolate",
"ruler", "area"], "empty"))
# TODO create custom empty frames, one for each custom button
self.tool_opt_map["custom_1"] = "empty"
self.tool_opt_map["custom_2"] = "empty"
self.tool_opt_map["custom_3"] = "empty"
self.tool_opt_map["custom_4"] = "empty"
# brush control
self.last_brush_pos = None
self.brush_shape = "Circle"
self.brush_size = 30
self.brush_rot = 0
# undo list
self.undo_stack = []
# Position top left of the view (in pixels of the original image)
# please note that these are NOT bounded to image size
self.view_x = None
self.view_y = None
# Corresponding view size (width, height; pixels of the original image)
self.view_w = None
self.view_h = None
# SAM management
self.sam_points = []
self.sam_pt_labels = []
# SAM preprocessing (for sliders: range -100 .. 100)
self.wand_brightness = 0
self.wand_contrast = 0
self.wand_gamma = 0
# Magic wand threshold (e.g. SAM model threshold), range 0.0 .. 1.0
self.wand_threshold = 0.5 # SAM has 0.5 as default value
# boolean to track if mouse buttons are pressed
self.b3_pressed = False
self.mid_pressed = False
# dictionary for icons
self.icons_dict = {}
for img in ["Eye", "Lock"]:
for st in ["Open", "Closed"]:
self.icons_dict[f"{img}{st}"] = {"normal": ctk.CTkImage(light_image=Image.open(f"images/icons/{img}{st}_light_on.png").convert("RGBA"),
dark_image=Image.open(f"images/icons/{img}{st}_dark_on.png").convert("RGBA"),
size=(16, 16)),
"disabled": ctk.CTkImage(light_image=Image.open(f"images/icons/{img}{st}_light_off.png").convert("RGBA"),
dark_image=Image.open(f"images/icons/{img}{st}_dark_off.png").convert("RGBA"),
size=(16, 16))
}
for img in ["NewMask", "ManualUpdate", "AutoUpdate"]:
self.icons_dict[f"{img}"] = {"normal": ctk.CTkImage(light_image=Image.open(f"images/icons/{img}_light_on.png").convert("RGBA"),
dark_image=Image.open(f"images/icons/{img}_dark_on.png").convert("RGBA"),
size=(16, 16)),
"disabled": ctk.CTkImage(light_image=Image.open(f"images/icons/{img}_light_off.png").convert("RGBA"),
dark_image=Image.open(f"images/icons/{img}_dark_off.png").convert("RGBA"),
size=(16, 16))
}
#%% Top Menu
self.menu_bar = tk.Menu(self)
self.set_menu_theme(self.menu_bar, self.appearance_mode.get())
self.config(menu=self.menu_bar)
self.topmenu_items = {}
# Menu File (top menu)
file_menu = tk.Menu(self.menu_bar, tearoff=0)
file_menu.add_command(label="Quit", command=self.quit_program, accelerator="Ctrl+Q")
self.topmenu_items["file"] = file_menu
self.menu_bar.add_cascade(label="File", menu=file_menu)
# Menu Edit (top menu)
edit_menu = tk.Menu(self.menu_bar, tearoff=0)
edit_menu.add_command(label="Undo", command=self.undo, accelerator="Ctrl+Z")
# TODO implement preferences window
edit_menu.add_command(label="Preferences...", command=None)
self.topmenu_items["edit"] = edit_menu
self.menu_bar.add_cascade(label="Edit", menu=edit_menu)
# Menu View (top menu)
view_menu = tk.Menu(self.menu_bar, tearoff=0)
view_menu.add_command(label="Zoom in", command=self.zoom_in, accelerator="Ctrl++")
view_menu.add_command(label="Zoom out", command=self.zoom_out, accelerator="Ctrl+-")
view_menu.add_command(label="Reset zoom", command=self.reset_zoom, accelerator="Ctrl+0")
self.topmenu_items["view"] = view_menu
self.menu_bar.add_cascade(label="View", menu=view_menu)
# Menu Image (top menu)
image_menu = tk.Menu(self.menu_bar, tearoff=0)
image_menu.add_command(label="Import image", command=self.load_image, accelerator="Ctrl+I")
#image_menu.add_command(label="Import folder", command=self.load_folder, accelerator="Ctrl+F")
# TODO reactivate import folder
self.topmenu_items["image"] = image_menu
self.menu_bar.add_cascade(label="Image", menu=image_menu)
# Menu Mask (top menu)
mask_menu = tk.Menu(self.menu_bar, tearoff=0)
mask_menu.add_command(label="Load mask", command=self.load_mask)
mask_menu.add_command(label="Save mask", command=lambda s=True: self.save_mask(switch_fast=s), accelerator="Ctrl+S")
mask_menu.add_command(label="Save mask as...", command=lambda s=False: self.save_mask(switch_fast=s))
mask_menu.add_separator()
mask_menu.add_command(label="Clear active mask", command=self.clear_active_mask)
mask_menu.add_command(label="Clear all masks", command=self.clear_all_masks)
self.topmenu_items["mask"] = mask_menu
self.menu_bar.add_cascade(label="Mask", menu=mask_menu)
# Menu Magic Wand (top menu)
# TODO implement load/save configuration
wand_menu = tk.Menu(self.menu_bar, tearoff=0)
wand_menu.add_command(label="Load configuration", command=None)
wand_menu.add_command(label="Save configuration", command=None)
self.topmenu_items["wand"] = wand_menu
self.menu_bar.add_cascade(label="Magic wand", menu=wand_menu)
# Menu Help (top menu)
# TODO implement help functions
help_menu = tk.Menu(self.menu_bar, tearoff=0)
help_menu.add_command(label="Documentation", command=None)
help_menu.add_command(label="About", command=None)
self.topmenu_items["help"] = help_menu
self.menu_bar.add_cascade(label="Help", menu=help_menu)
#%% Main UI elements
panels_width = 250
# Left panel for tools
self.left_panel = ctk.CTkFrame(self, width=panels_width)
self.left_panel.grid(row=0, column=0, sticky="nsew")
self.left_panel.grid_rowconfigure(5, weight=1)
# Main canvas
# TODO different frames with different widgets depending on load type
# e.g. previous/next image for folder, slider with z-axis for medical...
self.canvas = ctk.CTkCanvas(self, bg="black", highlightthickness=0)
self.canvas.grid(row=0, column=1, sticky="nsew")
# Right panel for masks
self.right_panel = ctk.CTkFrame(self, width=panels_width)
self.right_panel.grid(row=0, column=2, sticky="nsew")
self.right_panel.grid_rowconfigure(1, weight=1)
self.right_panel.grid_rowconfigure(2, weight=2)
# Statusbar
self.statusbar = ctk.CTkFrame(self, height=32, fg_color=("gray92", "gray14"))
self.statusbar.grid(row=1, column=0, columnspan=3, sticky="nsew", padx=0, pady=0)
self.statusbar.grid_columnconfigure(3, weight=1)
# Grid configuration for main window
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(1, weight=1)
#%% Left panel: Tools
# Frames for buttons
self.tools_btn_frame = {i: ctk.CTkFrame(self.left_panel, corner_radius=0) for i in range(5)}
frame_paddings = [(0, 5)] + 3*[5] + [(5, 0)]
for i in range(5):
self.tools_btn_frame[i].grid(row=i, column=0, sticky="nsew", padx=0, pady=frame_paddings[i])
# Buttons
# TODO all commands, in particular add the "right-click" that are a different tool now
# I ould keep the right-click behaviour in any case (for "pro users")
self.create_tool_button("brush", 0, 0, 0)
self.create_tool_button("eraser", 0, 0, 1)
self.create_tool_button("polygon", 0, 1, 0)
self.create_tool_button("bbox", 0, 1, 1)
self.create_tool_button("cut", 0, 2, 0)
self.create_tool_button("clean", 0, 2, 1)
self.create_tool_button("bucket", 0, 3, 0, last_row=True)
self.create_tool_button("undo", 0, 3, 1, command=self.undo, last_row=True)
self.create_tool_button("smooth", 1, 0, 0)
self.create_tool_button("fill", 1, 0, 1)
self.create_tool_button("denoise", 1, 1, 0, last_row=True)
self.create_tool_button("interpolate", 1, 1, 1, last_row=True)
self.create_tool_button("wand", 2, 0, 0)
self.create_tool_button("wand_all", 2, 0, 1)
self.create_tool_button("wand_multi", 2, 1, 0, None, last_row=True)
self.create_tool_button("wand_box", 2, 1, 1, None, last_row=True)
self.create_tool_button("ruler", 3, 0, 0, None, last_row=True)
self.create_tool_button("area", 3, 0, 1, None,last_row=True)
self.create_tool_button("custom_1", 4, 0, 0, None)
self.create_tool_button("custom_2", 4, 0, 1, None)
self.create_tool_button("custom_3", 4, 1, 0, None, last_row=True)
self.create_tool_button("custom_4", 4, 1, 1, None, last_row=True)
#%% Right panel: Masks
# Global masks buttons
self.mask_controls_frame = ctk.CTkFrame(self.right_panel, fg_color="transparent")
self.mask_controls_frame.grid(row=0, column=0, sticky="nsew", padx=0, pady=0)
self.mask_controls_frame.grid_columnconfigure(1, weight=1)
self.new_mask_btn = ctk.CTkButton(self.mask_controls_frame, text="New mask",
image=self.icons_dict["NewMask"]["normal"],
width=0, height=34,
anchor="w",
fg_color="transparent",
command=self.add_mask)
self.new_mask_btn.grid(row=0, column=0, sticky="w", padx=(10, 5), pady=5)
self.hide_all_mask_btn = ctk.CTkButton(self.mask_controls_frame, text="",
image=self.icons_dict["EyeOpen"]["disabled"],
width=34, height=34,
fg_color="transparent",
state="disabled",
command=lambda: self.toggle_all_masks_hide(not self.hide_all_mask_btn.hidden))
self.hide_all_mask_btn.grid(row=0, column=2, sticky="ew", padx=(5, 2), pady=5)
self.hide_all_mask_btn.hidden = False
self.lock_all_mask_btn = ctk.CTkButton(self.mask_controls_frame, text="",
image=self.icons_dict["LockOpen"]["disabled"],
width=34, height=34,
fg_color="transparent",
state="disabled",
command=lambda: self.toggle_all_masks_lock(not self.lock_all_mask_btn.locked))
self.lock_all_mask_btn.grid(row=0, column=3, sticky="ew", padx=2, pady=5)
self.lock_all_mask_btn.locked = False
self.clear_all_mask_btn = ctk.CTkButton(self.mask_controls_frame, text="×",
font=ctk.CTkFont(size=24, weight="bold"),
width=34, height=34,
fg_color="transparent",
text_color="#AB2B22",
command=self.clear_all_masks)
self.clear_all_mask_btn.bind("<Enter>", lambda e: self.clear_all_mask_btn.configure(fg_color="#AB2B22", text_color="white"))
self.clear_all_mask_btn.bind("<Leave>", lambda e: self.clear_all_mask_btn.configure(fg_color="transparent", text_color="#AB2B22"))
self.clear_all_mask_btn.grid(row=0, column=4, sticky="ew", padx=(2, 23), pady=5)
# ScrollFrame for mask list
self.mask_list_frame = ctk.CTkScrollableFrame(self.right_panel, corner_radius=0, height=100)
self.mask_list_frame.grid(row=1, column=0, sticky="nsew", padx=0, pady=(0, 5))
self.mask_list_frame._scrollbar.configure(height=0) # https://stackoverflow.com/a/76957827
#%% Right panel: Tools options
# Frame for tool options
self.tool_opt_container = ctk.CTkScrollableFrame(self.right_panel, corner_radius=0)
self.tool_opt_container.grid(row=2, column=0, sticky="nsew", padx=0, pady=5)
self.tool_opt_container.grid_columnconfigure(0, weight=1)
self.tool_opt_frame = {}
empty_frame = ctk.CTkFrame(self.tool_opt_container, fg_color="transparent")
empty_frame.grid(row=0, column=0, sticky="nsew", padx=0, pady=0)# pady=5
self.tool_opt_frame["empty"] = empty_frame
brush_frame = ctk.CTkFrame(self.tool_opt_container, fg_color="transparent")
brush_frame.grid(row=0, column=0, sticky="nsew", padx=0, pady=0)
self.tool_opt_frame["brush"] = brush_frame
wand_frame = ctk.CTkFrame(self.tool_opt_container, fg_color="transparent")
wand_frame.grid(row=0, column=0, sticky="nsew", padx=0, pady=0)
self.tool_opt_frame["wand"] = wand_frame
ccomp_frame = ctk.CTkFrame(self.tool_opt_container, fg_color="transparent")
ccomp_frame.grid(row=0, column=0, sticky="nsew", padx=0, pady=0)
self.tool_opt_frame["ccomp"] = ccomp_frame
smooth_frame = ctk.CTkFrame(self.tool_opt_container, fg_color="transparent")
smooth_frame.grid(row=0, column=0, sticky="nsew", padx=0, pady=0)
self.tool_opt_frame["smooth"] = smooth_frame
for tool in self.tool_opt_frame:
self.tool_opt_frame[tool].grid_columnconfigure(0, weight=1)
# set empty frame at start
self.current_tool_frame = None
self.show_tool_frame("empty")
# Brush options
ctk.CTkLabel(self.tool_opt_frame["brush"], text="Brush settings:", fg_color="transparent", font=ctk.CTkFont(size=17, weight='bold'), anchor="w").grid(row=0, column=0, columnspan=2, sticky="ew", padx=10, pady=(10, 0))
ctk.CTkLabel(self.tool_opt_frame["brush"], text="Shape", fg_color="transparent", anchor="w").grid(row=1, column=0, sticky="ew", padx=10, pady=(10, 2))
self.brush_shape_btn = ctk.CTkSegmentedButton(self.tool_opt_frame["brush"], values=["Circle", "Square", "Line"], command=None)
self.brush_shape_btn.set("Circle") # TODO implement shape
self.brush_shape_btn.grid(row=2, column=0, columnspan=2, sticky="ew", padx=10, pady=0)
self.brush_shape_btn.configure(state="disabled") # TODO remove when implemented
ctk.CTkLabel(self.tool_opt_frame["brush"], text="Size", fg_color="transparent", anchor="w").grid(row=3, column=0, sticky="ew", padx=(10, 5), pady=(10, 2)) #font=ctk.CTkFont(size=11),
self.brush_size_lbl = ctk.CTkLabel(self.tool_opt_frame["brush"], text=str(self.brush_size), fg_color="transparent", anchor="e")
self.brush_size_lbl.grid(row=3, column=1, sticky="ew", padx=(5, 10), pady=(10, 2))
self.brush_size_slider = ctk.CTkSlider(self.tool_opt_frame["brush"], from_=5, to=100,
command=lambda v: (setattr(self,"brush_size",int(v)), self.brush_size_lbl.configure(text=str(self.brush_size))))
self.brush_size_slider.set(self.brush_size)
self.brush_size_slider.grid(row=4, column=0, columnspan=2, sticky="ew", padx=10, pady=0)
ctk.CTkLabel(self.tool_opt_frame["brush"], text="Rotation", fg_color="transparent", anchor="w").grid(row=5, column=0, sticky="ew", padx=(10, 5), pady=(10, 2))
self.brush_rot_lbl = ctk.CTkLabel(self.tool_opt_frame["brush"], text=f"{self.brush_rot}°", fg_color="transparent", anchor="e")
self.brush_rot_lbl.grid(row=5, column=1, sticky="ew", padx=(5, 10), pady=(10, 2))
self.brush_rot_slider = ctk.CTkSlider(self.tool_opt_frame["brush"], from_=0, to=180,
command=lambda v: (setattr(self,"brush_rot",int(v)), self.brush_rot_lbl.configure(text=f"{self.brush_rot}°")))
self.brush_rot_slider.set(self.brush_rot) # TODO implement rotation
self.brush_rot_slider.grid(row=6, column=0, columnspan=2, sticky="ew", padx=10, pady=(0, 10))
self.brush_rot_slider.configure(state="disabled") # TODO remove when implemented
# Magic wand options
ctk.CTkLabel(self.tool_opt_frame["wand"], text="Magic wand settings:", fg_color="transparent", font=ctk.CTkFont(size=17, weight='bold'), anchor="w").grid(row=0, column=0, columnspan=2, sticky="ew", padx=10, pady=(10, 0))
self.wand_model_menu = ctk.CTkOptionMenu(self.tool_opt_frame["wand"], values=["SAM (ViT-B)"], command=None) # TODO
self.wand_model_menu.set("SAM (ViT-B)")
self.wand_model_menu.grid(row=1, column=0, columnspan=2, sticky="ew", padx=10, pady=(10, 0))
self.wand_adj_frame = ctk.CTkFrame(self.tool_opt_frame["wand"], border_width=1)
self.wand_adj_frame.grid(row=2, column=0, columnspan=2, sticky="nsew", padx=10, pady=(10, 0))
ctk.CTkLabel(self.wand_adj_frame, text="Preprocessing", fg_color="transparent", font=ctk.CTkFont(weight='bold')).grid(row=0, column=0, columnspan=2, sticky="ew", padx=10, pady=(3,0))
ctk.CTkLabel(self.wand_adj_frame, text="Brightness", fg_color="transparent", anchor="w").grid(row=1, column=0, sticky="ew", padx=(10,0), pady=(3,0))
self.wand_brightness_lbl = ctk.CTkLabel(self.wand_adj_frame, text=str(self.wand_brightness), fg_color="transparent", anchor="e")
self.wand_brightness_lbl.grid(row=1, column=1, sticky="ew", padx=(0,10), pady=(3,0))
ctk.CTkLabel(self.wand_adj_frame, text="Contrast", fg_color="transparent", anchor="w").grid(row=2, column=0, sticky="ew", padx=(10,0), pady=(3,0))
self.wand_contrast_lbl = ctk.CTkLabel(self.wand_adj_frame, text=str(self.wand_contrast), fg_color="transparent", anchor="e")
self.wand_contrast_lbl.grid(row=2, column=1, sticky="ew", padx=(0,10), pady=(3,0))
ctk.CTkLabel(self.wand_adj_frame, text="Shadows", fg_color="transparent", anchor="w").grid(row=3, column=0, sticky="ew", padx=(10,0), pady=(3,0))
self.wand_gamma_lbl = ctk.CTkLabel(self.wand_adj_frame, text=str(self.wand_gamma), fg_color="transparent", anchor="e")
self.wand_gamma_lbl.grid(row=3, column=1, sticky="ew", padx=(0,10), pady=(3,0))
self.wand_auto_update = ctk.CTkButton(self.wand_adj_frame, text="Auto", image=self.icons_dict["AutoUpdate"]["disabled"], command=None)
self.wand_auto_update.grid(row=4, column=1, sticky="ew", padx=(5, 10), pady=(3,10))
self.wand_auto_update.configure(state='disabled') # TODO implement auto update
self.wand_manual_update = ctk.CTkButton(self.wand_adj_frame, text="Manual", image=self.icons_dict["ManualUpdate"]["disabled"], command=self.manual_wand_preprocessing)
self.wand_manual_update.grid(row=4, column=0, sticky="ew", padx=(10, 5), pady=(3,10))
self.wand_adj_frame.grid_columnconfigure([0, 1], weight=1)
ctk.CTkLabel(self.tool_opt_frame["wand"], text="Wand threshold", fg_color="transparent", anchor="w").grid(row=3, column=0, sticky="ew", padx=(10, 5), pady=(10, 2))
self.wand_threshold_lbl = ctk.CTkLabel(self.tool_opt_frame["wand"], text=f"{self.wand_threshold:.2f}", fg_color="transparent", anchor="e")
self.wand_threshold_lbl.grid(row=3, column=1, sticky="ew", padx=(5, 10), pady=(10, 2))
self.wand_threshold_slider = ctk.CTkSlider(self.tool_opt_frame["wand"], from_=0.0, to=1.0,
command=lambda v: (setattr(self,"wand_threshold",float(v)), self.wand_threshold_lbl.configure(text=f"{self.wand_threshold:.2f}")))
self.wand_threshold_slider.set(self.wand_threshold) # TODO
self.wand_threshold_slider.grid(row=4, column=0, columnspan=2, sticky="ew", padx=10, pady=(0, 10))
#%% Right panel: Navigation
self.navigation_frame = ctk.CTkFrame(self.right_panel, fg_color="transparent")
self.navigation_frame.grid(row=3, column=0, sticky="n", padx=10, pady=(5, 10))
self.sub_canvas_frames = {}
image_only_frame = ctk.CTkFrame(self.navigation_frame)#, fg_color="transparent")
image_only_frame.canvas = ctk.CTkCanvas(image_only_frame, bg="black", highlightthickness=0, width=PREVIEW_DIM, height=PREVIEW_DIM)
image_only_frame.canvas.grid(row=0, column=0, sticky="sew", padx=5, pady=5)
image_only_frame.grid_rowconfigure(0, weight=1)
image_only_frame.grid_columnconfigure(0, weight=1)
self.sub_canvas_frames["image"] = image_only_frame
ortho_views_frame = ctk.CTkFrame(self.navigation_frame)#, fg_color="transparent")
ortho_views_frame.view1 = ctk.CTkCanvas(ortho_views_frame, bg="black", highlightthickness=0, width=PREVIEW_DIM, height=PREVIEW_DIM)
ortho_views_frame.view1.grid(row=0, column=0, sticky="sew", padx=5, pady=5)
ortho_views_frame.view2 = ctk.CTkCanvas(ortho_views_frame, bg="black", highlightthickness=0, width=PREVIEW_DIM, height=PREVIEW_DIM)
ortho_views_frame.view2.grid(row=1, column=0, sticky="sew", padx=5, pady=5)
ortho_views_frame.grid_columnconfigure(0, weight=1)
self.sub_canvas_frames["ortho"] = ortho_views_frame
# TODO bind mouse click on minimap to pan?
self.show_preview_frame("image") # default behaviour
#%% Statusbar
# Status
self.status_icon = ctk.CTkLabel(self.statusbar, text=STATUS_SYMBOL, text_color=STATUS_COLOR["idle"], width=14)
self.status_icon.grid(row=0, column=0, sticky="w", padx=(10, 0), pady=(0, 2))
self.status_label = ctk.CTkLabel(self.statusbar, text="Initializing...")
self.status_label.grid(row=0, column=1, sticky="w", padx=(4, 0))
self.status_sam_label = ctk.CTkLabel(self.statusbar, text="") # for SAM asynchronous loading
self.status_sam_label.grid(row=0, column=2, sticky="w", padx=(4, 0))
# Mask appearance controls
self.mask_appearance_frame = ctk.CTkFrame(self.statusbar, fg_color="transparent")
self.mask_appearance_frame.grid(row=0, column=4, sticky="ew", padx=0)
ctk.CTkLabel(self.mask_appearance_frame, text="Mask opacity", anchor="e").grid(row=0, column=0, sticky="ew", padx=10)
self.mask_opacity_slider = ctk.CTkSlider(self.mask_appearance_frame, from_=0, to=255, command=lambda v: self.update_mask_opacity(int(v)))
self.mask_opacity_slider.set(self.mask_opacity)
self.mask_opacity_slider.grid(row=0, column=1, sticky="ew", padx=(0, 10))
ctk.CTkLabel(self.mask_appearance_frame, text="Fill", anchor="e").grid(row=0, column=2, sticky="ew", padx=(0, 10))
self.mask_outline_switch = ctk.CTkSwitch(self.mask_appearance_frame, text="Outline", variable=self.mask_outline,
command=lambda: self.update_display(update_all="Mask"))
self.mask_outline_switch.grid(row=0, column=3, sticky="ew", padx=(0, 10))
self.mask_outline_switch.configure(state="disabled") # TODO remove when implemented
# Position label
self.pos_label = ctk.CTkLabel(self.statusbar, textvariable=self.pos_label_var, anchor="e", width=200)
self.pos_label.grid(row=0, column=5, sticky="e", padx=10)
# Zoom label
self.zoom_label = ctk.CTkLabel(self.statusbar, textvariable=self.zoom_label_var)
self.zoom_label.grid(row=0, column=6, sticky="e", padx=10)
#%% SAM
device = "cuda" if torch.cuda.is_available() else "cpu"
sam = sam_model_registry[MODEL_TYPE](checkpoint=MODEL_WEIGHTS_PATH)
sam.to(device).eval()
self.sam = SamPredictor(sam)
# Define the asynchronous mechanism to speed up image loading
self.switch_computed_magic_wand = False # True if SAM is loaded
self.thread = None # Threading variable
self.lock = threading.Lock() # To protect shared varaibles
self.set_controls_state(False) # Deactivate all buttons -- must be done after defining switch_computed_magic_wand
#%% Bindings
self.canvas.bind("<MouseWheel>", self.zoom_evt)
self.canvas.bind("<Button-4>", self.zoom_in) # <Button-4> is scroll up for Linux
self.canvas.bind("<Button-5>", self.zoom_out) # <Button-5> is scroll down for Linux
self.canvas.bind("<Motion>", self.draw_brush_preview, add="+")
self.canvas.bind("<Motion>", self.on_canvas_track, add="+")
self.canvas.bind("<Button-1>", self.on_canvas_left)
self.canvas.bind("<Button-2>", self.on_canvas_mid)
self.canvas.bind("<Button-3>", self.on_canvas_right)
self.canvas.bind("<B1-Motion>", self.on_canvas_drag)
self.canvas.bind("<B2-Motion>", self.on_canvas_drag)
self.canvas.bind("<B3-Motion>", self.on_canvas_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_canvas_left_release)
self.canvas.bind("<ButtonRelease-2>", self.on_canvas_mid_release)
self.canvas.bind("<ButtonRelease-3>", self.on_canvas_right_release)
# Zoom via keyboard (Ctrl + / Ctrl -)
self.bind("<Control-plus>", lambda e: self.zoom_in())
self.bind("<Control-0>", self.reset_zoom)
self.bind("<Control-KP_0>", self.reset_zoom) # also keypad for madmen like Oscar :)
self.bind("<Control-space>", self.reset_zoom)
self.bind("<Control-minus>", lambda e: self.zoom_out())
# Move view:
self.bind("<Up>", lambda e: self.pan_view(0, -20))
self.bind("<Down>", lambda e: self.pan_view(0, 20))
self.bind("<Left>", lambda e: self.pan_view(-20, 0))
self.bind("<Right>", lambda e: self.pan_view(20, 0))
# Bind "close window" to quit_program
self.protocol("WM_DELETE_WINDOW", self.quit_program)
# Bind "resizing window"
self.bind("<Configure>", self.on_resize)
# Fire SAM at Ctrl release
self.bind("<KeyRelease-Control_L>", lambda e: self.sam_apply_release())
self.bind("<KeyRelease-Control_R>", lambda e: self.sam_apply_release())
# Shortcuts
self.bind("<b>", lambda e: self.toggle_tool("brush"))
self.bind("<B>", lambda e: self.toggle_tool("brush"))
self.bind("<m>", lambda e: self.toggle_tool("wand"))
self.bind("<M>", lambda e: self.toggle_tool("wand"))
self.bind("<c>", lambda e: self.toggle_tool("cut"))
self.bind("<C>", lambda e: self.toggle_tool("cut"))
self.bind("<s>", lambda e: self.toggle_tool("smooth"))
self.bind("<S>", lambda e: self.toggle_tool("smooth"))
self.bind("<n>", lambda e: self.add_mask())
self.bind("<N>", lambda e: self.add_mask())
self.bind("<Control-z>", lambda e: self.undo())
self.bind("<Control-Z>", lambda e: self.undo())
self.bind("<Control-I>", lambda e: self.load_image())
self.bind("<Control-i>", lambda e: self.load_image())
#self.bind("<Control-F>", lambda e: self.load_folder()) # TODO reactivate load folder
#self.bind("<Control-f>", lambda e: self.load_folder())
self.bind("<Control-S>", lambda e: self.save_mask(switch_fast=True))
self.bind("<Control-s>", lambda e: self.save_mask(switch_fast=True))
self.bind("<Control-q>", lambda e: self.quit_program())
self.bind("<Control-Q>", lambda e: self.quit_program())
self.bind("<q>", lambda e: self.quit_program())
self.bind("<Q>", lambda e: self.quit_program())
self.bind("<Tab>", lambda e: self.tab())
self.bind("<Shift-Tab>", lambda e: self.shiftTab())
self.bind("<ISO_Left_Tab>", lambda e: self.shiftTab()) # for linux
self.bind("<KeyPress-Shift_L>", lambda e: self.shiftPressed())
self.bind("<KeyPress-Shift_R>", lambda e: self.shiftPressed())
self.bind("<KeyRelease-Shift_L>", lambda e: self.shiftReleased())
self.bind("<KeyRelease-Shift_R>", lambda e: self.shiftReleased())
# Next image
self.bind("<KeyPress-period>", lambda e: self.next_image())
# TODO when folder navigation will be implemented, uncomment this
#self.bind("<KeyPress-comma>", lambda e: self.prev_image())
#%% Clean-up at the end of __init__
# set appearance mode
self.toggle_appearance()
# Finally, set status to "Ready"
self.set_status("ready", "Ready")
#%% TODO old code to be repurposed, DO NOT REMOVE UNTIL IMPLEMENTED BACK
# Images in folder navigation frame
# TODO move in main_canvas frame
# self.images_in_folder_frame = ctk.CTkFrame(self.right_panel)
# self.images_in_folder_frame.grid(row=3, column=0, sticky="nsew", padx=10, pady=5)
# self.images_in_folder_label = ctk.CTkLabel(self.images_in_folder_frame, textvariable=self.images_num_label_var)
# self.images_in_folder_label.grid(row=0, column=0, columnspan=2, sticky="ew", padx=10, pady=(10, 5))
# self.prev_image_btn = ctk.CTkButton(self.images_in_folder_frame, text="Previous image [,]", command=self.prev_image)
# self.prev_image_btn.grid(row=1, column=0, sticky="ew", padx=(10, 5), pady=(5, 10))
# self.prev_image_btn.configure(state="disabled")
# self.next_image_btn = ctk.CTkButton(self.images_in_folder_frame, text="Next image [.]", command=self.next_image)
# self.next_image_btn.grid(row=1, column=1, sticky="ew", padx=(5, 10), pady=(5, 10))
# self.next_image_btn.configure(state="disabled")
# self.images_in_folder_frame.grid_columnconfigure([0, 1], weight=1)
#%% AUX methods
# Async method for efficient SAM loading
def async_loader(self):
#print("Loading SAM model")
self.status_sam_label.configure(text="(Loading image into SAM...)")
# Thread-safe upload of shared variable
with self.lock:
self.switch_computed_magic_wand = False
if len(self.mask_labels) == 0 or self.active_mask_id is None: # disable all buttons if there are no masks
self.set_controls_state(False)
else:
self.set_controls_state(True)
# SAM model inference on image
image = adjust_image(np.array(self.image_orig), self.wand_brightness, self.wand_contrast, self.wand_gamma)
self.sam.set_image(image)
# Turn on switch
self.switch_computed_magic_wand = True
#print("Loaded SAM model")
if len(self.mask_labels) == 0 or self.active_mask_id is None: # disable all buttons if there are no masks
self.set_controls_state(False)
else:
self.set_controls_state(True)
self.status_sam_label.configure(text="")
if self.list_images != None:
self.next_image_btn.configure(state="normal")
# Refresh and update display
self.update_display()
def quit_program(self):
"""
Quit program.
"""
if self.modified:
if self.list_images != None:
# in folder mode, bypass check and always save changes on the current mask
self.save_mask(switch_fast=True)
self.quit()
self.destroy()
else:
confirm = MultiButtonDialog(self, message="There are unsaved changes. What do you want to do?",
buttons=(("Save & Quit", "save"), ("Discard & Quit", "discard"), ("Cancel", None))
)
answer = confirm.return_value
if answer == "save":
self.save_mask()
self.quit()
self.destroy()
elif answer == "discard":
self.quit()
self.destroy()
else:
return
else:
self.quit()
self.destroy()
#%% STATUS METHODS
# update window title
def update_title(self):
title_string = f"{'*' if self.modified else ''}SLImTAG{f' [{os.path.basename(self.path_original_image)}]' if self.path_original_image is not None else ''}"
self.title(title_string)
def image_is_loaded(self):
'''
Warning message if no image has been loaded.
In that case, user can load image from warning dialog
'''
if self.image_orig is None:
warn = MultiButtonDialog(self, message="WARNING: No image loaded",
buttons=[("Import image...", "import"), ("Cancel", None)])
action = warn.return_value
if action == "import":
self.load_image(add_mask=False)
else:
return False
return True
def set_status(self, state, text):
"""
Set icon color and text for status bar.
"""
try:
self.status_icon.configure(text_color=STATUS_COLOR[state])
except KeyError:
self.status_icon.configure(text_color=STATUS_COLOR["idle"])
self.status_label.configure(text=text)
self.update_idletasks()
def set_modified(self, state):
"""
Check if self.modified is different than state, and in that case update
"""
if self.modified != state:
if state == True:
self.modified = True
else: # state == False
self.modified = False
self.update_title()
#%% APPEARANCE (DARK/LIGHT)
def toggle_appearance(self):
ctk.set_appearance_mode(self.appearance_mode.get())
self.set_menu_theme(self.menu_bar, self.appearance_mode.get())
for menu in self.topmenu_items:
self.set_menu_theme(self.topmenu_items[menu], self.appearance_mode.get())
if hasattr(self, 'active_context_menu'):
self.set_menu_theme(self.active_context_menu, self.appearance_mode.get())
def set_menu_theme(self, menu, mode):
if mode.lower() == 'dark':
menu.configure(bd=0, background="#242424", fg="#999999", activebackground="#242424", activeforeground="white", activeborderwidth=0)
else:
menu.configure(bd=0, background="#d9d9d9", fg="#000000", activebackground="#d9d9d9", activeforeground="#242424", activeborderwidth=0)
#%% NAVIGATION PANEL
def show_preview_frame(self, preview):
for nav in self.sub_canvas_frames:
self.sub_canvas_frames[nav].grid_forget()
# TODO implement for ortho
# if hasattr(self.sub_canvas_frames[preview], "view1") ...
if self.image_orig is not None:
scale = max(self.orig_w, self.orig_h) / PREVIEW_DIM
self.preview_scale = scale
self.sub_canvas_frames["image"].canvas.configure(width=int(self.orig_w / scale), height=int(self.orig_h / scale))
self.sub_canvas_image = ImageTk.PhotoImage(self.image_orig.resize((int(self.orig_w / scale), int(self.orig_h / scale)), Image.Resampling.LANCZOS))
self.sub_canvas_frames["image"].canvas.create_image(0, 0, anchor="nw", image=self.sub_canvas_image, tag="image")
self.current_preview_canvas = self.sub_canvas_frames["image"].canvas
self.sub_canvas_frames[preview].grid(row=0, column=0, sticky="nsew", padx=0, pady=0)
self.sub_canvas_frames[preview].tkraise()
def update_preview_frame(self):
self.current_preview_canvas.delete("rectangle")
x = int(self.view_x / self.preview_scale)
y = int(self.view_y / self.preview_scale)
w = int(self.view_w / self.preview_scale)
h = int(self.view_h / self.preview_scale)
self.current_preview_canvas.create_rectangle(x, y, x+w, y+h, outline=HIGHLIGHT_COLOR, width=2, tag="rectangle")
#%% UPDATE DISPLAY
def update_display(self, update_all="Global"):
'''
Aux method to update display whenever a change occurs.
Valid argument for update_all:
- "Global" updates both the background image and the mask overlay
- "Mask" updates only the mask overlay
'''
if self.image_orig is None:
return
self.zoom_label_var.set(f"Zoom: {round(100*self.zoom)}%")
if update_all == "Global":
# remove old info
self.canvas.delete("background_image","mask")
# create new image view and paste it on canvas
self.image_disp = self.image_orig.crop([self.view_x, self.view_y, self.view_x+self.view_w, self.view_y+self.view_h]) \
.resize((self.canvas.winfo_width(), self.canvas.winfo_height()), Image.NEAREST)
self.tk_img = ImageTk.PhotoImage(self.image_disp)
self.canvas.create_image(0, 0, anchor="nw", image=self.tk_img, tag="background_image")
elif update_all == "Mask":
# delete only the mask to speed up computations
self.canvas.delete("mask")
# compute new mask view margins
top = max(0, self.view_y)
bottom = min(max(self.view_y+self.view_h, 0), self.orig_h)
left = max(0,self.view_x)
right = min(max(self.view_x+self.view_w,0), self.orig_w)
# create new mask view and populate
cut_mask_orig = np.zeros((self.view_h, self.view_w), dtype=self.mask_orig.dtype)
try:
cut_mask_orig[top-self.view_y:bottom-self.view_y, left-self.view_x:right-self.view_x] = self.mask_orig[top:bottom, left:right]
except ValueError: # in case we are out of image limits, in this case keep empty mask
pass
# TODO: if self.mask_outline.get(): change overlay as border only
# else: do as below
# create overlay object and convert it to be pasted on canvas
overlay = np.zeros((self.view_h, self.view_w, 4), np.uint8)
for mid, c in self.mask_colors.items():
if not self.mask_widgets[mid].hidden:
overlay[cut_mask_orig==mid] = [*c, self.mask_opacity]
self.mask_pil = Image.fromarray(overlay)
resized = self.mask_pil.resize((self.canvas.winfo_width(), self.canvas.winfo_height()), Image.NEAREST)
self.tk_ov = ImageTk.PhotoImage(resized)
self.canvas.create_image(0, 0, anchor="nw", image=self.tk_ov, tag="mask")
# raise back SAM multipoints if any
self.canvas.tag_raise("sam_pt")
def update_mask_opacity(self, v):
self.mask_opacity = v
self.update_display(update_all="Mask")
def update_display_after_resize(self):
self.view_h = int(self.canvas.winfo_height()/self.zoom)
self.view_w = int(self.canvas.winfo_width()/self.zoom)
self.update_display(update_all="Global")
#%% UI TOOLS METHODS
def show_tool_frame(self, tool):
frame = self.tool_opt_frame[tool]
self.current_tool_frame = frame
frame.tkraise()
def deactivate_tools(self):
'''
Keep one tool button active at time.
'''
# TODO rework
for tool in self.tools:
self.tool_active[tool] = False
self.tool_btn[tool].configure(border_width=0)
self.show_tool_frame("empty")
def set_controls_state(self, enabled: bool):
'''
Enable/disable all buttons.
'''
state = "normal" if enabled else "disabled"
for tool in self.tool_btn:
self.tool_btn[tool].configure(state=state, image=self.tool_icon[tool][state])
if not self.switch_computed_magic_wand:
for tool in ["wand", "wand_all", "wand_multi", "wand_box"]:
self.tool_btn[tool].configure(state="disabled", image=self.tool_icon[tool]["disabled"])
# TODO remove tool from 'always disabled' list when the corresponding function has been implemented
always_disabled = ["polygon", "bbox", "bucket",
"fill", "denoise", "interpolate",
"wand_all", "wand_multi", "wand_box",
"ruler", "area",
"custom_1", "custom_2", "custom_3", "custom_4"]
for tool in always_disabled:
self.tool_btn[tool].configure(state="disabled", image=self.tool_icon[tool]["disabled"])
def set_hide_lock_all_btns(self, enabled: bool, propagate=True):
'''
Hard set state for "hide all masks" and "lock all masks" buttons.
Put them in the "non-hidden" and "non-locked" state, and enable/disable
the buttons depending on state.
If propagate, change also the state of all masks to "non-hidden" and "non-locked".
'''
state = "normal" if enabled else "disabled"
if propagate:
self.toggle_all_masks_hide(False)
self.toggle_all_masks_lock(False)
else:
self.hide_all_mask_btn.hidden = False
self.lock_all_mask_btn.locked = False
self.hide_all_mask_btn.configure(state=state, image=self.icons_dict["EyeOpen"][state])
self.lock_all_mask_btn.configure(state=state, image=self.icons_dict["LockOpen"][state])
#%% TOOL BUTTONS
def create_tool_button(self, tool, btn_frame, row, col, command=None, last_row=False):
"""
Aux function to create button object from tool
"""
assert tool in self.tools