saliacoel commited on
Commit
f29842e
·
verified ·
1 Parent(s): 422143a

Upload Salia_Alpha_Min_Fusion.py

Browse files
Files changed (1) hide show
  1. Salia_Alpha_Min_Fusion.py +247 -0
Salia_Alpha_Min_Fusion.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Three ComfyUI nodes for pixelwise minimum (more transparent) alpha fusion.
2
+
3
+ INSTALL
4
+ Copy this file into ComfyUI/custom_nodes/, restart ComfyUI, and refresh
5
+ the browser. Find the nodes under Salia > Alpha.
6
+
7
+ NODES
8
+ Salia Alpha Min Fusion (Images)
9
+ First_Image + Image_1, with Image_2 through Image_5 optional.
10
+ The First_Image supplies every output RGB pixel. All images supply
11
+ alpha, with RGB images treated as fully opaque (alpha = 1).
12
+
13
+ Salia Alpha Min Fusion (Masks)
14
+ First_Image + Mask_1 and Mask_2, with Mask_3 through Mask_5 optional.
15
+ inverse applies 1 - mask to each input mask BEFORE fusion.
16
+ The original First_Image alpha is included and is never inverted.
17
+
18
+ Salia Mask Min Fusion
19
+ Two masks, independent input inversion, an overriding inverse_both,
20
+ and inversion of the final output. inverse_both inverts each input
21
+ ONCE, regardless of the two individual input toggle states.
22
+
23
+ All inputs must have matching height and width. A single image/mask can
24
+ broadcast across a batch; other batch sizes must match. No resizing, color
25
+ blending, alpha multiplication, or alpha thresholding is performed.
26
+
27
+ Masks use alpha values: 0 = transparent, 1 = opaque. If an upstream node
28
+ outputs a transparency mask (including ComfyUI's Load Image MASK output),
29
+ enable the relevant input inversion to use it as alpha.
30
+
31
+ Only PyTorch, already included with ComfyUI, is required.
32
+ """
33
+
34
+ import torch
35
+
36
+
37
+ def _require_float_tensor(value, name):
38
+ if not isinstance(value, torch.Tensor):
39
+ raise TypeError("{} must be a PyTorch tensor.".format(name))
40
+ if not torch.is_floating_point(value):
41
+ raise TypeError("{} must contain floating-point values from 0 to 1.".format(name))
42
+
43
+
44
+ def _image_parts(image, name):
45
+ """Return unchanged RGB plus alpha in [batch, height, width] form."""
46
+ _require_float_tensor(image, name)
47
+ if image.ndim != 4 or image.shape[-1] not in (3, 4):
48
+ raise ValueError(
49
+ "{} must be an RGB or RGBA IMAGE shaped [B, H, W, 3 or 4]; got {}."
50
+ .format(name, tuple(image.shape))
51
+ )
52
+ rgb = image[..., :3]
53
+ if image.shape[-1] == 4:
54
+ alpha = image[..., 3].clamp(0.0, 1.0)
55
+ else:
56
+ alpha = image.new_ones(image.shape[:3])
57
+ return rgb, alpha
58
+
59
+
60
+ def _mask_tensor(mask, name):
61
+ """Normalize standard masks and masks with a singleton channel to BHW."""
62
+ _require_float_tensor(mask, name)
63
+ if mask.ndim == 2:
64
+ mask = mask.unsqueeze(0)
65
+ elif mask.ndim == 4:
66
+ if mask.shape[-1] == 1:
67
+ mask = mask[..., 0]
68
+ elif mask.shape[1] == 1:
69
+ mask = mask[:, 0, :, :]
70
+ if mask.ndim != 3:
71
+ raise ValueError(
72
+ "{} must be a MASK shaped [H, W] or [B, H, W] "
73
+ "(also accepts [B, H, W, 1] or [B, 1, H, W]); got {}."
74
+ .format(name, tuple(mask.shape))
75
+ )
76
+ return mask.clamp(0.0, 1.0)
77
+
78
+
79
+ def _compatible_batch(named_masks):
80
+ """Require matching canvases and allow only singleton batch broadcasting."""
81
+ reference_name, reference = named_masks[0]
82
+ height, width = reference.shape[1:]
83
+ if min(reference.shape) < 1:
84
+ raise ValueError("{} must not have an empty batch or canvas.".format(reference_name))
85
+ batch = max(mask.shape[0] for _, mask in named_masks)
86
+ for name, mask in named_masks:
87
+ if min(mask.shape) < 1:
88
+ raise ValueError("{} must not have an empty batch or canvas.".format(name))
89
+ if tuple(mask.shape[1:]) != (height, width):
90
+ raise ValueError(
91
+ "{} has canvas {}x{}; {} has {}x{}. "
92
+ "All inputs must have matching height and width."
93
+ .format(name, mask.shape[2], mask.shape[1], reference_name, width, height)
94
+ )
95
+ if mask.shape[0] not in (1, batch):
96
+ raise ValueError(
97
+ "{} has batch size {}; expected 1 or {}."
98
+ .format(name, mask.shape[0], batch)
99
+ )
100
+ return batch
101
+
102
+
103
+ def _merge_onto_first(First_Image, named_masks, inverse=False):
104
+ rgb, first_alpha = _image_parts(First_Image, "First_Image")
105
+ batch = _compatible_batch([("First_Image", first_alpha)] + named_masks)
106
+ alpha = first_alpha.expand(batch, -1, -1)
107
+ for _, mask in named_masks:
108
+ mask = mask.to(device=first_alpha.device, dtype=first_alpha.dtype)
109
+ if inverse:
110
+ mask = 1.0 - mask
111
+ alpha = torch.minimum(alpha, mask)
112
+ rgb = rgb.expand(batch, -1, -1, -1)
113
+ return torch.cat((rgb, alpha.unsqueeze(-1)), dim=-1)
114
+
115
+
116
+ class SaliaAlphaMinFusionImages:
117
+ @classmethod
118
+ def INPUT_TYPES(cls):
119
+ return {
120
+ "required": {
121
+ "First_Image": ("IMAGE", {
122
+ "tooltip": "RGB or RGBA source. Its colors are preserved; its alpha participates in fusion.",
123
+ }),
124
+ "Image_1": ("IMAGE", {
125
+ "tooltip": "Only alpha is used. An RGB input contributes opaque alpha (1).",
126
+ }),
127
+ },
128
+ "optional": {
129
+ "Image_2": ("IMAGE",),
130
+ "Image_3": ("IMAGE",),
131
+ "Image_4": ("IMAGE",),
132
+ "Image_5": ("IMAGE",),
133
+ },
134
+ }
135
+
136
+ RETURN_TYPES = ("IMAGE",)
137
+ RETURN_NAMES = ("RGBA",)
138
+ FUNCTION = "fuse"
139
+ CATEGORY = "Salia/Alpha"
140
+ DESCRIPTION = (
141
+ "Keep First_Image colors and use the lowest alpha at every pixel "
142
+ "across First_Image and every connected image. RGB images have alpha 1."
143
+ )
144
+
145
+ def fuse(self, First_Image, Image_1, Image_2=None, Image_3=None,
146
+ Image_4=None, Image_5=None):
147
+ named_alphas = []
148
+ for index, image in enumerate((Image_1, Image_2, Image_3, Image_4, Image_5), 1):
149
+ if image is not None:
150
+ name = "Image_{}".format(index)
151
+ _, alpha = _image_parts(image, name)
152
+ named_alphas.append((name, alpha))
153
+ return (_merge_onto_first(First_Image, named_alphas),)
154
+
155
+
156
+ class SaliaAlphaMinFusionMasks:
157
+ @classmethod
158
+ def INPUT_TYPES(cls):
159
+ return {
160
+ "required": {
161
+ "First_Image": ("IMAGE",),
162
+ "Mask_1": ("MASK",),
163
+ "Mask_2": ("MASK",),
164
+ "inverse": ("BOOLEAN", {
165
+ "default": False,
166
+ "tooltip": "Invert every connected mask before fusion. First_Image alpha is never inverted.",
167
+ }),
168
+ },
169
+ "optional": {
170
+ "Mask_3": ("MASK",),
171
+ "Mask_4": ("MASK",),
172
+ "Mask_5": ("MASK",),
173
+ },
174
+ }
175
+
176
+ RETURN_TYPES = ("IMAGE",)
177
+ RETURN_NAMES = ("RGBA",)
178
+ FUNCTION = "fuse"
179
+ CATEGORY = "Salia/Alpha"
180
+ DESCRIPTION = (
181
+ "Keep First_Image colors and take the minimum of its alpha and 2-5 masks. "
182
+ "Mask 0 is transparent, 1 opaque. inverse flips the input masks before fusion."
183
+ )
184
+
185
+ def fuse(self, First_Image, Mask_1, Mask_2, inverse=False,
186
+ Mask_3=None, Mask_4=None, Mask_5=None):
187
+ named_masks = []
188
+ for index, mask in enumerate((Mask_1, Mask_2, Mask_3, Mask_4, Mask_5), 1):
189
+ if mask is not None:
190
+ name = "Mask_{}".format(index)
191
+ named_masks.append((name, _mask_tensor(mask, name)))
192
+ return (_merge_onto_first(First_Image, named_masks, inverse=inverse),)
193
+
194
+
195
+ class SaliaMaskMinFusion:
196
+ @classmethod
197
+ def INPUT_TYPES(cls):
198
+ return {
199
+ "required": {
200
+ "Mask_1": ("MASK",),
201
+ "Mask_2": ("MASK",),
202
+ "inverse_first": ("BOOLEAN", {"default": False}),
203
+ "inverse_second": ("BOOLEAN", {"default": False}),
204
+ "inverse_both": ("BOOLEAN", {
205
+ "default": False,
206
+ "tooltip": "Invert both inputs once, ignoring inverse_first and inverse_second.",
207
+ }),
208
+ "inverse_output": ("BOOLEAN", {"default": False}),
209
+ },
210
+ }
211
+
212
+ RETURN_TYPES = ("MASK",)
213
+ RETURN_NAMES = ("MASK",)
214
+ FUNCTION = "fuse"
215
+ CATEGORY = "Salia/Alpha"
216
+ DESCRIPTION = (
217
+ "Invert inputs as selected, then take the minimum mask value per pixel. "
218
+ "inverse_both overrides both individual input toggles. inverse_output runs last."
219
+ )
220
+
221
+ def fuse(self, Mask_1, Mask_2, inverse_first=False, inverse_second=False,
222
+ inverse_both=False, inverse_output=False):
223
+ first = _mask_tensor(Mask_1, "Mask_1")
224
+ second = _mask_tensor(Mask_2, "Mask_2")
225
+ _compatible_batch([("Mask_1", first), ("Mask_2", second)])
226
+ second = second.to(device=first.device, dtype=first.dtype)
227
+ if inverse_both or inverse_first:
228
+ first = 1.0 - first
229
+ if inverse_both or inverse_second:
230
+ second = 1.0 - second
231
+ result = torch.minimum(first, second)
232
+ if inverse_output:
233
+ result = 1.0 - result
234
+ return (result,)
235
+
236
+
237
+ NODE_CLASS_MAPPINGS = {
238
+ "SaliaAlphaMinFusionImages": SaliaAlphaMinFusionImages,
239
+ "SaliaAlphaMinFusionMasks": SaliaAlphaMinFusionMasks,
240
+ "SaliaMaskMinFusion": SaliaMaskMinFusion,
241
+ }
242
+
243
+ NODE_DISPLAY_NAME_MAPPINGS = {
244
+ "SaliaAlphaMinFusionImages": "Salia Alpha Min Fusion (Images)",
245
+ "SaliaAlphaMinFusionMasks": "Salia Alpha Min Fusion (Masks)",
246
+ "SaliaMaskMinFusion": "Salia Mask Min Fusion",
247
+ }