saliacoel commited on
Commit
ef76837
·
verified ·
1 Parent(s): 22e83a6

Upload 2 files

Browse files
Salia_Aligned_Seam_Blend_GPT_2.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Salia Aligned Seam Blend GPT_1 -- NEW, standalone ComfyUI node
3
+ ============================================================
4
+ Copy this file into ComfyUI/custom_nodes/ and restart ComfyUI.
5
+ Add Salia/Image -> Salia Aligned Seam Blend GPT_1.
6
+ Dependencies: NumPy, SciPy, PyTorch, as used by the working alignment node.
7
+ No OpenCV, sibling Python files, models, or internet access are required.
8
+
9
+ REQUIRED CONNECTIONS
10
+ This node's background <- SAME original background fed to align
11
+ This node's composite_rgba <- align output composite_rgba
12
+ This node's overlay_canvas_rgba <- align output overlay_canvas_rgba
13
+ This node's x/y/width/height <- matching align FLOAT outputs
14
+ Connect BOTH alignment image outputs DIRECTLY. Do not pass them through
15
+ Load Image, RGB conversion, a mask-combining node, resizing, or another paste.
16
+ They already contain the exact alpha used by the working alignment node.
17
+
18
+ OPTIONAL CONNECTIONS
19
+ alignment_status <- align output status (recommended for diagnostics)
20
+ background_mask <- SAME Load Image MASK already used for align background
21
+ Only RGB backgrounds can use background_mask. Connect it unchanged: this
22
+ node converts Load Image MASK=1-alpha internally. Native RGBA takes priority.
23
+ There are NO overlay-mask/protection-mask inputs or overlay placement modes.
24
+ If RGB lost background alpha, this node reconstructs it from the two aligned
25
+ RGBA outputs where mathematically possible. Ambiguous opaque-overlay pixels
26
+ over a known transparent background keep the working composite until the
27
+ original background MASK is supplied; no guessed alpha changes are made.
28
+
29
+ WHAT IT DOES
30
+ This is an adapter for Salia Auto Align Overlay (Joint Registration + EWA).
31
+ It preserves the working composite's alpha EXACTLY and blends only its border
32
+ colors toward the original background. It does not turn transparent overlay
33
+ pixels into erasures or stack the overlay a second time. The aligned center
34
+ is protected. Fractional EWA placement/coverage is already baked into the
35
+ working composite and is never undone or applied twice.
36
+
37
+ Graph cut + feather chooses a low-disagreement path in a border band using
38
+ SciPy's compiled maximum-flow implementation. Border feather (diagnostic)
39
+ skips graph cut. Bypass returns the working composite unchanged. strength=0
40
+ also bypasses. seam_band_px=0 keeps the entire aligned composite unchanged.
41
+ The graph alone may be reduced; final images always retain full resolution.
42
+
43
+ INPUT CHECKS / FAILURE BEHAVIOR
44
+ Dimensions, embedded RGBA, coordinate support, and source-over recomposition
45
+ are checked. An inconsistent connection returns the alignment composite as
46
+ a safe bypass, with ERROR in status and debug images, rather than silently
47
+ blending mismatched data. Invalid non-image values still raise ValueError.
48
+ Zero-sized upstream failure coordinates also bypass with a clear status.
49
+ One image per input; split batches upstream, matching the alignment node.
50
+
51
+ OUTPUTS
52
+ result_rgba: the final straight-alpha image [1,H,W,4].
53
+ status: connection checks, alpha provenance, seam details, invariants, upstream
54
+ status if connected, and explicit warnings/errors/fallbacks.
55
+ debug_result_rgb / debug_alignment_rgb / debug_overlay_rgb: opaque checkerboard
56
+ previews; compare result against the known-good working alignment composite.
57
+ debug_overlay_alpha_rgb: WHITE=opaque overlay; BLACK=transparent (image).
58
+ debug_blend_weight_rgb: WHITE=working composite; BLACK=background color.
59
+ debug_seam_rgb: yellow=rect, cyan=protected core, green=chosen hard seam,
60
+ magenta=inconsistent overlay outside rectangle.
61
+ debug_difference_x8_rgb: abs(final-visible-reference-visible) * 8 on gray.
62
+ output_mask: standard Comfy MASK = 1-result alpha, not the seam weight.
63
+ All debug_* outputs are RGB IMAGEs: connect directly to Preview Image.
64
+
65
+ SciPy graph-cut building blocks:
66
+ https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.maximum_flow.html
67
+ https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.breadth_first_order.html
68
+ """
69
+ from __future__ import annotations
70
+
71
+ import time
72
+
73
+ import numpy as np
74
+ from scipy.ndimage import binary_erosion, distance_transform_edt, zoom
75
+
76
+ _EPS = 1.0e-8
77
+ _TOL = 2.0e-4
78
+ _METHODS = ("Graph cut + feather", "Border feather (diagnostic)", "Bypass (alignment result)")
79
+
80
+
81
+ def _array(value):
82
+ if hasattr(value, "detach"):
83
+ return value.detach().cpu().float().numpy()
84
+ return np.asarray(value)
85
+
86
+
87
+ def _image(value, name):
88
+ image = _array(value)
89
+ if image.ndim == 4 and image.shape[0] == 1:
90
+ image = image[0]
91
+ if image.ndim != 3 or image.shape[-1] not in (3, 4) or min(image.shape[:2]) < 1:
92
+ raise ValueError(name + " must be one IMAGE [1,H,W,3 or 4]; split batches upstream.")
93
+ if not np.issubdtype(image.dtype, np.floating) or not np.isfinite(image).all():
94
+ raise ValueError(name + " must contain finite floating point image pixels.")
95
+ return np.ascontiguousarray(np.clip(image, 0.0, 1.0), dtype=np.float32)
96
+
97
+
98
+ def _rgba(image):
99
+ if image.shape[-1] == 4:
100
+ return image.copy()
101
+ return np.concatenate((image, np.ones((*image.shape[:2], 1), np.float32)), axis=-1)
102
+
103
+
104
+ def _load_mask(value, shape):
105
+ mask = _array(value)
106
+ if mask.ndim == 3 and mask.shape[0] == 1:
107
+ mask = mask[0]
108
+ if mask.ndim != 2 or not np.isfinite(mask).all():
109
+ raise ValueError("background_mask must be one finite Load Image MASK [1,H,W].")
110
+ if mask.shape != shape:
111
+ if mask.shape == (64, 64) and not np.any(mask):
112
+ return np.zeros(shape, np.float32)
113
+ raise ValueError("background_mask dimensions must match the original background; do not resize/invert it.")
114
+ return np.clip(mask, 0.0, 1.0).astype(np.float32)
115
+
116
+
117
+ def _source_over(background, overlay):
118
+ # Match the ATTACHED working node: straight-alpha source-over in sRGB.
119
+ sa, ba = overlay[..., 3:4], background[..., 3:4]
120
+ alpha = sa + ba * (1.0 - sa)
121
+ p = overlay[..., :3] * sa + background[..., :3] * ba * (1.0 - sa)
122
+ rgb = np.zeros_like(p)
123
+ np.divide(p, alpha, out=rgb, where=alpha > _EPS)
124
+ result = np.concatenate((np.clip(rgb, 0.0, 1.0), alpha), axis=-1)
125
+ return np.where(sa > 0.0, result, background).astype(np.float32)
126
+
127
+
128
+ def _fields(rgba):
129
+ return np.concatenate((rgba[..., :3] * rgba[..., 3:4], rgba[..., 3:4]), axis=-1)
130
+
131
+
132
+ def _visible_error(first, second):
133
+ # Hidden RGB in fully transparent pixels cannot invalidate good wiring.
134
+ return float(np.max(np.abs(_fields(first) - _fields(second)), initial=0.0))
135
+
136
+
137
+ def _linear(rgb):
138
+ return np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4).astype(np.float32)
139
+
140
+
141
+ def _srgb(rgb):
142
+ rgb = np.clip(rgb, 0.0, 1.0)
143
+ return np.where(rgb <= 0.0031308, rgb * 12.92, 1.055 * rgb ** (1.0 / 2.4) - 0.055).astype(np.float32)
144
+
145
+
146
+ def _smooth(value):
147
+ value = np.clip(value, 0.0, 1.0)
148
+ return value * value * (3.0 - 2.0 * value)
149
+
150
+
151
+ def _geometry(shape, x, y, width, height, x0=0, y0=0):
152
+ h, w = shape
153
+ xx = x0 + np.arange(w, dtype=np.float64)
154
+ yy = y0 + np.arange(h, dtype=np.float64)
155
+ cx = np.maximum(0.0, np.minimum(xx + 1.0, x + width) - np.maximum(xx, x))
156
+ cy = np.maximum(0.0, np.minimum(yy + 1.0, y + height) - np.maximum(yy, y))
157
+ support = (cy[:, None] > 0.0) & (cx[None, :] > 0.0)
158
+ dx = np.minimum(xx + 0.5 - x, x + width - xx - 0.5)
159
+ dy = np.minimum(yy + 0.5 - y, y + height - yy - 0.5)
160
+ return support, np.minimum(dy[:, None], dx[None, :])
161
+
162
+
163
+ def _resize_nearest(image, shape):
164
+ iy = np.minimum(image.shape[0] - 1, (np.arange(shape[0]) * image.shape[0] / shape[0]).astype(np.intp))
165
+ ix = np.minimum(image.shape[1] - 1, (np.arange(shape[1]) * image.shape[1] / shape[1]).astype(np.intp))
166
+ return image[iy[:, None], ix[None, :]]
167
+
168
+
169
+ def _graph_mask(error, core, frame, interrupt):
170
+ """Exact binary minimum cut via SciPy's compiled sparse max-flow solver."""
171
+ from scipy.sparse import csr_matrix
172
+ from scipy.sparse.csgraph import maximum_flow, breadth_first_order
173
+ error = np.asarray(error, dtype=np.float64)
174
+ core, frame = np.asarray(core, dtype=bool), np.asarray(frame, dtype=bool)
175
+ if (error.ndim != 2 or min(error.shape) < 1
176
+ or core.shape != error.shape or frame.shape != error.shape
177
+ or not np.isfinite(error).all() or np.any(error < 0.0)):
178
+ raise ValueError("Graph cost/core/frame must be matching finite nonnegative HxW arrays.")
179
+ if np.any(core & frame) or not np.any(core) or not np.any(frame):
180
+ raise ValueError("Graph needs nonoverlapping mandatory composite and background seeds.")
181
+ interrupt()
182
+ h, w = error.shape
183
+ n = h * w
184
+ error = np.clip(error, 0.0, 1.0)
185
+ ids = np.arange(n, dtype=np.int32).reshape(h, w)
186
+ horizontal, vertical = ids[:, :-1].reshape(-1), ids[:-1, :].reshape(-1)
187
+ u = np.concatenate((horizontal, vertical))
188
+ v = np.concatenate((horizontal + 1, vertical + w))
189
+ scale = 4096
190
+ cost = np.concatenate((
191
+ 1 + np.rint(scale * (error[:, :-1] + error[:, 1:])).astype(np.int32).reshape(-1),
192
+ 1 + np.rint(scale * (error[:-1, :] + error[1:, :])).astype(np.int32).reshape(-1)))
193
+ core_ids, frame_ids = np.flatnonzero(core).astype(np.int32), np.flatnonzero(frame).astype(np.int32)
194
+ # A seed can save at most four incident grid costs by changing labels.
195
+ # Strictly greater terminals force the required label without huge
196
+ # near-INT_MAX capacities. Aggregate flow may exceed 32-bit safely.
197
+ terminal, source, sink = 4 * (1 + 2 * scale) + 1, n, n + 1
198
+ rows = np.concatenate((u, v, np.full(core_ids.size, source, np.int32), frame_ids))
199
+ cols = np.concatenate((v, u, core_ids, np.full(frame_ids.size, sink, np.int32)))
200
+ data = np.concatenate((cost, cost, np.full(core_ids.size + frame_ids.size, terminal, np.int32)))
201
+ capacity = csr_matrix((data, (rows, cols)), shape=(n + 2, n + 2), dtype=np.int32)
202
+ del rows, cols, data, u, v, cost, ids, horizontal, vertical
203
+ interrupt()
204
+ flow = maximum_flow(capacity, source, sink, method="dinic")
205
+ interrupt()
206
+ residual = capacity - flow.flow
207
+ residual.data[residual.data <= 0] = 0
208
+ residual.eliminate_zeros()
209
+ reachable = breadth_first_order(residual, source, directed=True, return_predecessors=False)
210
+ selected = np.zeros(n + 2, dtype=bool)
211
+ selected[reachable] = True
212
+ selected = selected[:n].reshape(h, w)
213
+ if not np.all(selected[core]) or np.any(selected[frame]):
214
+ raise RuntimeError("SciPy graph-cut violated a mandatory label.")
215
+ interrupt()
216
+ return np.ascontiguousarray(selected)
217
+
218
+
219
+ def _bounded_graph(error, core, frame, max_side, interrupt):
220
+ h, w = error.shape
221
+ scale = min(1.0, max_side / max(h, w))
222
+ gh, gw = max(1, int(round(h * scale))), max(1, int(round(w * scale)))
223
+ if (gh, gw) == (h, w):
224
+ return _graph_mask(error, core, frame, interrupt), (gw, gh)
225
+ # Evaluate mask constraints at cell centers, then restore original hard
226
+ # constraints at full resolution; tiny mandatory seed sets must survive.
227
+ small_error = zoom(error, (gh / h, gw / w), order=1, prefilter=False)
228
+ small_core = _resize_nearest(core, (gh, gw))
229
+ small_frame = _resize_nearest(frame, (gh, gw)) & ~small_core
230
+ for original, reduced, other in ((core, small_core, small_frame), (frame, small_frame, small_core)):
231
+ if np.any(original) and not np.any(reduced):
232
+ points = np.argwhere(original)
233
+ py, px = points[len(points) // 2]
234
+ gy, gx = min(gh - 1, int(py * gh / h)), min(gw - 1, int(px * gw / w))
235
+ if not other[gy, gx]:
236
+ reduced[gy, gx] = True
237
+ if not np.any(small_core) or not np.any(small_frame):
238
+ raise RuntimeError("Graph reduction removed a mandatory seed; using border feather.")
239
+ selected = _graph_mask(small_error, small_core, small_frame, interrupt)
240
+ selected = _resize_nearest(selected, (h, w)).astype(bool)
241
+ selected[core], selected[frame] = True, False
242
+ return selected, (gw, gh)
243
+
244
+
245
+ def _cost(background, reference):
246
+ # Visible disagreement over black AND white; alpha and hidden RGB never
247
+ # masquerade as a matching color. Add outline disagreement to avoid cuts
248
+ # through detail when a nearby low-error route exists.
249
+ a, b = _fields(background), _fields(reference)
250
+ dark = a[..., :3] - b[..., :3]
251
+ light = dark - (a[..., 3:4] - b[..., 3:4])
252
+ error = np.sqrt(np.mean(dark * dark + light * light, axis=-1) * 0.5)
253
+ if min(error.shape) >= 2:
254
+ ay, ax = np.gradient(a, axis=(0, 1))
255
+ by, bx = np.gradient(b, axis=(0, 1))
256
+ error += 0.35 * np.sqrt(np.mean((ay - by) ** 2 + (ax - bx) ** 2, axis=-1))
257
+ return np.clip(error, 0.0, 1.0).astype(np.float32)
258
+
259
+
260
+ def _soft_seam(hard, core, frame, distance, band, radius, use_graph):
261
+ if use_graph:
262
+ if radius > 0.0 and np.any(hard) and np.any(~hard):
263
+ signed = distance_transform_edt(hard) - distance_transform_edt(~hard)
264
+ signed = np.sign(signed) * np.maximum(np.abs(signed) - 0.5, 0.0)
265
+ weight = _smooth(0.5 + signed / (2.0 * radius))
266
+ # Smoothly meet fixed endpoints even when the seam runs beside
267
+ # the protected core; no sudden restamping jump at its boundary.
268
+ if np.any(core) and np.any(~core):
269
+ weight = np.maximum(weight, _smooth(1.0 - distance_transform_edt(~core) / radius))
270
+ if np.any(frame) and np.any(~frame):
271
+ weight = np.minimum(weight, _smooth(distance_transform_edt(~frame) / radius))
272
+ else:
273
+ weight = hard.astype(np.float32)
274
+ else:
275
+ weight = _smooth((distance - 0.75) / max(band - 0.75, 0.25))
276
+ weight[core], weight[frame] = 1.0, 0.0
277
+ return np.clip(weight, 0.0, 1.0).astype(np.float32)
278
+
279
+
280
+ def _mix_color(background, reference, weight):
281
+ # Blend visible colors with consistent premultiplied normalization. Keep
282
+ # the KNOWN-GOOD reference alpha, without applying canvas alpha again.
283
+ t = weight[..., None]
284
+ ba, ra = background[..., 3:4], reference[..., 3:4]
285
+ alpha = (1.0 - t) * ba + t * ra
286
+ p = (1.0 - t) * _linear(background[..., :3]) * ba + t * _linear(reference[..., :3]) * ra
287
+ color = np.zeros_like(p)
288
+ np.divide(p, alpha, out=color, where=alpha > _EPS)
289
+ out = reference.copy()
290
+ out[..., :3] = _srgb(color)
291
+ out[weight <= 0.0, :3] = background[weight <= 0.0, :3]
292
+ out[weight >= 1.0] = reference[weight >= 1.0]
293
+ identical = np.all(background[..., :3] == reference[..., :3], axis=-1)
294
+ out[identical] = reference[identical]
295
+ out[reference[..., 3] <= _EPS] = reference[reference[..., 3] <= _EPS]
296
+ out[..., 3] = reference[..., 3]
297
+ return np.ascontiguousarray(out)
298
+
299
+
300
+ def _checker(rgba):
301
+ h, w = rgba.shape[:2]
302
+ yy, xx = np.ogrid[:h, :w]
303
+ gray = np.where(((xx // 16 + yy // 16) % 2) == 0, 0.32, 0.58).astype(np.float32)
304
+ a = rgba[..., 3:4]
305
+ return np.ascontiguousarray(rgba[..., :3] * a + gray[..., None] * (1.0 - a), dtype=np.float32)
306
+
307
+
308
+ def _gray(value):
309
+ return np.repeat(np.clip(value, 0.0, 1.0)[..., None], 3, axis=-1).astype(np.float32)
310
+
311
+
312
+ def _edge(mask):
313
+ # Outside-canvas is not a new rectangle border. Geometry handles clipping.
314
+ return mask & ~binary_erosion(mask, border_value=1)
315
+
316
+
317
+ def _make_result(reference, overlay, result, weight, support, core, hard, invalid, lines):
318
+ seam = _checker(result)
319
+ seam[_edge(support)] = (1.0, 0.8, 0.0)
320
+ seam[_edge(core)] = (0.0, 0.8, 1.0)
321
+ seam[_edge(hard) & support] = (0.0, 1.0, 0.0)
322
+ seam[invalid] = (1.0, 0.0, 1.0)
323
+ # Difference on a FIXED matte so checker tiles do not hide subtle errors.
324
+ ra, oa = reference[..., 3:4], result[..., 3:4]
325
+ before = reference[..., :3] * ra + 0.5 * (1.0 - ra)
326
+ after = result[..., :3] * oa + 0.5 * (1.0 - oa)
327
+ return {
328
+ "result_rgba": result, "status": "\n".join(lines),
329
+ "debug_result_rgb": _checker(result), "debug_alignment_rgb": _checker(reference),
330
+ "debug_overlay_rgb": _checker(overlay), "debug_overlay_alpha_rgb": _gray(overlay[..., 3]),
331
+ "debug_blend_weight_rgb": _gray(weight), "debug_seam_rgb": seam,
332
+ "debug_difference_x8_rgb": np.clip(np.abs(after - before) * 8.0, 0.0, 1.0).astype(np.float32),
333
+ "output_mask": (1.0 - result[..., 3]).astype(np.float32),
334
+ "weight": weight, "core": core, "support": support,
335
+ }
336
+
337
+
338
+ def blend_aligned_arrays(background, composite_rgba, overlay_canvas_rgba, x, y, width, height,
339
+ seam_band_px=24.0, feather_px=3.0, strength=1.0,
340
+ method=_METHODS[0], graph_max_side=512, background_mask=None,
341
+ alignment_status=None, interrupt=lambda: None, progress=lambda value: None):
342
+ """Pure NumPy core; same alpha semantics as the supplied working aligner."""
343
+ started = time.monotonic()
344
+ raw_bg = _image(background, "background")
345
+ raw_ref = _image(composite_rgba, "composite_rgba")
346
+ raw_ov = _image(overlay_canvas_rgba, "overlay_canvas_rgba")
347
+ reference, overlay = _rgba(raw_ref), _rgba(raw_ov)
348
+ h, w = reference.shape[:2]
349
+ empty = np.zeros((h, w), dtype=bool)
350
+ support, core, hard, invalid = empty.copy(), empty.copy(), empty.copy(), empty.copy()
351
+ weight = np.zeros((h, w), dtype=np.float32)
352
+ errors, notes = [], []
353
+ lines = ["Salia Aligned Seam Blend GPT_1", "Alpha policy: preserve composite_rgba alpha EXACTLY; transparent overlay pixels never erase background."]
354
+ for name, array in (("background", raw_bg), ("composite_rgba", raw_ref), ("overlay_canvas_rgba", raw_ov)):
355
+ alpha = array[..., 3] if array.shape[-1] == 4 else np.ones(array.shape[:2])
356
+ lines.append("%s: %dx%dx%d; alpha min=%.6f max=%.6f zero=%.2f%%."
357
+ % (name, array.shape[1], array.shape[0], array.shape[2], alpha.min(), alpha.max(), 100.0 * np.mean(alpha <= _EPS)))
358
+ def finish(headline, result=None):
359
+ progress(100)
360
+ shown_overlay = overlay if overlay.shape == reference.shape else np.zeros_like(reference)
361
+ out = reference.copy() if result is None else result
362
+ if result is None:
363
+ # An early/error bypass selects the supplied aligned result,
364
+ # not the background. Make its debug weight tell the truth.
365
+ weight[:] = 1.0
366
+ text = [headline, *lines, *["ERROR: " + s for s in errors], *["NOTE: " + s for s in notes],
367
+ "seconds=%.3f" % (time.monotonic() - started)]
368
+ if alignment_status:
369
+ text += ["UPSTREAM ALIGNMENT STATUS:", str(alignment_status)[:16000]]
370
+ return _make_result(reference, shown_overlay, out, weight, support, core, hard, invalid, text)
371
+ if raw_ref.shape[-1] != 4 or raw_ov.shape[-1] != 4:
372
+ errors.append("Both aligned image outputs must retain 4 embedded RGBA channels. Connect them directly from the working alignment node, without RGB conversion/reloading/mask edits.")
373
+ if raw_bg.shape[:2] != (h, w) or overlay.shape[:2] != (h, w):
374
+ errors.append("All three images must have the same full-canvas dimensions; use overlay_canvas_rgba, not the small original overlay.")
375
+ if errors:
376
+ return finish("ERROR / BYPASS: invalid image connections; displaying the supplied alignment result.")
377
+ values = np.asarray((x, y, width, height, seam_band_px, feather_px, strength), np.float64)
378
+ if not np.isfinite(values).all() or min(width, height, seam_band_px, feather_px) < 0.0 or not 0.0 <= strength <= 1.0:
379
+ errors.append("Coordinates must be finite; sizes/band/feather must be nonnegative; strength must be 0..1.")
380
+ return finish("ERROR / BYPASS: invalid coordinates or controls.")
381
+ x, y, width, height, seam_band_px, feather_px, strength = map(float, values)
382
+ if method not in _METHODS or int(graph_max_side) != graph_max_side or not 64 <= graph_max_side <= 1024:
383
+ errors.append("Unknown method or graph_max_side outside integer range 64..1024.")
384
+ return finish("ERROR / BYPASS: invalid blending controls.")
385
+ lines.append("Geometry: x=%.8f y=%.8f width=%.8f height=%.8f (TOP LEFT pixel edges)." % (x, y, width, height))
386
+ if width == 0.0 or height == 0.0:
387
+ return finish("BYPASS: upstream zero-sized alignment/failure coordinates; alignment result retained.")
388
+ support, distance = _geometry((h, w), x, y, width, height)
389
+ invalid = ~support & (overlay[..., 3] > 2.0e-6)
390
+ if np.any(invalid):
391
+ errors.append("Overlay has %d visible pixels outside x/y/width/height. Coordinates and overlay must come from the SAME alignment run; debug_seam marks them magenta." % np.count_nonzero(invalid))
392
+ bg = _rgba(raw_bg)
393
+ ambiguous = np.zeros((h, w), dtype=bool)
394
+ if raw_bg.shape[-1] == 4:
395
+ notes.append("Background alpha: embedded RGBA, authoritative; optional background_mask ignored.")
396
+ elif background_mask is not None:
397
+ try:
398
+ bg[..., 3] = 1.0 - _load_mask(background_mask, (h, w))
399
+ notes.append("Background alpha: SAME standard Load Image MASK; converted internally as 1-mask. No external inversion.")
400
+ except ValueError as exc:
401
+ errors.append(str(exc))
402
+ else:
403
+ sa, ca = overlay[..., 3], reference[..., 3]
404
+ known = sa < 1.0 - 1.0e-6
405
+ recovered = np.zeros((h, w), np.float32)
406
+ np.divide(ca - sa, 1.0 - sa, out=recovered, where=known)
407
+ if np.any(known & ((recovered < -_TOL) | (recovered > 1.0 + _TOL))):
408
+ errors.append("Composite/canvas alpha cannot come from source-over of the same background; check aligned image connections.")
409
+ bg[..., 3] = np.where(known, np.clip(recovered, 0.0, 1.0), 1.0)
410
+ unknown = ~known & support
411
+ transparent_evidence = np.any(known & (recovered < 0.999))
412
+ ambiguous = unknown if transparent_evidence else np.zeros_like(unknown)
413
+ notes.append("Background RGB alpha reconstructed from the aligned outputs where possible; fully covered unknown pixels=%d." % np.count_nonzero(unknown))
414
+ if np.any(ambiguous):
415
+ notes.append("Transparent background detected; %d ambiguous fully covered pixels keep the working composite. For complete border blending there, connect the SAME background Load Image MASK unchanged." % np.count_nonzero(ambiguous))
416
+ expected = _source_over(bg, overlay)
417
+ recomposition_error = _visible_error(expected, reference)
418
+ lines.append("Source-over connection check: max visible RGBA error=%.9g; tolerance=%.1g." % (recomposition_error, _TOL))
419
+ if recomposition_error > _TOL:
420
+ errors.append("Composite is inconsistent with background + overlay canvas. Common causes: wrong background, swapped aligned images, differing alignment runs, or an inverted/different background MASK.")
421
+ if errors:
422
+ return finish("ERROR / BYPASS: inconsistent alignment connections; alignment result retained.")
423
+ progress(15)
424
+ if not np.any(support):
425
+ return finish("BYPASS: rectangle is outside the canvas; alignment result retained.")
426
+ if method == _METHODS[2] or strength == 0.0 or seam_band_px == 0.0:
427
+ weight[support] = 1.0
428
+ core, hard = support.copy(), support.copy()
429
+ return finish("BYPASS: explicitly keeping the working alignment result.")
430
+ # Work on a small ROI, preserving full-resolution output/debug canvases.
431
+ yy, xx = np.nonzero(support)
432
+ x0, y0 = max(0, int(xx.min()) - 1), max(0, int(yy.min()) - 1)
433
+ x1, y1 = min(w, int(xx.max()) + 2), min(h, int(yy.max()) + 2)
434
+ sl = np.s_[y0:y1, x0:x1]
435
+ valid, d = support[sl], distance[sl]
436
+ band = min(seam_band_px, 0.45 * min(width, height))
437
+ radius = min(feather_px, band / 3.0)
438
+ keep = valid & ((d >= band) | ambiguous[sl])
439
+ # New visible parts over genuinely transparent background have no old
440
+ # color to blend with; keep their known-good aligned appearance.
441
+ keep |= valid & (bg[sl][..., 3] <= _EPS) & (reference[sl][..., 3] > _EPS)
442
+ if not np.any(keep):
443
+ index = np.argmax(np.where(valid, d, -np.inf))
444
+ keep.flat[index] = True
445
+ frame = ((~valid) | (d <= 0.75)) & ~keep
446
+ chosen = keep.copy()
447
+ use_graph = method == _METHODS[0]
448
+ graph_shape = (0, 0)
449
+ if not np.any(frame):
450
+ chosen = valid.copy()
451
+ notes.append("No original rectangle border is visible on this clipped canvas; retained the working composite.")
452
+ elif use_graph:
453
+ interrupt()
454
+ try:
455
+ chosen, graph_shape = _bounded_graph(_cost(bg[sl], reference[sl]), keep, frame, int(graph_max_side), interrupt)
456
+ except (RuntimeError, ValueError, MemoryError, OverflowError) as exc:
457
+ use_graph = False
458
+ notes.append("GRAPH FALLBACK to border feather: %s: %s" % (type(exc).__name__, str(exc)))
459
+ progress(65)
460
+ chosen &= valid
461
+ chosen[keep], chosen[frame] = True, False
462
+ soft = (_soft_seam(chosen, keep, frame, d, band, radius, use_graph)
463
+ if np.any(frame) else valid.astype(np.float32))
464
+ soft[~valid] = 0.0
465
+ soft[valid] = 1.0 - strength * (1.0 - soft[valid])
466
+ weight[sl] = soft
467
+ core[sl], hard[sl] = keep, chosen
468
+ result = reference.copy()
469
+ mixed = _mix_color(bg[sl], reference[sl], soft)
470
+ result[sl] = np.where(valid[..., None], mixed, reference[sl])
471
+ interrupt()
472
+ alpha_error = float(np.max(np.abs(result[..., 3] - reference[..., 3])))
473
+ center_error = float(np.max(np.abs(result[core] - reference[core]), initial=0.0))
474
+ outside_error = float(np.max(np.abs(result[~support] - reference[~support]), initial=0.0))
475
+ difference = np.max(np.abs(_fields(result) - _fields(reference)), axis=-1)
476
+ changed = int(np.count_nonzero(difference > 1.0e-6))
477
+ lines += [
478
+ "Engine: %s; SciPy max-flow graph=%dx%d; ROI=(%d,%d)-(%d,%d)." % (method, *graph_shape, x0, y0, x1, y1),
479
+ "Effective band=%.3fpx feather=%.3fpx strength=%.3f; protected=%d; visibly changed=%d pixels." % (band, radius, strength, np.count_nonzero(core), changed),
480
+ "Invariants: alpha error=%.9g; protected-center error=%.9g; outside-rectangle error=%.9g (all must be 0)." % (alpha_error, center_error, outside_error),
481
+ "Debug seam: yellow=rect, cyan=protected core, green=chosen seam, magenta=invalid canvas support.",
482
+ ]
483
+ if changed == 0:
484
+ notes.append("NO VISIBLE CHANGE: inspect alignment, overlay alpha, and blend weight previews; the border may already match or be fully protected.")
485
+ if band != seam_band_px or radius != feather_px:
486
+ notes.append("Band/feather reduced automatically to preserve a center in this rectangle.")
487
+ if x < 0.0 or y < 0.0 or x + width > w or y + height > h:
488
+ notes.append("Clipped placement: distances use the ORIGINAL fractional rect, not a fabricated canvas-edge border.")
489
+ return finish("OK: blended aligned border colors; working composite alpha and center preserved.", result)
490
+
491
+
492
+ class Salia_Aligned_Seam_Blend_GPT_2:
493
+ @classmethod
494
+ def INPUT_TYPES(cls):
495
+ pos = {"default": 0.0, "min": -1000000.0, "max": 1000000.0, "forceInput": True}
496
+ size = {"default": 0.0, "min": 0.0, "max": 1000000.0, "forceInput": True}
497
+ return {"required": {
498
+ "background": ("IMAGE", {"tooltip": "SAME original background fed to the working alignment node."}),
499
+ "composite_rgba": ("IMAGE", {"tooltip": "DIRECT working alignment output composite_rgba; contains the correct final appearance and alpha."}),
500
+ "overlay_canvas_rgba": ("IMAGE", {"tooltip": "DIRECT working alignment output overlay_canvas_rgba; same run as composite and coordinates."}),
501
+ "x": ("FLOAT", dict(pos)), "y": ("FLOAT", dict(pos)),
502
+ "width": ("FLOAT", dict(size)), "height": ("FLOAT", dict(size)),
503
+ "seam_band_px": ("FLOAT", {"default": 24.0, "min": 0.0, "max": 512.0, "step": 1.0,
504
+ "tooltip": "Border available for seam selection. Center protected. 0 bypasses."}),
505
+ "feather_px": ("FLOAT", {"default": 3.0, "min": 0.0, "max": 64.0, "step": 0.5}),
506
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.05,
507
+ "tooltip": "1=full border blending, 0=exact original aligned composite."}),
508
+ "method": (list(_METHODS), {"default": _METHODS[0]}),
509
+ "graph_max_side": ("INT", {"default": 512, "min": 64, "max": 1024, "step": 64,
510
+ "tooltip": "Graph resolution cap only; images remain full resolution."}),
511
+ }, "optional": {
512
+ "alignment_status": ("STRING", {"forceInput": True, "tooltip": "Connect working alignment status to include it in diagnostics."}),
513
+ "background_mask": ("MASK", {"tooltip": "Only if original background is RGB with alpha split out: SAME Load Image MASK used for align background, unchanged. No inversion."}),
514
+ }}
515
+
516
+ RETURN_TYPES = ("IMAGE", "STRING", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "MASK")
517
+ RETURN_NAMES = ("result_rgba", "status", "debug_result_rgb", "debug_alignment_rgb", "debug_overlay_rgb",
518
+ "debug_overlay_alpha_rgb", "debug_blend_weight_rgb", "debug_seam_rgb", "debug_difference_x8_rgb", "output_mask")
519
+ FUNCTION = "blend"
520
+ CATEGORY = "Salia/Image"
521
+ DESCRIPTION = ("GPT_1 adapter for the working Joint Registration + EWA node. "
522
+ "Connect both aligned RGBA outputs, original background and coordinates. "
523
+ "Validates wiring, assigns alpha/coverage internally, preserves the working alpha, "
524
+ "and returns status plus RGB debug images. No OpenCV needed.")
525
+
526
+ def blend(self, background, composite_rgba, overlay_canvas_rgba, x, y, width, height,
527
+ seam_band_px=24.0, feather_px=3.0, strength=1.0, method=_METHODS[0],
528
+ graph_max_side=512, alignment_status=None, background_mask=None):
529
+ import torch
530
+ try:
531
+ from comfy.model_management import throw_exception_if_processing_interrupted as interrupt
532
+ except ImportError:
533
+ interrupt = lambda: None
534
+ try:
535
+ from comfy.utils import ProgressBar
536
+ bar = ProgressBar(100)
537
+ progress = lambda value: bar.update_absolute(int(value), 100)
538
+ except ImportError:
539
+ progress = lambda value: None
540
+ with torch.inference_mode():
541
+ interrupt()
542
+ result = blend_aligned_arrays(background, composite_rgba, overlay_canvas_rgba,
543
+ x, y, width, height, seam_band_px, feather_px, strength, method,
544
+ graph_max_side, background_mask, alignment_status, interrupt, progress)
545
+ outputs = []
546
+ for name in self.RETURN_NAMES:
547
+ if name == "status":
548
+ outputs.append(result[name])
549
+ else:
550
+ outputs.append(torch.from_numpy(np.ascontiguousarray(result[name])).unsqueeze(0))
551
+ return tuple(outputs)
552
+
553
+
554
+ NODE_CLASS_MAPPINGS = {"Salia_Aligned_Seam_Blend_GPT_2": Salia_Aligned_Seam_Blend_GPT_2}
555
+ NODE_DISPLAY_NAME_MAPPINGS = {"Salia_Aligned_Seam_Blend_GPT_2": "Salia Aligned Seam Blend GPT_2"}
Salia_Aligner_Seam_Blend_GPT_1.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Salia Aligner Seam Blend GPT_1 -- NEW, standalone ComfyUI node
3
+ ===========================================================
4
+ Install THIS file in ComfyUI/custom_nodes/ and restart ComfyUI.
5
+ Node menu: Salia/Image -> Salia Aligner Seam Blend GPT_1.
6
+ Does not modify/import another custom node. Tested against the attached
7
+ Salia_Auto_Align_Overlay(3).py (v2.2) output contract.
8
+
9
+ Required connections -- only THREE
10
+ ---------------------------------
11
+ background <- SAME ORIGINAL image feeding aligner.background
12
+ (NOT aligner.composite_rgba).
13
+ overlay_canvas_rgba <- aligner.overlay_canvas_rgba (SECOND IMAGE output).
14
+ alignment_status <- aligner.status (STRING output).
15
+ The node reads x/y/width/height from the aligner's final Overlay status line.
16
+ Do not connect individual coordinates. No overlay mode or overlay mask.
17
+
18
+ If background is already RGBA, embedded alpha is used automatically.
19
+ If the working aligner receives RGB + background_mask, branch BOTH of those
20
+ same connections here: image -> background; MASK -> optional background_mask.
21
+ Do not invert that MASK: alpha=1-MASK is reconstructed internally, just like
22
+ the working aligner. The required overlay canvas already contains real RGBA.
23
+ A PNG file having alpha does NOT mean a standard Load Image IMAGE output has
24
+ four channels. Connect the already working aligner output directly.
25
+
26
+ Inputs/settings
27
+ ---------------
28
+ seam_band=48: adjustable rectangle border; center is protected edited content.
29
+ Reduce this to preserve more of the edited patch near its edges.
30
+ feather_pixels=4: small smooth transition across the content-aware seam.
31
+ multiband=False: optional OpenCV multiband COLOR correction in that transition.
32
+ Object alpha still follows the exact RGBA replacement blend.
33
+
34
+ Automatic setup and checks
35
+ --------------------------
36
+ - Parses the final Overlay line, never Crop or center-as-top-left.
37
+ - Rejects upstream LOCATION FAILED and inconsistent status coordinates.
38
+ - Requires a four-channel overlay canvas, matching background resolution.
39
+ - Checks visible canvas pixels outside the recorded rectangle, and checks
40
+ alpha against fractional rectangle coverage to catch wrong outputs/status.
41
+ - Compares background dimensions/alpha statistics with the aligner's report.
42
+ - When Comfy supplies hidden workflow metadata, checks direct aligner output
43
+ wiring and catches composite_rgba or different-aligner connections.
44
+ - Assigns geometric coverage, object alpha, core, frame and seam internally.
45
+ - Uses actual OpenCV GraphCutSeamFinder. RGBA cost compares over BOTH black
46
+ and white, fixing the single-gray-matte ambiguity that can hide alpha changes.
47
+ - Optional MultiBandBlender affects colors only; protected/source and original
48
+ background pixels are restored exactly. The graph is capped at 1536px/side
49
+ for memory, then the full-resolution constraints are restored.
50
+
51
+ RGBA handling
52
+ -------------
53
+ This replaces an edited region, rather than stacking the same sprite twice.
54
+ Blend weight, pixel-rectangle coverage and object alpha stay separate. Blend
55
+ premultiplied LINEAR RGB and alpha, then unpremultiply. An unchanged half-alpha
56
+ edge remains half-alpha. Transparent edited pixels inside the protected core
57
+ may erase old pixels. Output outside placement stays exactly the original.
58
+ The overlay is ALREADY rendered/aligned: this node does not resize it again.
59
+
60
+ Outputs
61
+ -------
62
+ composite_rgba: final true RGBA image; save this one.
63
+ composite_preview: opaque checkerboard preview of the result.
64
+ debug_grid: eight labeled panels, with a red border on input/blending errors.
65
+ aligned_overlay_preview: incoming aligned canvas on checkerboard.
66
+ overlay_alpha: RGB grayscale, WHITE=opaque object; BLACK=transparent object.
67
+ blend_weight: RGB grayscale, WHITE=edited version; BLACK=original version.
68
+ seam_preview: result preview, GREEN=chosen seam, CYAN=protected core boundary.
69
+ blend_mask: actual replacement weight as a Comfy MASK. It is NOT object alpha
70
+ and is NOT a standard inverted Load Image transparency mask.
71
+ status: validation, parsed placement, alpha source, actual settings and errors.
72
+
73
+ Debug grid panels:
74
+ A original background | B overlay canvas | C object alpha | D blend weight
75
+ E protected core/frame | F seam | G ordinary source-over | H replacement result
76
+ Checkered/gray debug images are previews only, never the final transparent PNG.
77
+ No preview files are written automatically. Connect Preview Image to debug_grid.
78
+
79
+ On an input/dependency error, the original background is returned unchanged
80
+ with explicit status and debug images. ComfyUI cancellation still propagates.
81
+ One image per input; split batches before this node.
82
+
83
+ Dependencies: NumPy, SciPy, Pillow, PyTorch and OpenCV stitching module.
84
+ If OpenCV is missing, install in ComfyUI's Python environment:
85
+ python -m pip install opencv-python-headless
86
+ A working existing cv2 installation does not need replacement.
87
+ No network calls, model downloads, or other node files are used at runtime.
88
+
89
+ References for existing APIs used:
90
+ https://docs.opencv.org/4.x/db/dda/classcv_1_1detail_1_1GraphCutSeamFinder.html
91
+ https://docs.opencv.org/4.x/d5/d4b/classcv_1_1detail_1_1MultiBandBlender.html
92
+ https://docs.comfy.org/custom-nodes/backend/more_on_inputs
93
+ """
94
+ from __future__ import annotations
95
+ import math
96
+ import re
97
+ import time
98
+ import logging
99
+ import numpy as np
100
+ from scipy.ndimage import distance_transform_edt, binary_erosion
101
+ from PIL import Image, ImageDraw, ImageFont
102
+
103
+ __version__ = "1.0.0"
104
+ _ALPHA_EPSILON = 1.0e-8
105
+ _MAX_GRAPH_SIDE = 1536
106
+ _BLEND_MODES = ("Graph cut + feather", "Graph cut + multiband")
107
+ _LOG = logging.getLogger(__name__)
108
+
109
+ def _to_linear(rgb: np.ndarray) -> np.ndarray:
110
+ return np.where(
111
+ rgb <= 0.04045,
112
+ rgb / 12.92,
113
+ np.power((rgb + 0.055) / 1.055, 2.4),
114
+ ).astype(np.float32, copy=False)
115
+
116
+ def _to_srgb(rgb: np.ndarray) -> np.ndarray:
117
+ rgb = np.clip(rgb, 0.0, 1.0)
118
+ return np.where(
119
+ rgb <= 0.0031308,
120
+ rgb * 12.92,
121
+ 1.055 * np.power(rgb, 1.0 / 2.4) - 0.055,
122
+ ).astype(np.float32, copy=False)
123
+
124
+ def _finish_image(filtered: np.ndarray, channels: int) -> np.ndarray:
125
+ filtered = np.asarray(filtered, dtype=np.float32)
126
+ rgb = filtered[..., :3]
127
+ if channels == 4:
128
+ raw_alpha = filtered[..., 3:4]
129
+ visible = raw_alpha > _ALPHA_EPSILON
130
+ # Divide by the ORIGINAL filtered alpha, before clipping alpha.
131
+ # Negative-lobe filters can overshoot 1; clipping before division
132
+ # would alter the color of those pixels.
133
+ straight_rgb = np.zeros_like(rgb)
134
+ np.divide(rgb, raw_alpha, out=straight_rgb, where=visible)
135
+ rgb = _to_srgb(straight_rgb)
136
+ alpha = np.where(visible, np.clip(raw_alpha, 0.0, 1.0), 0.0)
137
+ result = np.concatenate((rgb, alpha), axis=-1)
138
+ else:
139
+ result = _to_srgb(rgb)
140
+ return np.ascontiguousarray(np.clip(result, 0.0, 1.0), dtype=np.float32)
141
+
142
+ def _rgba_array(image, name="image"):
143
+ """Private normalized float32 copy; hidden RGB is retained but never scored."""
144
+ result = np.asarray(image)
145
+ if result.ndim != 3 or result.shape[-1] not in (3, 4):
146
+ raise ValueError("%s must be HWC RGB or RGBA." % name)
147
+ if min(result.shape[:2]) < 1:
148
+ raise ValueError("%s is empty." % name)
149
+ if not np.issubdtype(result.dtype, np.floating):
150
+ raise ValueError("%s must contain floating-point values in [0, 1]." % name)
151
+ if not np.isfinite(result).all():
152
+ raise ValueError("%s contains NaN or infinity." % name)
153
+ result = np.clip(result, 0.0, 1.0).astype(np.float32, copy=True)
154
+ if result.shape[-1] == 3:
155
+ result = np.concatenate((result, np.ones((*result.shape[:2], 1), np.float32)), axis=-1)
156
+ return np.ascontiguousarray(result)
157
+
158
+ def rgba_disagreement(background, overlay):
159
+ """Visible disagreement in [0,1], independent of RGB beneath alpha zero.
160
+
161
+ Inputs: equal HWC straight RGBA float arrays in the same color space.
162
+ Compute the RMS difference of their RGB composites over both black and
163
+ white. This is a genuine alpha-aware cost; a single grey matte would miss
164
+ alpha differences whenever a foreground color equals that grey.
165
+ """
166
+ a = np.asarray(background, dtype=np.float64)
167
+ b = np.asarray(overlay, dtype=np.float64)
168
+ if a.shape != b.shape or a.ndim != 3 or a.shape[-1] != 4:
169
+ raise ValueError("RGBA disagreement requires equal HWC RGBA arrays.")
170
+ if not np.isfinite(a).all() or not np.isfinite(b).all():
171
+ raise ValueError("RGBA disagreement inputs must be finite.")
172
+ a, b = np.clip(a, 0.0, 1.0), np.clip(b, 0.0, 1.0)
173
+ delta_premultiplied = b[..., :3] * b[..., 3:4] - a[..., :3] * a[..., 3:4]
174
+ delta_alpha = b[..., 3:4] - a[..., 3:4]
175
+ squared = 0.5 * (np.mean(delta_premultiplied ** 2, axis=-1)
176
+ + np.mean((delta_premultiplied - delta_alpha) ** 2, axis=-1))
177
+ return np.ascontiguousarray(np.sqrt(np.clip(squared, 0.0, 1.0)), dtype=np.float32)
178
+
179
+ def graphcut_mask(error, core, frame, interrupt=lambda: None):
180
+ """Return bool mask selecting the overlay, using OpenCV's actual solver.
181
+
182
+ ``error`` is a finite HxW scalar disagreement in [0,1]. ``core`` forces
183
+ edited/overlay pixels and ``frame`` forces original/background pixels.
184
+ Availability masks are geometry constraints, NOT image alpha: a source
185
+ pixel with alpha zero may intentionally erase an old opaque pixel.
186
+
187
+ OpenCV's GraphCutSeamFinder expects three-channel float cost images. Its
188
+ COST_COLOR edge term is norm(image1[p]-image2[p]) plus the same at q plus
189
+ one. Feed zero versus repeated(error*255/sqrt(3)) to make its color norm
190
+ exactly the caller's RGBA-aware error. COST_COLOR_GRAD is deliberately
191
+ not used: gradients of an error proxy are not gradients of the artwork.
192
+ This calls the existing OpenCV graph-cut implementation; it does not
193
+ reimplement max-flow/min-cut in Python.
194
+ """
195
+ error = np.asarray(error, dtype=np.float32)
196
+ core, frame = np.asarray(core, dtype=bool), np.asarray(frame, dtype=bool)
197
+ if error.ndim != 2 or min(error.shape) < 1 or core.shape != error.shape or frame.shape != error.shape:
198
+ raise ValueError("Graph-cut error/core/frame must have matching nonempty HxW shapes.")
199
+ if not np.isfinite(error).all():
200
+ raise ValueError("Graph-cut error contains NaN or infinity.")
201
+ if np.any(core & frame):
202
+ raise ValueError("Protected overlay core and background frame must not overlap.")
203
+ if not np.any(core):
204
+ raise ValueError("Graph-cut requires at least one protected overlay core pixel.")
205
+ try:
206
+ import cv2
207
+ except ImportError as exc:
208
+ raise RuntimeError("OpenCV is required. Install opencv-python-headless in ComfyUI's Python environment.") from exc
209
+ constructor = getattr(getattr(cv2, "detail", None), "GraphCutSeamFinder", None)
210
+ if constructor is None:
211
+ constructor = getattr(cv2, "detail_GraphCutSeamFinder", None)
212
+ if constructor is None:
213
+ raise RuntimeError("This OpenCV build does not include GraphCutSeamFinder (stitching module).")
214
+
215
+ interrupt()
216
+ h, w = error.shape
217
+ first = np.zeros((h, w, 3), dtype=np.float32)
218
+ scalar = np.clip(error, 0.0, 1.0) * np.float32(255.0 / np.sqrt(3.0))
219
+ second = np.ascontiguousarray(np.repeat(scalar[..., None], 3, axis=-1))
220
+ background_available = np.full((h, w), 255, dtype=np.uint8)
221
+ overlay_available = np.full((h, w), 255, dtype=np.uint8)
222
+ background_available[core] = 0
223
+ overlay_available[frame] = 0
224
+ # UMat makes the in/out mutation behavior reliable across Python builds.
225
+ masks = [cv2.UMat(background_available), cv2.UMat(overlay_available)]
226
+ finder = constructor("COST_COLOR", 1.0e7, 0.0)
227
+ changed = finder.find([cv2.UMat(first), cv2.UMat(second)], [(0, 0), (0, 0)], masks)
228
+ if changed is not None:
229
+ masks = list(changed)
230
+ selected = masks[1].get() if hasattr(masks[1], "get") else np.asarray(masks[1])
231
+ selected = np.asarray(selected) > 0
232
+ # Explicit final constraints also guard against changed OpenCV penalties
233
+ # or precision behavior in alternative builds.
234
+ selected[core] = True
235
+ selected[frame] = False
236
+ interrupt()
237
+ return np.ascontiguousarray(selected)
238
+
239
+ def opencv_multiband_fields(background_fields, source_fields, source_weight,
240
+ bands=4, interrupt=lambda: None):
241
+ """Blend ``[linear-premultiplied R,G,B,alpha]`` arrays with OpenCV.
242
+
243
+ Inputs are equally sized HWC float arrays; source_weight is HW in [0,1]
244
+ and is independent of either image's alpha. The source fields must be
245
+ UNCOVERED fields (placement coverage is already part of source_weight).
246
+
247
+ Uses the actual cv2.detail.MultiBandBlender implementation in two passes:
248
+ premultiplied RGB, then alpha in two channels plus a unit calibration
249
+ channel. OpenCV requires
250
+ signed 16-bit 3-channel images and 8-bit masks. Values are quantized at
251
+ scale 32767 internally; output remains float32 premultiplied RGBA fields.
252
+ The caller should constrain any pyramid overshoot, unpremultiply, and
253
+ restamp protected/source or unchanged/background regions as appropriate.
254
+
255
+ This helper does not impose locality: multiband filters can affect pixels
256
+ outside a simple mask's transition. The caller owns the permitted region.
257
+ """
258
+ interrupt()
259
+ background = np.asarray(background_fields)
260
+ source = np.asarray(source_fields)
261
+ weight = np.asarray(source_weight)
262
+ if (background.ndim != 3 or background.shape[-1] != 4
263
+ or source.shape != background.shape or min(background.shape[:2]) < 1):
264
+ raise ValueError("Multiband fields must be equal, nonempty HWC four-channel arrays.")
265
+ if weight.shape != background.shape[:2]:
266
+ raise ValueError("Multiband source_weight must match the image H/W.")
267
+ if (not np.issubdtype(background.dtype, np.floating)
268
+ or not np.issubdtype(source.dtype, np.floating)
269
+ or not np.issubdtype(weight.dtype, np.floating)):
270
+ raise ValueError("Multiband fields and source_weight must be floating point.")
271
+ if (not np.isfinite(background).all() or not np.isfinite(source).all()
272
+ or not np.isfinite(weight).all()):
273
+ raise ValueError("Multiband fields contain NaN or infinity.")
274
+ if isinstance(bands, bool) or not isinstance(bands, (int, np.integer)) or not 0 <= bands <= 10:
275
+ raise ValueError("Multiband bands must be an integer from 0 to 10.")
276
+ background = np.ascontiguousarray(np.clip(background, 0.0, 1.0), dtype=np.float32)
277
+ source = np.ascontiguousarray(np.clip(source, 0.0, 1.0), dtype=np.float32)
278
+ weight = np.clip(weight, 0.0, 1.0)
279
+ if not np.any(weight > 0.0):
280
+ return background.copy()
281
+ if not np.any(weight < 1.0):
282
+ return source.copy()
283
+ if np.array_equal(background, source):
284
+ return background.copy()
285
+
286
+ import cv2
287
+ factory = getattr(cv2, "detail_MultiBandBlender", None)
288
+ if factory is None:
289
+ factory = getattr(getattr(cv2, "detail", None), "MultiBandBlender", None)
290
+ if factory is None:
291
+ raise RuntimeError("This OpenCV build does not provide MultiBandBlender.")
292
+
293
+ height, width = background.shape[:2]
294
+ # Quantize once and construct the complement from the same integer mask.
295
+ # This guarantees masks sum to 255 instead of independent rounding gaps.
296
+ source_mask = np.ascontiguousarray(np.rint(weight * 255.0), dtype=np.uint8)
297
+ background_mask = np.ascontiguousarray(255 - source_mask, dtype=np.uint8)
298
+ if not np.any(source_mask):
299
+ return background.copy()
300
+ if np.all(source_mask == 255):
301
+ return source.copy()
302
+ value_scale = 32767.0
303
+
304
+ def blend_three(background_three, source_three):
305
+ interrupt()
306
+ blender = factory()
307
+ blender.setNumBands(int(bands))
308
+ blender.prepare((0, 0, int(width), int(height)))
309
+ for values, mask in ((background_three, background_mask), (source_three, source_mask)):
310
+ interrupt()
311
+ # MultiBandBlender accepts CV_16SC3 rather than float color input.
312
+ quantized = np.ascontiguousarray(np.rint(values * value_scale), dtype=np.int16)
313
+ blender.feed(quantized, mask, (0, 0))
314
+ interrupt()
315
+ output, _output_mask = blender.blend(None, None)
316
+ interrupt()
317
+ output = np.asarray(output)
318
+ if output.shape != (height, width, 3):
319
+ raise RuntimeError("OpenCV returned an unexpected multiband image shape.")
320
+ return output.astype(np.float32) / value_scale
321
+
322
+ premultiplied_rgb = blend_three(background[..., :3], source[..., :3])
323
+ # The 16-bit implementation can produce a small mask-dependent gain
324
+ # bias even for constant unit input. Carry a unit field alongside alpha
325
+ # to measure/correct it using the very same masks and pyramid levels.
326
+ ones = np.ones((height, width, 1), dtype=np.float32)
327
+ background_alpha = np.concatenate((background[..., 3:4], background[..., 3:4], ones), axis=-1)
328
+ source_alpha = np.concatenate((source[..., 3:4], source[..., 3:4], ones), axis=-1)
329
+ alpha_three = blend_three(background_alpha, source_alpha)
330
+ gain = alpha_three[..., 2:3]
331
+ if not np.isfinite(gain).all() or np.any(gain <= 0.0):
332
+ raise RuntimeError("OpenCV multiband normalization failed.")
333
+ premultiplied_rgb = premultiplied_rgb / gain
334
+ alpha = alpha_three[..., :1] / gain
335
+ if np.array_equal(background[..., 3], source[..., 3]):
336
+ alpha = background[..., 3:4].copy()
337
+ return np.ascontiguousarray(np.concatenate((premultiplied_rgb, alpha), axis=-1), dtype=np.float32)
338
+
339
+ def _coverage(x, y, width, height, x0, y0, out_width, out_height):
340
+ px = np.arange(x0, x0 + out_width, dtype=np.float64)
341
+ py = np.arange(y0, y0 + out_height, dtype=np.float64)
342
+ kx = np.maximum(0.0, np.minimum(px + 1.0, x + width) - np.maximum(px, x))
343
+ ky = np.maximum(0.0, np.minimum(py + 1.0, y + height) - np.maximum(py, y))
344
+ return np.ascontiguousarray(ky[:, None] * kx[None, :], dtype=np.float32)
345
+
346
+ def _linear_fields(rgba):
347
+ alpha = rgba[..., 3:4]
348
+ return np.concatenate((_to_linear(rgba[..., :3]) * alpha, alpha), axis=-1)
349
+
350
+ def _seam_cost(background, overlay, gradient_weight):
351
+ # Compare appearance over BOTH black and white, so neither hidden RGB
352
+ # nor a lucky match to a single matte can hide an alpha disagreement.
353
+ a, b = background.copy(), overlay.copy()
354
+ a[..., :3], b[..., :3] = _to_linear(a[..., :3]), _to_linear(b[..., :3])
355
+ error = rgba_disagreement(a, b)
356
+ if gradient_weight > 0.0 and min(error.shape) >= 2:
357
+ af, bf = _linear_fields(background), _linear_fields(overlay)
358
+ ady, adx = np.gradient(af, axis=(0, 1))
359
+ bdy, bdx = np.gradient(bf, axis=(0, 1))
360
+ gradient_error = np.sqrt(np.mean((ady - bdy) ** 2 + (adx - bdx) ** 2, axis=-1))
361
+ error = (error + float(gradient_weight) * gradient_error) / (1.0 + float(gradient_weight))
362
+ return np.ascontiguousarray(np.clip(error, 0.0, 1.0), dtype=np.float32)
363
+
364
+ def _bounded_graphcut(error, core, frame, interrupt):
365
+ h, w = error.shape
366
+ if max(h, w) <= _MAX_GRAPH_SIDE:
367
+ return graphcut_mask(error, core, frame, interrupt), (w, h)
368
+ import cv2
369
+ ratio = _MAX_GRAPH_SIDE / max(h, w)
370
+ gw, gh = max(3, int(round(w * ratio))), max(3, int(round(h * ratio)))
371
+ small_error = cv2.resize(error, (gw, gh), interpolation=cv2.INTER_AREA)
372
+ small_core = cv2.resize(core.astype(np.float32), (gw, gh), interpolation=cv2.INTER_AREA) > 0.0
373
+ small_frame = cv2.resize(frame.astype(np.float32), (gw, gh), interpolation=cv2.INTER_AREA) > 0.0
374
+ small_frame &= ~small_core
375
+ small = graphcut_mask(small_error, small_core, small_frame, interrupt)
376
+ result = cv2.resize(small.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) > 0
377
+ result[core], result[frame] = True, False
378
+ return result, (gw, gh)
379
+
380
+ def _feather_seam(selected, core, frame, radius):
381
+ if radius <= 0 or np.all(selected) or not np.any(selected):
382
+ result = selected.astype(np.float32)
383
+ else:
384
+ signed = distance_transform_edt(selected) - distance_transform_edt(~selected)
385
+ # The seam lies halfway between the two adjacent pixel centers.
386
+ signed = np.sign(signed) * np.maximum(0.0, np.abs(signed) - 0.5)
387
+ t = np.clip(0.5 + signed / (2.0 * float(radius)), 0.0, 1.0)
388
+ result = (t * t * (3.0 - 2.0 * t)).astype(np.float32)
389
+ result[core], result[frame] = 1.0, 0.0
390
+ return result
391
+
392
+ def _replace_rgba(background, source, weight, coverage, blend_mode, bands, interrupt):
393
+ # k is rectangle coverage, a is object alpha, w is seam preference.
394
+ # Keep them distinct. Source-over would thicken an unchanged alpha edge.
395
+ effective = np.clip(weight * coverage, 0.0, 1.0)
396
+ bg_fields, src_fields = _linear_fields(background), _linear_fields(source)
397
+ base = bg_fields * (1.0 - effective[..., None]) + src_fields * effective[..., None]
398
+ fields = base.copy()
399
+ if blend_mode == _BLEND_MODES[1] and np.any((effective > 0.0) & (effective < 1.0)):
400
+ mb = opencv_multiband_fields(bg_fields, src_fields, effective, bands, interrupt)
401
+ # Keep exact replacement alpha so Laplacian bands do not spread the
402
+ # transparent silhouette. Multiband adjusts color in the transition.
403
+ mb_rgb = np.zeros_like(mb[..., :3])
404
+ np.divide(mb[..., :3], mb[..., 3:4], out=mb_rgb,
405
+ where=mb[..., 3:4] > _ALPHA_EPSILON)
406
+ mb_premultiplied = np.clip(mb_rgb, 0.0, 1.0) * base[..., 3:4]
407
+ gate = 4.0 * effective * (1.0 - effective)
408
+ fields[..., :3] += gate[..., None] * (mb_premultiplied - base[..., :3])
409
+ fields[..., 3] = np.clip(base[..., 3], 0.0, 1.0)
410
+ fields[..., :3] = np.clip(fields[..., :3], 0.0, fields[..., 3:4])
411
+ result = _finish_image(fields, 4)
412
+ # Keep unselected original pixels byte-for-byte. Full-source pixels stay
413
+ # byte-for-byte equal to the placed source; identical pairs stay identical.
414
+ result[effective <= 0.0] = background[effective <= 0.0]
415
+ result[effective >= 1.0] = source[effective >= 1.0]
416
+ # Original-source EWA can leave ~1 ULP in a constant field. Do not let
417
+ # OpenCV's internal 16-bit color path amplify that into a visible change.
418
+ # Fully selected source/core pixels keep their exact placed-source values.
419
+ identical = (np.all(np.abs(source - background) <= 2.0e-7, axis=-1)
420
+ & (effective < 1.0))
421
+ result[identical] = background[identical]
422
+ return result, effective
423
+
424
+ # ---------------------------------------------------------------------------
425
+ # Direct contract with Salia Auto Align Overlay (Joint Registration + EWA).
426
+ # ---------------------------------------------------------------------------
427
+
428
+ class GPT1InputError(ValueError):
429
+ pass
430
+
431
+
432
+ _NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"
433
+ _OVERLAY_STATUS = re.compile(
434
+ r"^Overlay:\s*top_left=\(\s*(" + _NUMBER + r"),\s*(" + _NUMBER
435
+ + r")\s*\),\s*size=\(\s*(" + _NUMBER + r"),\s*(" + _NUMBER
436
+ + r")\s*\),\s*center=\(\s*(" + _NUMBER + r"),\s*(" + _NUMBER
437
+ + r")\s*\)\s*$", re.MULTILINE)
438
+ _BACKGROUND_STATUS = re.compile(
439
+ r"^background=(\d+)x(\d+),\s*input_channels=(\d+),\s*alpha_zero=([\d.]+)%,\s*alpha_opaque=([\d.]+)%\s*$",
440
+ re.MULTILINE)
441
+
442
+
443
+ def parse_alignment_status(status):
444
+ if not isinstance(status, str) or not status.strip():
445
+ raise GPT1InputError("alignment_status is empty. Connect the aligner's status output directly.")
446
+ if "LOCATION FAILED" in status:
447
+ raise GPT1InputError("The aligner reported LOCATION FAILED. Fix alignment first; no blending was applied.")
448
+ matches = list(_OVERLAY_STATUS.finditer(status))
449
+ if len(matches) != 1:
450
+ raise GPT1InputError("Expected one final 'Overlay: top_left=..., size=..., center=...' line. Connect status from Salia Auto Align Overlay (Joint Registration + EWA), not another blender.")
451
+ x, y, width, height, cx, cy = map(float, matches[0].groups())
452
+ values = np.asarray((x, y, width, height, cx, cy), dtype=np.float64)
453
+ if not np.isfinite(values).all() or not (1.0 <= width <= 32768 and 1.0 <= height <= 32768):
454
+ raise GPT1InputError("Aligner rectangle is invalid: coordinates must be finite and width/height at least 1.")
455
+ if abs(cx - (x + width / 2.0)) > 2.0e-6 or abs(cy - (y + height / 2.0)) > 2.0e-6:
456
+ raise GPT1InputError("Aligner status contains inconsistent top-left/size/center values.")
457
+ background_match = list(_BACKGROUND_STATUS.finditer(status))
458
+ if len(background_match) > 1:
459
+ raise GPT1InputError("Status contains multiple background descriptions; connect one aligner's status.")
460
+ expected = None
461
+ if background_match:
462
+ bw, bh, channels, zero, opaque = background_match[0].groups()
463
+ expected = {"width": int(bw), "height": int(bh), "channels": int(channels),
464
+ "alpha_zero": float(zero), "alpha_opaque": float(opaque)}
465
+ return (x, y, width, height), expected
466
+
467
+
468
+ def _alpha_stats(rgba):
469
+ alpha = rgba[..., 3]
470
+ return (float(np.mean(alpha <= _ALPHA_EPSILON) * 100.0),
471
+ float(np.mean(alpha >= 1.0 - _ALPHA_EPSILON) * 100.0))
472
+
473
+
474
+ def _describe(name, rgba):
475
+ zero, opaque = _alpha_stats(rgba)
476
+ return "%s: %dx%d RGBA, transparent %.2f%%, opaque %.2f%%" % (
477
+ name, rgba.shape[1], rgba.shape[0], zero, opaque)
478
+
479
+
480
+ def _background_rgba(background, mask):
481
+ raw = np.asarray(background)
482
+ rgba = _rgba_array(raw, "background")
483
+ if raw.shape[-1] == 4:
484
+ return rgba, "embedded RGBA alpha (external background_mask ignored)"
485
+ if mask is None:
486
+ return rgba, "RGB with no mask; treated as opaque"
487
+ value = np.asarray(mask)
488
+ if value.ndim == 3 and value.shape[0] == 1:
489
+ value = value[0]
490
+ if value.shape != rgba.shape[:2]:
491
+ if value.shape == (64, 64) and not np.any(value):
492
+ value = np.zeros(rgba.shape[:2], np.float32)
493
+ else:
494
+ raise GPT1InputError("background_mask must match the background resolution. Reuse the exact same MASK connected to the aligner; do not invert it.")
495
+ if not np.isfinite(value).all():
496
+ raise GPT1InputError("background_mask contains NaN or infinity.")
497
+ rgba[..., 3] = 1.0 - np.clip(value, 0.0, 1.0)
498
+ return rgba, "RGB + standard Comfy MASK; alpha=1-MASK automatically"
499
+
500
+
501
+ def _canvas_rgba(canvas):
502
+ raw = np.asarray(canvas)
503
+ if raw.ndim != 3 or raw.shape[-1] != 4:
504
+ raise GPT1InputError("overlay_canvas_rgba must have FOUR channels. Connect the aligner's overlay_canvas_rgba output directly; do not split alpha or convert it to RGB.")
505
+ return _rgba_array(raw, "overlay_canvas_rgba")
506
+
507
+
508
+ def _edge(value):
509
+ if (isinstance(value, (list, tuple)) and len(value) == 2
510
+ and isinstance(value[0], (int, str))
511
+ and isinstance(value[1], int) and not isinstance(value[1], bool)):
512
+ return str(value[0]), value[1]
513
+ return None
514
+
515
+
516
+ def check_prompt_wiring(prompt, unique_id, background_is_rgb=False):
517
+ """Optional graph-level diagnostics; tensor validation still applies."""
518
+ if not isinstance(prompt, dict) or unique_id is None:
519
+ return ["Workflow-link metadata unavailable; image/status data were validated directly."]
520
+ here = prompt.get(str(unique_id), prompt.get(unique_id, {}))
521
+ if not isinstance(here, dict):
522
+ return ["Workflow-link metadata unavailable for this node."]
523
+ inputs = here.get("inputs", {})
524
+ status_link = _edge(inputs.get("alignment_status"))
525
+ if status_link is None:
526
+ return ["Status was supplied indirectly; for easiest debugging connect the aligner's status output directly."]
527
+ source = prompt.get(status_link[0], {})
528
+ if not isinstance(source, dict) or source.get("class_type") != "Salia_Auto_Align_Overlay":
529
+ return ["Status source is an intermediate node; its final overlay line was validated."]
530
+ if status_link[1] != 2:
531
+ raise GPT1InputError("alignment_status is connected to the wrong aligner output; use status (output 3).")
532
+ canvas_link = _edge(inputs.get("overlay_canvas_rgba"))
533
+ if canvas_link is not None:
534
+ if canvas_link[0] == status_link[0] and canvas_link[1] != 1:
535
+ raise GPT1InputError("Wrong image output: use overlay_canvas_rgba (output 2), NOT composite_rgba (output 1).")
536
+ other = prompt.get(canvas_link[0], {})
537
+ if (canvas_link[0] != status_link[0] and isinstance(other, dict)
538
+ and other.get("class_type") == "Salia_Auto_Align_Overlay"):
539
+ raise GPT1InputError("The overlay canvas and status come from different aligner nodes. Connect both from the same aligner.")
540
+ background_link = _edge(inputs.get("background"))
541
+ if background_link is not None and background_link[0] == status_link[0]:
542
+ raise GPT1InputError("background is connected to an aligner RESULT. Branch the ORIGINAL image feeding the aligner's background input instead.")
543
+ aligner_background = _edge(source.get("inputs", {}).get("background"))
544
+ notes = ["Verified status source: Salia Auto Align Overlay (Joint Registration + EWA)."]
545
+ if canvas_link == (status_link[0], 1):
546
+ notes.append("Verified overlay_canvas_rgba comes directly from the same aligner.")
547
+ if background_link == aligner_background and background_link is not None:
548
+ notes.append("Verified background uses the same upstream image as the aligner.")
549
+ elif background_link is not None:
550
+ notes.append("Background uses a different graph branch from the aligner; dimensions/alpha were checked, but original RGB cannot be proven from status alone.")
551
+ if background_is_rgb:
552
+ aligner_mask = _edge(source.get("inputs", {}).get("background_mask"))
553
+ this_mask = _edge(inputs.get("background_mask"))
554
+ if this_mask != aligner_mask:
555
+ raise GPT1InputError("background_mask uses a different connection from the aligner. For an RGB background, branch the EXACT SAME MASK feeding the aligner's background_mask, without inversion. If the aligner has no background_mask, leave this socket disconnected too.")
556
+ if this_mask is not None:
557
+ notes.append("Verified background_mask uses the exact same upstream MASK as the aligner; no extra inversion.")
558
+ else:
559
+ notes.append("Verified neither RGB background input has an external MASK.")
560
+ return notes
561
+
562
+
563
+ def _validate_canvas(background, canvas, rectangle, expected_background):
564
+ if canvas.shape != background.shape:
565
+ raise GPT1InputError("Background and overlay canvas sizes differ (%dx%d versus %dx%d). The original cropped overlay is not the canvas; connect overlay_canvas_rgba from the aligner." % (
566
+ background.shape[1], background.shape[0], canvas.shape[1], canvas.shape[0]))
567
+ if expected_background is not None:
568
+ if (background.shape[1], background.shape[0]) != (expected_background["width"], expected_background["height"]):
569
+ raise GPT1InputError("Background dimensions do not match the aligner's recorded background.")
570
+ zero, opaque = _alpha_stats(background)
571
+ if (abs(zero - expected_background["alpha_zero"]) > 0.15
572
+ or abs(opaque - expected_background["alpha_opaque"]) > 0.15):
573
+ raise GPT1InputError("Background alpha does not match what the aligner used. Reuse its exact original RGBA background; for RGB, also branch the exact same background_mask without inverting it. Aligner: transparent %.2f%%/opaque %.2f%%; here: %.2f%%/%.2f%%." % (
574
+ expected_background["alpha_zero"], expected_background["alpha_opaque"], zero, opaque))
575
+ x, y, width, height = rectangle
576
+ bh, bw = background.shape[:2]
577
+ x0, y0 = max(0, min(bw, math.floor(x))), max(0, min(bh, math.floor(y)))
578
+ x1, y1 = max(0, min(bw, math.ceil(x + width))), max(0, min(bh, math.ceil(y + height)))
579
+ if x1 <= x0 or y1 <= y0:
580
+ raise GPT1InputError("The aligner's rectangle has no overlap with the background.")
581
+ outside = canvas[..., 3] > 2.0e-6
582
+ outside[y0:y1, x0:x1] = False
583
+ if np.any(outside):
584
+ raise GPT1InputError("Canvas has %d visible pixels OUTSIDE the aligner rectangle. This commonly means composite_rgba was connected instead of overlay_canvas_rgba, or the canvas and status belong to different runs." % int(outside.sum()))
585
+ k = _coverage(x, y, width, height, x0, y0, x1 - x0, y1 - y0)
586
+ patch = canvas[y0:y1, x0:x1].copy()
587
+ if not np.any(patch[..., 3] > _ALPHA_EPSILON):
588
+ raise GPT1InputError("The aligned overlay canvas is empty. Check the aligner's status and overlay_canvas_rgba output.")
589
+ if np.any(patch[..., 3] > k + 2.0e-5):
590
+ raise GPT1InputError("Canvas alpha exceeds the fractional rectangle coverage recorded in status. The canvas may have been altered, inverted, or paired with the wrong status.")
591
+ np.divide(patch[..., 3], k, out=patch[..., 3], where=k > 0.0)
592
+ patch[..., 3] = np.clip(patch[..., 3], 0.0, 1.0)
593
+ return patch, k, (x0, y0, x1 - x0, y1 - y0)
594
+
595
+
596
+ def _blend_verified_canvas(background, canvas, rectangle, source, coverage, bbox,
597
+ seam_band, feather_pixels, multiband, interrupt, progress):
598
+ x0, y0, w, h = bbox
599
+ roi = background[y0:y0 + h, x0:x0 + w]
600
+ valid = coverage > 0.0
601
+ inward = distance_transform_edt(np.pad(valid, 1, constant_values=False))[1:-1, 1:-1]
602
+ actual_band = min(int(seam_band), max(1, int(math.floor(inward.max() / 2.0))))
603
+ core = (inward > actual_band) & valid
604
+ frame = ((inward <= 1.0) | ~valid) & ~core
605
+ progress(35)
606
+ if min(h, w) < 3:
607
+ core, frame, selected = valid.copy(), np.zeros_like(valid), valid.copy()
608
+ graph_shape = (0, 0)
609
+ else:
610
+ error = _seam_cost(roi, source, 0.35)
611
+ selected, graph_shape = _bounded_graphcut(error, core, frame, interrupt)
612
+ selected &= valid
613
+ weight = _feather_seam(selected, core, frame, int(feather_pixels))
614
+ weight[~valid] = 0.0
615
+ mode = _BLEND_MODES[1] if multiband else _BLEND_MODES[0]
616
+ progress(65)
617
+ mixed, effective = _replace_rgba(roi, source, weight, coverage, mode, 4, interrupt)
618
+ output = background.copy()
619
+ output[y0:y0 + h, x0:x0 + w] = mixed
620
+ full_weight = np.zeros(background.shape[:2], np.float32)
621
+ full_core = np.zeros(background.shape[:2], bool)
622
+ full_frame = np.zeros(background.shape[:2], bool)
623
+ full_selected = np.zeros(background.shape[:2], bool)
624
+ full_weight[y0:y0 + h, x0:x0 + w] = effective
625
+ full_core[y0:y0 + h, x0:x0 + w] = core
626
+ full_frame[y0:y0 + h, x0:x0 + w] = frame
627
+ full_selected[y0:y0 + h, x0:x0 + w] = selected
628
+ return {"composite": output, "weight": full_weight, "core": full_core,
629
+ "frame": full_frame, "selected": full_selected, "bbox": bbox,
630
+ "graph_shape": graph_shape, "seam_band": actual_band, "mode": mode}
631
+
632
+
633
+ # ---------------------------------------------------------------------------
634
+ # Opaque debug previews. Their checkerboard is a preview, not the final alpha.
635
+ # ---------------------------------------------------------------------------
636
+
637
+ def checker_preview(rgba):
638
+ h, w = rgba.shape[:2]
639
+ yy, xx = np.ogrid[:h, :w]
640
+ tiles = ((xx // 24 + yy // 24) % 2).astype(np.float32)
641
+ checker = 0.24 + 0.14 * tiles
642
+ alpha = rgba[..., 3:4]
643
+ return np.ascontiguousarray(rgba[..., :3] * alpha + checker[..., None] * (1.0 - alpha), dtype=np.float32)
644
+
645
+
646
+ def _gray(value):
647
+ return np.repeat(np.clip(value, 0.0, 1.0)[..., None], 3, axis=-1).astype(np.float32)
648
+
649
+
650
+ def _source_over_debug(background, canvas):
651
+ if background.shape != canvas.shape:
652
+ return checker_preview(background)
653
+ aa, ab = canvas[..., 3:4], background[..., 3:4]
654
+ alpha = aa + ab * (1.0 - aa)
655
+ premult = canvas[..., :3] * aa + background[..., :3] * ab * (1.0 - aa)
656
+ color = np.zeros_like(premult)
657
+ np.divide(premult, alpha, out=color, where=alpha > _ALPHA_EPSILON)
658
+ return checker_preview(np.concatenate((color, alpha), axis=-1))
659
+
660
+
661
+ def _debug_grid(panels, error_text=None):
662
+ cell, title, gap = 320, 32, 8
663
+ grid = Image.new("RGB", (4 * (cell + gap) + gap, 2 * (cell + title + gap) + gap), (22, 22, 26))
664
+ draw = ImageDraw.Draw(grid)
665
+ try:
666
+ font = ImageFont.truetype("DejaVuSans.ttf", 14)
667
+ except OSError:
668
+ font = ImageFont.load_default()
669
+ for index, (label, rgb) in enumerate(panels[:8]):
670
+ col, row = index % 4, index // 4
671
+ left, top = gap + col * (cell + gap), gap + row * (cell + title + gap)
672
+ draw.text((left + 4, top + 7), label, fill=(235, 235, 235), font=font)
673
+ image = Image.fromarray(np.rint(np.clip(rgb, 0.0, 1.0) * 255.0).astype(np.uint8), "RGB")
674
+ try:
675
+ resample = Image.Resampling.LANCZOS
676
+ except AttributeError:
677
+ resample = Image.LANCZOS
678
+ image.thumbnail((cell, cell), resample)
679
+ grid.paste(image, (left + (cell - image.width) // 2, top + title + (cell - image.height) // 2))
680
+ if error_text:
681
+ draw.rectangle((0, 0, grid.width - 1, grid.height - 1), outline=(255, 64, 64), width=5)
682
+ return np.asarray(grid, dtype=np.float32) / 255.0
683
+
684
+
685
+ def _debug_outputs(background, canvas, state, status, error=False):
686
+ output = state["composite"]
687
+ weight, core, frame, selected = state["weight"], state["core"], state["frame"], state["selected"]
688
+ background_preview = checker_preview(background)
689
+ overlay_preview = checker_preview(canvas)
690
+ final_preview = checker_preview(output)
691
+ alpha_preview = _gray(canvas[..., 3])
692
+ weight_preview = _gray(weight)
693
+ constraints = np.zeros((*core.shape, 3), np.float32)
694
+ constraints[core] = (0.0, 0.7, 1.0)
695
+ constraints[frame] = (1.0, 0.25, 0.1)
696
+ constraints[(~core) & (~frame) & (selected | (weight > 0.0))] = (0.25, 0.25, 0.25)
697
+ seam = final_preview.copy()
698
+ seam_edge = selected ^ binary_erosion(selected, border_value=0)
699
+ core_edge = core ^ binary_erosion(core, border_value=0)
700
+ seam[seam_edge] = (0.0, 1.0, 0.0)
701
+ seam[core_edge] = (0.0, 0.7, 1.0)
702
+ panels = [
703
+ ("A Original background", background_preview),
704
+ ("B Aligner overlay canvas", overlay_preview),
705
+ ("C Overlay alpha (white=opaque)", alpha_preview),
706
+ ("D Blend weight (white=edited)", weight_preview),
707
+ ("E Core cyan / frame orange", constraints),
708
+ ("F Seam green / core cyan", seam),
709
+ ("G Simple source-over comparison", _source_over_debug(background, canvas)),
710
+ ("H Final replacement blend", final_preview),
711
+ ]
712
+ return {"composite_rgba": output, "composite_preview": final_preview,
713
+ "debug_grid": _debug_grid(panels, status if error else None),
714
+ "aligned_overlay_preview": overlay_preview, "overlay_alpha": alpha_preview,
715
+ "blend_weight": weight_preview, "seam_preview": seam,
716
+ "blend_mask": weight, "status": status, "ok": not error, "state": state}
717
+
718
+
719
+ def error_outputs(background, canvas, message):
720
+ try:
721
+ bg = _rgba_array(background, "background")
722
+ except Exception:
723
+ bg = np.zeros((256, 256, 4), np.float32)
724
+ bg[..., 3] = 1.0
725
+ try:
726
+ ov = _rgba_array(canvas, "overlay canvas")
727
+ except Exception:
728
+ ov = np.zeros_like(bg)
729
+ zeros = np.zeros(bg.shape[:2], np.float32)
730
+ state = {"composite": bg.copy(), "weight": zeros,
731
+ "core": zeros.astype(bool), "frame": zeros.astype(bool), "selected": zeros.astype(bool)}
732
+ status = "GPT_1 INPUT/BLEND ERROR: " + str(message) + "\nNo blend was applied; original background returned. Debug grid has a red border.\nRequired: ORIGINAL background + SAME aligner's overlay_canvas_rgba + SAME aligner's status."
733
+ return _debug_outputs(bg, ov, state, status, error=True)
734
+
735
+
736
+ def blend_from_aligner_arrays(background, overlay_canvas_rgba, alignment_status,
737
+ seam_band=48, feather_pixels=4, multiband=False,
738
+ background_mask=None, prompt=None, unique_id=None,
739
+ interrupt=lambda: None, progress=lambda value: None):
740
+ """Connect aligner outputs directly. Errors return diagnostic images/status."""
741
+ started = time.monotonic()
742
+ bg, canvas = background, overlay_canvas_rgba
743
+ try:
744
+ for name, value, lo, hi in (("seam_band", seam_band, 1, 4096),
745
+ ("feather_pixels", feather_pixels, 0, 256)):
746
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not lo <= value <= hi:
747
+ raise GPT1InputError("%s must be an integer in [%d,%d]." % (name, lo, hi))
748
+ if not isinstance(multiband, (bool, np.bool_)):
749
+ raise GPT1InputError("multiband must be a boolean.")
750
+ bg, alpha_source = _background_rgba(background, background_mask)
751
+ canvas = _canvas_rgba(overlay_canvas_rgba)
752
+ rectangle, expected = parse_alignment_status(alignment_status)
753
+ wiring = check_prompt_wiring(prompt, unique_id,
754
+ background_is_rgb=np.asarray(background).shape[-1] == 3)
755
+ source, coverage, bbox = _validate_canvas(bg, canvas, rectangle, expected)
756
+ interrupt()
757
+ state = _blend_verified_canvas(bg, canvas, rectangle, source, coverage, bbox,
758
+ seam_band, feather_pixels, multiband, interrupt, progress)
759
+ x, y, width, height = rectangle
760
+ notes = [
761
+ "GPT_1 OK: aligned canvas blended using OpenCV GraphCutSeamFinder.",
762
+ "Read automatically from aligner status: x=%.8f y=%.8f width=%.8f height=%.8f" % rectangle,
763
+ "Canvas mode is automatic. No coordinate inputs, overlay mode, overlay MASK, or mask inversion needed.",
764
+ _describe("Background", bg), _describe("Overlay canvas", canvas),
765
+ "Background alpha: " + alpha_source,
766
+ "Method=%s; seam_band=%d; feather_pixels=%d; graph=%dx%d; protected pixels=%d"
767
+ % (state["mode"], state["seam_band"], feather_pixels, *state["graph_shape"], int(state["core"].sum())),
768
+ "White blend weight means use the EDITED VERSION; it is NOT image alpha or an inverted Comfy transparency mask.",
769
+ "RGBA replacement keeps object alpha separate from the blend weight. Protected transparent edits may erase original pixels; identical fading edges do not become more opaque.",
770
+ "Seam cost uses black AND white composites plus gradient disagreement; a single gray matte would miss some alpha differences.",
771
+ *wiring,
772
+ "Debug grid: A background; B aligned overlay; C object alpha; D replacement weight; E constraints; F seam; G ordinary source-over; H final result.",
773
+ "seconds=%.3f" % (time.monotonic() - started),
774
+ ]
775
+ result = _debug_outputs(bg, canvas, state, "\n".join(notes))
776
+ progress(100)
777
+ return result
778
+ except Exception as exc:
779
+ # ComfyUI cancellation must remain cancellation, not become an error image.
780
+ if type(exc).__name__ == "InterruptProcessingException":
781
+ raise
782
+ _LOG.warning("Salia GPT_1 blend failed: %s", exc)
783
+ progress(100)
784
+ return error_outputs(bg, canvas, "%s: %s" % (type(exc).__name__, exc))
785
+
786
+
787
+ class Salia_Aligner_Seam_Blend_GPT_1:
788
+ @classmethod
789
+ def INPUT_TYPES(cls):
790
+ return {"required": {
791
+ "background": ("IMAGE", {"tooltip": "Branch the ORIGINAL background feeding the aligner. Do not use composite_rgba."}),
792
+ "overlay_canvas_rgba": ("IMAGE", {"tooltip": "Connect overlay_canvas_rgba directly from Salia Auto Align Overlay (Joint Registration + EWA)."}),
793
+ "alignment_status": ("STRING", {"forceInput": True,
794
+ "tooltip": "Connect status from the SAME aligner. Coordinates and placement are read automatically."}),
795
+ "seam_band": ("INT", {"default": 48, "min": 1, "max": 4096, "step": 1,
796
+ "tooltip": "Adjustable border in pixels. The edited center and original outer border are protected automatically."}),
797
+ "feather_pixels": ("INT", {"default": 4, "min": 0, "max": 256, "step": 1,
798
+ "tooltip": "Narrow smoothing across the content-aware seam; 0 gives a hard cut."}),
799
+ "multiband": ("BOOLEAN", {"default": False,
800
+ "tooltip": "Optional OpenCV multiband color correction inside the seam transition. Object alpha remains a replacement blend."}),
801
+ }, "optional": {
802
+ "background_mask": ("MASK", {"tooltip": "Only if background is RGB: branch the EXACT SAME background_mask feeding the aligner. Do not invert it. RGBA ignores this socket."}),
803
+ }, "hidden": {"prompt": "PROMPT", "unique_id": "UNIQUE_ID"}}
804
+
805
+ RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "MASK", "STRING")
806
+ RETURN_NAMES = ("composite_rgba", "composite_preview", "debug_grid", "aligned_overlay_preview",
807
+ "overlay_alpha", "blend_weight", "seam_preview", "blend_mask", "status")
808
+ FUNCTION = "blend"
809
+ CATEGORY = "Salia/Image"
810
+ DESCRIPTION = (
811
+ "GPT_1 adapter for the working Salia aligner. Three connections: original background, "
812
+ "overlay_canvas_rgba and status. Reads coordinates and assigns alpha/core/seam automatically. "
813
+ "OpenCV graph cut, optional multiband, real RGBA replacement, and labeled debug views."
814
+ )
815
+
816
+ def blend(self, background, overlay_canvas_rgba, alignment_status,
817
+ seam_band=48, feather_pixels=4, multiband=False, background_mask=None,
818
+ prompt=None, unique_id=None):
819
+ import torch
820
+ try:
821
+ from comfy.model_management import throw_exception_if_processing_interrupted as interrupt
822
+ except ImportError:
823
+ interrupt = lambda: None
824
+ try:
825
+ from comfy.utils import ProgressBar
826
+ bar = ProgressBar(100)
827
+ progress = lambda value: bar.update_absolute(int(value), 100)
828
+ except ImportError:
829
+ progress = lambda value: None
830
+
831
+ def single(value, name):
832
+ if (not isinstance(value, torch.Tensor) or value.ndim != 4
833
+ or value.shape[0] != 1 or not value.is_floating_point()):
834
+ raise GPT1InputError("%s must be one floating IMAGE shaped [1,H,W,C]." % name)
835
+ return value[0].detach().to(device="cpu", dtype=torch.float32).numpy()
836
+
837
+ bg, canvas = None, None
838
+ with torch.inference_mode():
839
+ try:
840
+ bg = single(background, "background")
841
+ canvas = single(overlay_canvas_rgba, "overlay_canvas_rgba")
842
+ mask = None
843
+ if bg.shape[-1] == 3 and background_mask is not None:
844
+ if not isinstance(background_mask, torch.Tensor):
845
+ raise GPT1InputError("background_mask must be the same MASK tensor used by the aligner.")
846
+ mask = background_mask.detach().to(device="cpu", dtype=torch.float32).numpy()
847
+ result = blend_from_aligner_arrays(
848
+ bg, canvas, alignment_status, seam_band, feather_pixels, multiband,
849
+ background_mask=mask, prompt=prompt, unique_id=unique_id,
850
+ interrupt=interrupt, progress=progress)
851
+ except Exception as exc:
852
+ if type(exc).__name__ == "InterruptProcessingException":
853
+ raise
854
+ result = error_outputs(bg, canvas, "%s: %s" % (type(exc).__name__, exc))
855
+ names = ("composite_rgba", "composite_preview", "debug_grid", "aligned_overlay_preview",
856
+ "overlay_alpha", "blend_weight", "seam_preview", "blend_mask")
857
+ tensors = tuple(torch.from_numpy(np.ascontiguousarray(result[name], dtype=np.float32)).unsqueeze(0)
858
+ for name in names)
859
+ return (*tensors, result["status"])
860
+
861
+
862
+ NODE_CLASS_MAPPINGS = {"Salia_Aligner_Seam_Blend_GPT_1": Salia_Aligner_Seam_Blend_GPT_1}
863
+ NODE_DISPLAY_NAME_MAPPINGS = {"Salia_Aligner_Seam_Blend_GPT_1": "Salia Aligner Seam Blend GPT_1"}