saliacoel commited on
Commit
fb79c49
·
verified ·
1 Parent(s): b36051f

Upload segment_anything_ultra_v3.py

Browse files
Files changed (1) hide show
  1. segment_anything_ultra_v3.py +176 -0
segment_anything_ultra_v3.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # layerstyle advance
2
+
3
+ from .imagefunc import *
4
+ from .segment_anything_func import *
5
+
6
+
7
+ class LS_LoadSAMModels:
8
+ def __init__(self):
9
+ self.NODE_NAME = 'SegmentAnythingUltra V3'
10
+
11
+ @classmethod
12
+ def INPUT_TYPES(cls):
13
+ return {
14
+ "required": {
15
+ "sam_model": (list_sam_model(), ),
16
+ "grounding_dino_model": (list_groundingdino_model(),),
17
+ },
18
+ "optional": {
19
+ }
20
+ }
21
+
22
+ RETURN_TYPES = ("LS_SAM_MODELS",)
23
+ RETURN_NAMES = ("sam_models", )
24
+ FUNCTION = "load_sam_models"
25
+ CATEGORY = '😺dzNodes/LayerMask'
26
+
27
+ def load_sam_models(self, sam_model, grounding_dino_model):
28
+
29
+
30
+ SAM_MODEL = load_sam_model(sam_model)
31
+ DINO_MODEL = load_groundingdino_model(grounding_dino_model)
32
+
33
+ return ({"SAM_MODEL":SAM_MODEL, "DINO_MODEL":DINO_MODEL},)
34
+
35
+
36
+ class LS_SegmentAnythingUltraV3:
37
+ def __init__(self):
38
+ self.NODE_NAME = 'SegmentAnythingUltra V3'
39
+
40
+ @classmethod
41
+ def INPUT_TYPES(cls):
42
+ method_list = ['VITMatte', 'VITMatte(local)', 'PyMatting', 'GuidedFilter', ]
43
+ device_list = ['cuda','cpu']
44
+ return {
45
+ "required": {
46
+ "image": ("IMAGE",),
47
+ "sam_models": ("LS_SAM_MODELS", ),
48
+ "threshold": ("FLOAT", {"default": 0.3, "min": 0, "max": 1.0, "step": 0.01}),
49
+ "detail_method": (method_list,),
50
+ "detail_erode": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}),
51
+ "detail_dilate": ("INT", {"default": 6, "min": 1, "max": 255, "step": 1}),
52
+ "black_point": ("FLOAT", {"default": 0.15, "min": 0.01, "max": 0.98, "step": 0.01, "display": "slider"}),
53
+ "white_point": ("FLOAT", {"default": 0.99, "min": 0.02, "max": 0.99, "step": 0.01, "display": "slider"}),
54
+ "process_detail": ("BOOLEAN", {"default": True}),
55
+ "prompt": ("STRING", {"default": "subject"}),
56
+ "device": (device_list,),
57
+ "max_megapixels": ("FLOAT", {"default": 2.0, "min": 1, "max": 999, "step": 0.1}),
58
+ },
59
+ "optional": {
60
+ }
61
+ }
62
+
63
+ RETURN_TYPES = ("IMAGE", "MASK",)
64
+ RETURN_NAMES = ("image", "mask",)
65
+ FUNCTION = "segment_anything_ultra_v3"
66
+ CATEGORY = '😺dzNodes/LayerMask'
67
+
68
+ def segment_anything_ultra_v3(self, image, sam_models, threshold,
69
+ detail_method, detail_erode, detail_dilate,
70
+ black_point, white_point, process_detail, prompt,
71
+ device, max_megapixels,
72
+ ):
73
+
74
+ if detail_method == 'VITMatte(local)':
75
+ local_files_only = True
76
+ else:
77
+ local_files_only = False
78
+
79
+
80
+
81
+ SAM_MODEL = sam_models["SAM_MODEL"]
82
+ DINO_MODEL = sam_models["DINO_MODEL"]
83
+
84
+ ret_images = []
85
+ ret_masks = []
86
+
87
+ for i in image:
88
+ i = torch.unsqueeze(i, 0)
89
+ i = pil2tensor(tensor2pil(i).convert('RGB'))
90
+ _image = tensor2pil(i).convert('RGBA')
91
+ boxes = groundingdino_predict(DINO_MODEL, _image, prompt, threshold)
92
+ if boxes.shape[0] == 0:
93
+ break
94
+ (_, _mask) = sam_segment(SAM_MODEL, _image, boxes)
95
+ _mask = _mask[0]
96
+ detail_range = detail_erode + detail_dilate
97
+ if process_detail:
98
+ if detail_method == 'GuidedFilter':
99
+ _mask = guided_filter_alpha(i, _mask, detail_range // 6 + 1)
100
+ _mask = tensor2pil(histogram_remap(_mask, black_point, white_point))
101
+ elif detail_method == 'PyMatting':
102
+ _mask = tensor2pil(mask_edge_detail(i, _mask, detail_range // 8 + 1, black_point, white_point))
103
+ else:
104
+ _trimap = generate_VITMatte_trimap(_mask, detail_erode, detail_dilate)
105
+ _mask = generate_VITMatte(_image, _trimap, local_files_only=local_files_only, device=device, max_megapixels=max_megapixels)
106
+ _mask = tensor2pil(histogram_remap(pil2tensor(_mask), black_point, white_point))
107
+ else:
108
+ _mask = mask2image(_mask)
109
+ _image = RGB2RGBA(tensor2pil(i).convert('RGB'), _mask.convert('L'))
110
+
111
+ ret_images.append(pil2tensor(_image))
112
+ ret_masks.append(image2mask(_mask))
113
+ if len(ret_masks) == 0:
114
+ _, height, width, _ = image.size()
115
+ empty_mask = torch.zeros((1, height, width), dtype=torch.uint8, device="cpu")
116
+ return (empty_mask, empty_mask)
117
+
118
+
119
+ log(f"{self.NODE_NAME} Processed {len(ret_masks)} image(s).", message_type='finish')
120
+ return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0),)
121
+
122
+
123
+ class LS_SegmentAnythingUltraV3_TriggerGate(LS_SegmentAnythingUltraV3):
124
+ """
125
+ Same as LS_SegmentAnythingUltraV3, except:
126
+ - Takes an additional STRING input: trigger_gate
127
+ - If trigger_gate == "" (exact empty string), bypass all processing:
128
+ - image output is the original input image (unchanged)
129
+ - mask output is a completely opaque mask
130
+ - Otherwise behaves exactly like LS_SegmentAnythingUltraV3
131
+ """
132
+ def __init__(self):
133
+ super().__init__()
134
+ self.NODE_NAME = 'SegmentAnythingUltra V3 (TriggerGate)'
135
+
136
+ @classmethod
137
+ def INPUT_TYPES(cls):
138
+ data = LS_SegmentAnythingUltraV3.INPUT_TYPES()
139
+ # Default is non-empty so behavior matches the original node unless user empties it.
140
+ data["required"]["trigger_gate"] = ("STRING", {"default": "1"})
141
+ return data
142
+
143
+ FUNCTION = "segment_anything_ultra_v3_trigger_gate"
144
+
145
+ def segment_anything_ultra_v3_trigger_gate(self, image, sam_models, threshold,
146
+ detail_method, detail_erode, detail_dilate,
147
+ black_point, white_point, process_detail, prompt,
148
+ device, max_megapixels,
149
+ trigger_gate,
150
+ ):
151
+ # Gate: exact empty string means bypass and return original image + fully opaque mask
152
+ if trigger_gate == "":
153
+ opaque_mask = torch.ones_like(image[:, :, :, 0])
154
+ log(f"{self.NODE_NAME} trigger_gate is empty — bypassed processing.", message_type='finish')
155
+ return (image, opaque_mask)
156
+
157
+ # Normal behavior (exactly the same as the original node)
158
+ return super().segment_anything_ultra_v3(
159
+ image, sam_models, threshold,
160
+ detail_method, detail_erode, detail_dilate,
161
+ black_point, white_point, process_detail, prompt,
162
+ device, max_megapixels,
163
+ )
164
+
165
+
166
+ NODE_CLASS_MAPPINGS = {
167
+ "LayerMask: SegmentAnythingUltra V3": LS_SegmentAnythingUltraV3,
168
+ "LayerMask: SegmentAnythingUltra V3 (TriggerGate)": LS_SegmentAnythingUltraV3_TriggerGate,
169
+ "LayerMask: LoadSegmentAnythingModels": LS_LoadSAMModels,
170
+ }
171
+
172
+ NODE_DISPLAY_NAME_MAPPINGS = {
173
+ "LayerMask: SegmentAnythingUltra V3": "LayerMask: SegmentAnythingUltra V3(Advance)",
174
+ "LayerMask: SegmentAnythingUltra V3 (TriggerGate)": "LayerMask: SegmentAnythingUltra V3(Advance, TriggerGate)",
175
+ "LayerMask: LoadSegmentAnythingModels": "LayerMask: Load SegmentAnything Models(Advance)",
176
+ }