saliacoel commited on
Commit
248736e
·
verified ·
1 Parent(s): 4eab2df

Upload Salia_Auto_Align_Seam_Blend_GPT_1.py

Browse files
Files changed (1) hide show
  1. Salia_Auto_Align_Seam_Blend_GPT_1.py +1634 -0
Salia_Auto_Align_Seam_Blend_GPT_1.py ADDED
@@ -0,0 +1,1634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Salia Auto Align + Seam Blend GPT_1 -- self-contained ComfyUI node, v1.0
3
+ ====================================================================
4
+ Install ONLY this Python file in ComfyUI/custom_nodes/, restart, and add
5
+ "Salia Auto Align + Seam Blend GPT_1" from Salia/Image.
6
+
7
+ This node takes the SAME INPUTS as the supplied working Salia Auto Align
8
+ Overlay node, plus seam_band, feather_pixels and multiband. It contains its
9
+ own full crop locator, continuous registration, EWA renderer and blender.
10
+ No other Salia Python files, upstream alignment nodes, coordinates, status
11
+ strings or previously rendered images are required.
12
+
13
+ Connect your THREE ORIGINAL SOURCE IMAGES:
14
+ background : full original background
15
+ overlay : original, unscaled edited replacement rectangle
16
+ Unedited_Rect : original crop before editing, used to find its position
17
+
18
+ For standard Comfy Load Image nodes, connect each IMAGE to its image input
19
+ and its corresponding MASK directly to background_mask, overlay_mask or
20
+ Unedited_Rect_mask. Do NOT invert these MASKs. Native four-channel RGBA uses
21
+ embedded alpha and ignores external masks, exactly like the working aligner.
22
+ RGB without a MASK is opaque; Comfy's zero 64x64 placeholder is supported.
23
+ One image per input; split batches upstream.
24
+
25
+ All original alignment widgets/defaults are retained:
26
+ target_width=0, target_height=0 (0 uses crop size), max_evaluations=100,
27
+ pyramid_levels=3, robust_threshold=0.05, scale_limit=2.0, min_tolerance=0.9.
28
+ The highest-scoring crop match is found before applying min_tolerance.
29
+ Alignment uses the exact verified source logic: masked FFT location,
30
+ continuous four-parameter robust registration, original-source EWA LanczosSharp.
31
+ The resulting rectangle, placed canvas, coverage and alpha pass DIRECTLY to
32
+ blending as internal arrays/geometry. No status-text parsing or graph lookup.
33
+
34
+ Additional blend widgets:
35
+ seam_band=48: adjustable border; edited center and original frame protected.
36
+ feather_pixels=4: narrow smoothing across the chosen content-aware seam.
37
+ multiband=False: optional existing OpenCV color blending in the transition.
38
+ GraphCutSeamFinder compares appearance over BOTH black and white plus
39
+ gradient disagreement. Blend in premultiplied linear RGB, keeping object
40
+ alpha, rectangle coverage and replacement weight separate. Unchanged fading
41
+ edges do not get stacked twice. Protected transparent edits can erase old
42
+ pixels. Outside the edited rectangle, original pixels stay exactly intact.
43
+
44
+ Outputs (first 10 follow the working aligner's layout):
45
+ composite_rgba : final BLENDED RGBA; save this image
46
+ overlay_canvas_rgba : internally aligned overlay on background-size canvas
47
+ status : crop, geometry, input alpha, blending and diagnostics
48
+ x/y/width/height, center_x/center_y, similarity: fitted geometry and score
49
+ Additional debugging outputs:
50
+ debug_grid : eight labeled panels; connect Preview Image
51
+ composite_preview : final result over checkerboard (opaque preview)
52
+ aligned_overlay_preview, overlay_alpha (white=opaque), blend_weight
53
+ seam_preview : green seam, cyan protected-center boundary
54
+ blend_mask : MASK, white=edited replacement, not object alpha
55
+ aligned_composite_rgba : ordinary source-over BEFORE seam blending
56
+ crop_similarity : original-crop match score, 0..200
57
+ Checkerboards and annotation colors are only previews, not final PNG pixels.
58
+
59
+ On failed crop acceptance, return original RGBA, empty aligned canvas, zero
60
+ blend mask, x/y=-1 and dimensions=0, plus explicit status/debug images.
61
+ Other input/blend errors also return diagnostics and preserve the background
62
+ when it is valid. Cancellation propagates. This file writes nothing at runtime.
63
+
64
+ Dependencies: NumPy, SciPy, Pillow, PyTorch (normally present in ComfyUI),
65
+ and OpenCV's stitching module. If OpenCV is missing, install using Comfy's
66
+ Python environment: python -m pip install opencv-python-headless
67
+ An existing working cv2 installation does not need replacement.
68
+
69
+ Numerical/API references:
70
+ https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html
71
+ https://docs.opencv.org/4.x/db/dda/classcv_1_1detail_1_1GraphCutSeamFinder.html
72
+ https://docs.opencv.org/4.x/d5/d4b/classcv_1_1detail_1_1MultiBandBlender.html
73
+ """
74
+ from __future__ import annotations
75
+ import math
76
+ from functools import lru_cache
77
+ from typing import Callable, Tuple
78
+ import numpy as np
79
+ from scipy import sparse
80
+ from scipy.special import j1, jn_zeros
81
+ _MODES = ("EWA LanczosSharp", "EWA LanczosRadius / Jinc-Jinc")
82
+ _PAIR_BUDGET = 262144
83
+ _LUT_INTERVALS = 65536
84
+ _ALPHA_EPSILON = 1.0e-8
85
+
86
+ def _to_linear(rgb: np.ndarray) -> np.ndarray:
87
+ return np.where(
88
+ rgb <= 0.04045,
89
+ rgb / 12.92,
90
+ np.power((rgb + 0.055) / 1.055, 2.4),
91
+ ).astype(np.float32, copy=False)
92
+
93
+ def _to_srgb(rgb: np.ndarray) -> np.ndarray:
94
+ rgb = np.clip(rgb, 0.0, 1.0)
95
+ return np.where(
96
+ rgb <= 0.0031308,
97
+ rgb * 12.92,
98
+ 1.055 * np.power(rgb, 1.0 / 2.4) - 0.055,
99
+ ).astype(np.float32, copy=False)
100
+
101
+ def _prepare_image(source: np.ndarray) -> np.ndarray:
102
+ if not np.isfinite(source).all():
103
+ raise ValueError("Salia_Rescale_Image: image contains NaN or infinity.")
104
+ image = np.clip(source, 0.0, 1.0).astype(np.float32, copy=True)
105
+ image[..., :3] = _to_linear(image[..., :3])
106
+ if image.shape[-1] == 4:
107
+ image[..., :3] *= image[..., 3:4]
108
+ return image
109
+
110
+ def _finish_image(filtered: np.ndarray, channels: int) -> np.ndarray:
111
+ filtered = np.asarray(filtered, dtype=np.float32)
112
+ rgb = filtered[..., :3]
113
+ if channels == 4:
114
+ raw_alpha = filtered[..., 3:4]
115
+ visible = raw_alpha > _ALPHA_EPSILON
116
+ # Divide by the ORIGINAL filtered alpha, before clipping alpha.
117
+ # Negative-lobe filters can overshoot 1; clipping before division
118
+ # would alter the color of those pixels.
119
+ straight_rgb = np.zeros_like(rgb)
120
+ np.divide(rgb, raw_alpha, out=straight_rgb, where=visible)
121
+ rgb = _to_srgb(straight_rgb)
122
+ alpha = np.where(visible, np.clip(raw_alpha, 0.0, 1.0), 0.0)
123
+ result = np.concatenate((rgb, alpha), axis=-1)
124
+ else:
125
+ result = _to_srgb(rgb)
126
+ return np.ascontiguousarray(np.clip(result, 0.0, 1.0), dtype=np.float32)
127
+
128
+ def _jinc(x: np.ndarray) -> np.ndarray:
129
+ # Normalized Jinc = 2 * J1(pi*x) / (pi*x), with value 1 at zero.
130
+ z = math.pi * np.asarray(x, dtype=np.float64)
131
+ result = np.ones_like(z)
132
+ np.divide(2.0 * j1(z), z, out=result, where=np.abs(z) > 1.0e-12)
133
+ return result
134
+
135
+ @lru_cache(maxsize=2)
136
+ def _ewa_definition(mode: str) -> Tuple[float, np.ndarray, float]:
137
+ first_zero, _, third_zero = jn_zeros(1, 3) / math.pi
138
+ if mode == _MODES[0]:
139
+ blur = 0.9812505644269356
140
+ elif mode == _MODES[1]:
141
+ blur = 3.0 / third_zero
142
+ else:
143
+ raise ValueError("Unknown EWA mode: " + str(mode))
144
+ radius = float(third_zero * blur)
145
+ squared_radius = radius * radius
146
+ # A uniform table in squared distance avoids per-weight square roots.
147
+ squared_distances = np.linspace(0.0, squared_radius, _LUT_INTERVALS + 1)
148
+ r = np.sqrt(squared_distances) / blur
149
+ table = _jinc(r) * _jinc(r * first_zero / third_zero)
150
+ table[-1] = 0.0
151
+ # Duplicate endpoint makes interpolation at/outside support safe.
152
+ table = np.concatenate((table, np.zeros(1, dtype=np.float64)))
153
+ table.setflags(write=False)
154
+ return radius, table, _LUT_INTERVALS / squared_radius
155
+
156
+ def _lookup_ewa(squared_distance: np.ndarray, table: np.ndarray,
157
+ table_scale: float) -> np.ndarray:
158
+ position = np.minimum(squared_distance * table_scale, float(_LUT_INTERVALS))
159
+ index = position.astype(np.intp)
160
+ fraction = position - index
161
+ return table[index] + fraction * (table[index + 1] - table[index])
162
+
163
+ def _ewa_axis(source_size: int, target_size: int,
164
+ radius: float) -> Tuple[np.ndarray, np.ndarray]:
165
+ ratio = source_size / target_size
166
+ footprint_scale = max(1.0, ratio)
167
+ support = radius * footprint_scale
168
+ centers = (np.arange(target_size, dtype=np.float64) + 0.5) * ratio - 0.5
169
+ # All source indices with nonzero support fit in this fixed-width table.
170
+ count = min(source_size, int(math.ceil(2.0 * support)) + 1)
171
+ starts = np.maximum(0, np.ceil(centers - support).astype(np.int64))
172
+ raw_indices = starts[:, None] + np.arange(count, dtype=np.int64)[None, :]
173
+ squared_distance = ((raw_indices - centers[:, None]) / footprint_scale) ** 2
174
+ valid = (raw_indices < source_size) & (squared_distance < radius * radius)
175
+ # Infinity is deliberately mapped to the zero endpoint of the lookup table.
176
+ squared_distance[~valid] = np.inf
177
+ indices = np.minimum(raw_indices, source_size - 1).astype(np.int32)
178
+ return indices, squared_distance
179
+
180
+ def _resize_ewa(image: np.ndarray, out_width: int, out_height: int,
181
+ definition: Tuple[float, np.ndarray, float],
182
+ x_axis: Tuple[np.ndarray, np.ndarray],
183
+ y_axis: Tuple[np.ndarray, np.ndarray],
184
+ interrupt: Callable[[], None],
185
+ progress: Callable[[float], None]) -> np.ndarray:
186
+ _, table, table_scale = definition
187
+ in_height, in_width, channels = image.shape
188
+ x_indices, x_squared = x_axis
189
+ y_indices, y_squared = y_axis
190
+ nx, ny = x_indices.shape[1], y_indices.shape[1]
191
+ total_pixels = out_width * out_height
192
+ output = np.empty((total_pixels, channels), dtype=np.float32)
193
+ # Match the float64 weights once; otherwise SciPy may repeatedly upcast
194
+ # the complete source image for every output tile.
195
+ source_flat = np.ascontiguousarray(image, dtype=np.float64).reshape(-1, channels)
196
+ pixel_block = max(1, min(2048, _PAIR_BUDGET // max(1, nx * ny)))
197
+ index_dtype = np.int32 if in_width * in_height < 2**31 else np.int64
198
+
199
+ for begin in range(0, total_pixels, pixel_block):
200
+ interrupt()
201
+ end = min(begin + pixel_block, total_pixels)
202
+ output_pixels = np.arange(begin, end, dtype=np.int64)
203
+ oy, ox = np.divmod(output_pixels, out_width)
204
+ count = end - begin
205
+ weighted_sum = np.zeros((count, channels), dtype=np.float64)
206
+ weight_sum = np.zeros(count, dtype=np.float64)
207
+ # Also tile source taps, so even a huge reduction to 1x1 doesn't
208
+ # allocate one enormous output_pixels x source_pixels weight array.
209
+ x_chunk = min(nx, max(1, _PAIR_BUDGET // count))
210
+ y_chunk = min(ny, max(1, _PAIR_BUDGET // (count * x_chunk)))
211
+
212
+ for ys in range(0, ny, y_chunk):
213
+ ye = min(ys + y_chunk, ny)
214
+ yi = y_indices[oy, ys:ye]
215
+ dy = y_squared[oy, ys:ye]
216
+ for xs in range(0, nx, x_chunk):
217
+ interrupt()
218
+ xe = min(xs + x_chunk, nx)
219
+ xi = x_indices[ox, xs:xe]
220
+ dx = x_squared[ox, xs:xe]
221
+ distance = dy[:, :, None] + dx[:, None, :]
222
+ weights = _lookup_ewa(distance, table, table_scale)
223
+ taps_per_pixel = (ye - ys) * (xe - xs)
224
+ flat_weights = weights.reshape(count, taps_per_pixel)
225
+ weight_sum += flat_weights.sum(axis=1)
226
+ source_indices = (
227
+ yi.astype(np.int64)[:, :, None] * in_width
228
+ + xi[:, None, :]
229
+ ).astype(index_dtype, copy=False)
230
+ row_pointers = np.arange(count + 1, dtype=np.int64) * taps_per_pixel
231
+ # Sparse multiply avoids materializing a large [pixel,tap,RGBA]
232
+ # gather. Each row is one target pixel's full 2-D footprint.
233
+ operator = sparse.csr_matrix(
234
+ (weights.ravel(), source_indices.ravel(), row_pointers),
235
+ shape=(count, in_width * in_height),
236
+ )
237
+ weighted_sum += operator @ source_flat
238
+ if not np.isfinite(weight_sum).all() or np.any(np.abs(weight_sum) < 1.0e-12):
239
+ raise RuntimeError("Salia_Rescale_Image: degenerate EWA normalization.")
240
+ output[begin:end] = weighted_sum / weight_sum[:, None]
241
+ progress(end / total_pixels)
242
+ return output.reshape(out_height, out_width, channels)
243
+
244
+ class EwaLanczosSharpResizer:
245
+ """Resample each requested size from the original prepared source.
246
+
247
+ Color preparation happens once. No candidate is resized from a previous
248
+ candidate. Axis tables are cheap and computed for each requested size.
249
+ The caller can cache finished candidate images when useful.
250
+ """
251
+ def __init__(self, source: np.ndarray, interrupt: Callable[[], None] = lambda: None):
252
+ source = np.asarray(source)
253
+ if source.ndim != 3 or source.shape[2] not in (3, 4) or min(source.shape[:2]) < 1:
254
+ raise ValueError("EWA source must be a nonempty HWC RGB/RGBA array.")
255
+ if not np.isfinite(source).all():
256
+ raise ValueError("EWA source contains NaN or infinity.")
257
+ self.source = np.ascontiguousarray(source, dtype=np.float32)
258
+ self.prepared = _prepare_image(self.source)
259
+ self.definition = _ewa_definition(_MODES[0])
260
+ self.interrupt = interrupt
261
+
262
+ def resize(self, width: int, height: int) -> np.ndarray:
263
+ if width < 1 or height < 1:
264
+ raise ValueError("EWA dimensions must be positive.")
265
+ self.interrupt()
266
+ if (int(width), int(height)) == (self.source.shape[1], self.source.shape[0]):
267
+ return self.source.copy()
268
+ radius = self.definition[0]
269
+ x_axis = _ewa_axis(self.source.shape[1], int(width), radius)
270
+ y_axis = _ewa_axis(self.source.shape[0], int(height), radius)
271
+ filtered = _resize_ewa(
272
+ self.prepared, int(width), int(height), self.definition,
273
+ x_axis, y_axis, self.interrupt, lambda value: None,
274
+ )
275
+ self.interrupt()
276
+ return _finish_image(filtered, self.source.shape[2])
277
+
278
+
279
+ def resize_rgba_ewa(source: np.ndarray, width: int, height: int,
280
+ interrupt: Callable[[], None] = lambda: None) -> np.ndarray:
281
+ """Standalone original-source EWA LanczosSharp resize (RGB or RGBA)."""
282
+ return EwaLanczosSharpResizer(source, interrupt).resize(width, height)
283
+
284
+
285
+
286
+ import logging
287
+ import time
288
+ from scipy.signal import correlate
289
+ __version__ = "2.2.0"
290
+ _LOG = logging.getLogger(__name__)
291
+ _MAX_DIMENSION = 32768
292
+ _RGB_COPY_ERROR_TOLERANCE = 1.0e-6
293
+
294
+ def _rgba_array(image, name="image"):
295
+ """Private normalized float32 copy; hidden RGB is retained but never scored."""
296
+ result = np.asarray(image)
297
+ if result.ndim != 3 or result.shape[-1] not in (3, 4):
298
+ raise ValueError("%s must be HWC RGB or RGBA." % name)
299
+ if min(result.shape[:2]) < 1:
300
+ raise ValueError("%s is empty." % name)
301
+ if not np.issubdtype(result.dtype, np.floating):
302
+ raise ValueError("%s must contain floating-point values in [0, 1]." % name)
303
+ if not np.isfinite(result).all():
304
+ raise ValueError("%s contains NaN or infinity." % name)
305
+ result = np.clip(result, 0.0, 1.0).astype(np.float32, copy=True)
306
+ if result.shape[-1] == 3:
307
+ result = np.concatenate((result, np.ones((*result.shape[:2], 1), np.float32)), axis=-1)
308
+ return np.ascontiguousarray(result)
309
+
310
+ def _weights(template):
311
+ alpha = template[..., 3].astype(np.float64)
312
+ return np.where(alpha > _ALPHA_EPSILON, alpha, 0.0)
313
+
314
+ def _color_error(background, template):
315
+ # Straight sRGB, not premultiplied RGB: half-alpha green can match green.
316
+ delta = background[..., :3].astype(np.float64) - template[..., :3]
317
+ error = np.mean(delta * delta, axis=-1)
318
+ return np.where(background[..., 3] > _ALPHA_EPSILON, error, 1.0)
319
+
320
+ def GET_RECTS_SIMILARITY(rect1, rect2, template_mode=False):
321
+ """Compare equal-size HWC float RGB/RGBA rectangles; return 0..200.
322
+
323
+ Default is symmetric: weight by max(alpha1, alpha2); RGB differences
324
+ count only when BOTH pixels are visible. A visible/invisible pair has
325
+ maximum error. If both pixels are invisible, hidden RGB is irrelevant.
326
+ Positive alpha magnitudes are confidence weights, not color darkness.
327
+ Thus solid green at alpha .5 and at alpha 1 have similarity 200.
328
+
329
+ template_mode=True is directional: rect1 is background; rect2 is the
330
+ template. Only rect2 alpha weights the score, so its transparent padding
331
+ does not punish a visible background. Used for locating and refining.
332
+ A fully transparent template raises ValueError (no matching evidence).
333
+ """
334
+ a, b = _rgba_array(rect1, "rect1"), _rgba_array(rect2, "rect2")
335
+ if a.shape != b.shape:
336
+ raise ValueError("GET_RECTS_SIMILARITY requires equal rectangle dimensions.")
337
+ if template_mode:
338
+ weight = _weights(b)
339
+ total = float(weight.sum())
340
+ if total <= 0.0:
341
+ raise ValueError("A fully transparent template has no matching information.")
342
+ error = float(np.sum(weight * _color_error(a, b)) / total)
343
+ else:
344
+ aa, ba = _weights(a), _weights(b)
345
+ weight = np.maximum(aa, ba)
346
+ total = float(weight.sum())
347
+ if total <= 0.0:
348
+ return 200.0
349
+ visible_both = (aa > 0.0) & (ba > 0.0)
350
+ delta = a[..., :3].astype(np.float64) - b[..., :3]
351
+ pixel_error = np.where(visible_both, np.mean(delta * delta, axis=-1), 1.0)
352
+ error = float(np.sum(weight * pixel_error) / total)
353
+ return float(200.0 * (1.0 - np.clip(error, 0.0, 1.0)))
354
+
355
+ def _overlap(background, template, x, y):
356
+ bh, bw = background.shape[:2]
357
+ th, tw = template.shape[:2]
358
+ x0, y0 = max(0, x), max(0, y)
359
+ x1, y1 = min(bw, x + tw), min(bh, y + th)
360
+ if x1 <= x0 or y1 <= y0:
361
+ return None
362
+ return (slice(y0, y1), slice(x0, x1),
363
+ slice(y0 - y, y1 - y), slice(x0 - x, x1 - x))
364
+
365
+ def _error_at(background, template, x, y, respect_background_alpha=True):
366
+ """Full template normalization: clipping outside the canvas cannot win."""
367
+ weight = _weights(template)
368
+ total = float(weight.sum())
369
+ if total <= 0.0:
370
+ return float("inf")
371
+ overlap = _overlap(background, template, x, y)
372
+ if overlap is None:
373
+ return 1.0
374
+ by, bx, ty, tx = overlap
375
+ inside_weight = weight[ty, tx]
376
+ # Off-canvas visible pixels are maximum mismatch, not discarded samples.
377
+ outside_error = max(0.0, total - float(inside_weight.sum()))
378
+ if respect_background_alpha:
379
+ pixel_error = _color_error(background[by, bx], template[ty, tx])
380
+ else:
381
+ delta = background[by, bx, :3].astype(np.float64) - template[ty, tx, :3]
382
+ pixel_error = np.mean(delta * delta, axis=-1)
383
+ inside_error = np.sum(inside_weight * pixel_error)
384
+ return float(np.clip((outside_error + inside_error) / total, 0.0, 1.0))
385
+
386
+ def _locate_unedited(background, template, interrupt=lambda: None, respect_background_alpha=True):
387
+ """Evaluate every fully-contained placement using weighted RGB SSD.
388
+
389
+ FFT correlation is an algebraic acceleration of the SAME per-pixel
390
+ error. No image pyramid, approximate search, or reduced-resolution crop.
391
+ Re-evaluate near-best candidates directly to remove FFT roundoff.
392
+ """
393
+ bh, bw = background.shape[:2]
394
+ th, tw = template.shape[:2]
395
+ if tw > bw or th > bh:
396
+ raise ValueError("Unedited_Rect is larger than background; it cannot be a crop of it.")
397
+ weight = _weights(template)
398
+ total = float(weight.sum())
399
+ if total <= 0.0:
400
+ raise ValueError("Unedited_Rect is fully transparent; its position cannot be located.")
401
+ visible = ((background[..., 3] > _ALPHA_EPSILON).astype(np.float64)
402
+ if respect_background_alpha else np.ones((bh, bw), dtype=np.float64))
403
+ if not np.any(visible):
404
+ # Every placement has the same maximum appearance error. Avoid
405
+ # directly rescoring every all-transparent location in a large image.
406
+ return 0, 0, 1.0, (bh - th + 1) * (bw - tw + 1)
407
+ rgb = background[..., :3].astype(np.float64)
408
+ template_rgb = template[..., :3].astype(np.float64)
409
+
410
+ def corr(a, b):
411
+ interrupt()
412
+ result = correlate(a, b, mode="valid", method="fft")
413
+ interrupt()
414
+ return result
415
+
416
+ background_square = np.mean(rgb * rgb, axis=-1)
417
+ template_square = np.mean(template_rgb * template_rgb, axis=-1)
418
+ if np.all(visible):
419
+ errors = corr(background_square, weight)
420
+ errors += float(np.sum(weight * template_square))
421
+ for channel in range(3):
422
+ errors -= (2.0 / 3.0) * corr(rgb[..., channel], weight * template_rgb[..., channel])
423
+ else:
424
+ errors = corr(1.0 - visible + visible * background_square, weight)
425
+ errors += corr(visible, weight * template_square)
426
+ for channel in range(3):
427
+ errors -= (2.0 / 3.0) * corr(visible * rgb[..., channel], weight * template_rgb[..., channel])
428
+ errors /= total
429
+ np.clip(errors, 0.0, 1.0, out=errors)
430
+ minimum = float(errors.min())
431
+ near_best = np.flatnonzero(errors.ravel() <= minimum + 1.0e-12)
432
+ # Never drop a possible best match because many low-contrast positions
433
+ # share a near-equal FFT score. Check the earliest candidate and the FFT
434
+ # argmin first, then every remaining near-best candidate if necessary.
435
+ # A directly verified EXACT zero is the mathematical lower bound, so
436
+ # only that allows early exit. Uniform duplicate crops stop immediately.
437
+ fft_best = int(np.argmin(errors))
438
+ first = int(near_best[0])
439
+ candidates = (first, fft_best)
440
+ best_error, best_x, best_y = float("inf"), 0, 0
441
+ from itertools import chain
442
+ for flat in chain(candidates, (int(k) for k in near_best if k != first and k != fft_best)):
443
+ interrupt()
444
+ y, x = divmod(int(flat), errors.shape[1])
445
+ error = _error_at(background, template, x, y, respect_background_alpha)
446
+ if error < best_error:
447
+ best_error, best_x, best_y = error, x, y
448
+ if best_error == 0.0:
449
+ break
450
+ return best_x, best_y, best_error, int(near_best.size)
451
+
452
+ def _source_over(background, template, x, y):
453
+ """Straight-alpha source-over in sRGB; only the pasted region changes."""
454
+ composite = background.copy()
455
+ canvas = np.zeros_like(background)
456
+ overlap = _overlap(background, template, x, y)
457
+ if overlap is None:
458
+ return composite, canvas
459
+ by, bx, ty, tx = overlap
460
+ source, target = template[ty, tx], background[by, bx]
461
+ canvas[by, bx] = source
462
+ source_alpha, target_alpha = source[..., 3:4], target[..., 3:4]
463
+ alpha = source_alpha + target_alpha * (1.0 - source_alpha)
464
+ premultiplied = (source[..., :3] * source_alpha
465
+ + target[..., :3] * target_alpha * (1.0 - source_alpha))
466
+ rgb = np.zeros_like(premultiplied)
467
+ np.divide(premultiplied, alpha, out=rgb, where=alpha > _ALPHA_EPSILON)
468
+ result = np.concatenate((np.clip(rgb, 0.0, 1.0), alpha), axis=-1)
469
+ # Preserve the background exactly under fully transparent overlay pixels.
470
+ composite[by, bx] = np.where(source_alpha > 0.0, result, target)
471
+ # Canonical invisible RGB on the otherwise empty overlay canvas.
472
+ canvas[..., :3][canvas[..., 3] <= 0.0] = 0.0
473
+ return composite, canvas
474
+
475
+ def _tensor_image(image, name, mask=None):
476
+ import torch
477
+ if not isinstance(image, torch.Tensor) or image.ndim != 4 or image.shape[0] != 1:
478
+ raise ValueError("%s must be one IMAGE shaped [1,H,W,3 or 4]; split batches first." % name)
479
+ if not image.is_floating_point():
480
+ raise ValueError("%s must be a floating-point IMAGE." % name)
481
+ result = _rgba_array(image[0].detach().to(device="cpu", dtype=torch.float32).numpy(), name)
482
+ # Embedded alpha is authoritative for RGBA. Do not replace, multiply or
483
+ # invert it through the external MASK, even if that mask is connected.
484
+ if int(image.shape[-1]) == 4:
485
+ return result
486
+ if mask is not None:
487
+ if not isinstance(mask, torch.Tensor):
488
+ raise ValueError("%s_mask must be a ComfyUI MASK tensor." % name)
489
+ value = mask.detach().to(device="cpu", dtype=torch.float32).numpy()
490
+ if value.ndim == 3 and value.shape[0] == 1:
491
+ value = value[0]
492
+ if value.shape != result.shape[:2]:
493
+ # Standard Load Image's no-alpha placeholder is a 64x64 all-zero
494
+ # MASK even when its RGB image has another resolution.
495
+ if value.shape == (64, 64) and not np.any(value):
496
+ value = np.zeros(result.shape[:2], dtype=np.float32)
497
+ else:
498
+ raise ValueError("%s_mask resolution must match %s. Masks are not resized." % (name, name))
499
+ if not np.isfinite(value).all():
500
+ raise ValueError("%s_mask contains NaN or infinity." % name)
501
+ # RGB has no alpha: reconstruct it from the Comfy Load Image MASK.
502
+ result[..., 3] = 1.0 - np.clip(value, 0.0, 1.0)
503
+ # Preserve the fact that RGB had NO alpha. Promoting it here used to erase
504
+ # that information before crop-location diagnostics and recovery.
505
+ if mask is None and int(image.shape[-1]) == 3:
506
+ return np.ascontiguousarray(result[..., :3])
507
+ return result
508
+
509
+ # ---------------------------------------------------------------------------
510
+ # Original-source EWA rendering with continuous rectangle geometry.
511
+ # The numerical filter/color helpers above are intentionally shared with the
512
+ # supplied Salia_Rescale_Image implementation. There is no second resize pass.
513
+ # ---------------------------------------------------------------------------
514
+
515
+ def _ewa_axis_at_centers(source_size, centers, source_per_output_pixel, radius):
516
+ """EWA source taps for arbitrary source-coordinate pixel centers.
517
+
518
+ ``centers`` are source pixel-center coordinates (first center is zero).
519
+ Footprint widening uses the continuous source/output scale, independent
520
+ of how many destination pixels happen to survive canvas clipping.
521
+ """
522
+ centers = np.asarray(centers, dtype=np.float64)
523
+ footprint = max(1.0, float(source_per_output_pixel))
524
+ support = radius * footprint
525
+ count = min(int(source_size), int(math.ceil(2.0 * support)) + 1)
526
+ starts = np.maximum(0, np.ceil(centers - support).astype(np.int64))
527
+ raw_indices = starts[:, None] + np.arange(count, dtype=np.int64)[None, :]
528
+ squared_distance = ((raw_indices - centers[:, None]) / footprint) ** 2
529
+ valid = (raw_indices < source_size) & (squared_distance < radius * radius)
530
+ squared_distance[~valid] = np.inf
531
+ indices = np.minimum(raw_indices, source_size - 1).astype(np.int32)
532
+ return indices, squared_distance
533
+
534
+
535
+ def render_rgba_ewa(source, background_width, background_height,
536
+ center_x, center_y, width, height, interrupt=lambda: None):
537
+ """Render a continuous RGBA rectangle from its original source, once.
538
+
539
+ Return ``(patch_rgba, x0, y0)``. ``x0/y0`` are integer pixel-edge canvas
540
+ coordinates; ``patch_rgba`` contains only the clipped destination bbox.
541
+ The requested rectangle has floating pixel-edge bounds
542
+ ``[center_x-width/2, center_x+width/2]`` and corresponding Y bounds.
543
+ Destination pixel centers are inverse-mapped directly to the original
544
+ source. RGB filtering is linear-light and alpha-premultiplied. Source
545
+ edge taps are truncated and normalized just as in the original rescaler.
546
+
547
+ The fraction of a destination pixel covered by the rectangle multiplies
548
+ filtered alpha (not RGB). This antialiases fractional outer bounds without
549
+ darkening their straight RGB. Filtering and placement stay continuous;
550
+ width, height and position are never rounded to an integer transform.
551
+
552
+ For integer-aligned geometry the output is the original resizer's output
553
+ cropped to the background. Same-size integer-aligned requests are exact
554
+ no-ops on pixel values, including hidden RGB, matching that resizer.
555
+ Empty overlap returns float32 array ``(0,0,4)`` and a clipped origin.
556
+ """
557
+ interrupt()
558
+ source = np.asarray(source)
559
+ if (source.ndim != 3 or source.shape[-1] != 4
560
+ or min(source.shape[:2]) < 1
561
+ or not np.issubdtype(source.dtype, np.floating)):
562
+ raise ValueError("render_rgba_ewa expects a nonempty floating HWC RGBA image.")
563
+ geometry = np.asarray((center_x, center_y, width, height), dtype=np.float64)
564
+ if not np.isfinite(geometry).all() or width < 1.0 or height < 1.0:
565
+ raise ValueError("EWA rectangle geometry must be finite with width/height >= 1.")
566
+ if (isinstance(background_width, bool) or isinstance(background_height, bool)
567
+ or int(background_width) != background_width
568
+ or int(background_height) != background_height
569
+ or background_width < 1 or background_height < 1):
570
+ raise ValueError("EWA background dimensions must be positive integers.")
571
+ if not np.isfinite(source).all():
572
+ raise ValueError("EWA source contains NaN or infinity.")
573
+ source = np.ascontiguousarray(np.clip(source, 0.0, 1.0), dtype=np.float32)
574
+ bw, bh = int(background_width), int(background_height)
575
+ left, top = float(center_x - width / 2.0), float(center_y - height / 2.0)
576
+ right, bottom = left + float(width), top + float(height)
577
+ x0 = max(0, min(bw, int(math.floor(left))))
578
+ y0 = max(0, min(bh, int(math.floor(top))))
579
+ x1 = max(0, min(bw, int(math.ceil(right))))
580
+ y1 = max(0, min(bh, int(math.ceil(bottom))))
581
+ if x1 <= x0 or y1 <= y0:
582
+ return np.empty((0, 0, 4), dtype=np.float32), x0, y0
583
+ source_height, source_width = source.shape[:2]
584
+ if (float(width) == source_width and float(height) == source_height
585
+ and left == math.floor(left) and top == math.floor(top)):
586
+ return (source[y0 - int(top):y1 - int(top),
587
+ x0 - int(left):x1 - int(left)].copy(), x0, y0)
588
+
589
+ definition = _ewa_definition(_MODES[0])
590
+ ratio_x, ratio_y = source_width / float(width), source_height / float(height)
591
+ output_x = np.arange(x0, x1, dtype=np.float64)
592
+ output_y = np.arange(y0, y1, dtype=np.float64)
593
+ source_x = (output_x + 0.5 - left) * ratio_x - 0.5
594
+ source_y = (output_y + 0.5 - top) * ratio_y - 0.5
595
+ x_axis = _ewa_axis_at_centers(source_width, source_x, ratio_x, definition[0])
596
+ y_axis = _ewa_axis_at_centers(source_height, source_y, ratio_y, definition[0])
597
+ filtered = _resize_ewa(_prepare_image(source), x1 - x0, y1 - y0,
598
+ definition, x_axis, y_axis, interrupt, lambda value: None)
599
+ result = _finish_image(filtered, 4)
600
+ coverage_x = np.maximum(0.0, np.minimum(output_x + 1.0, right)
601
+ - np.maximum(output_x, left))
602
+ coverage_y = np.maximum(0.0, np.minimum(output_y + 1.0, bottom)
603
+ - np.maximum(output_y, top))
604
+ result[..., 3] *= (coverage_y[:, None] * coverage_x[None, :]).astype(np.float32)
605
+ result[..., :3][result[..., 3] <= 0.0] = 0.0
606
+ interrupt()
607
+ return np.ascontiguousarray(result, dtype=np.float32), x0, y0
608
+
609
+
610
+ # ---------------------------------------------------------------------------
611
+ # Joint continuous alpha-aware registration (X, Y, width and height together).
612
+ # ---------------------------------------------------------------------------
613
+
614
+ from scipy.ndimage import gaussian_filter, map_coordinates, spline_filter
615
+ from scipy.optimize import least_squares
616
+
617
+ _MATCH_MAX_SIDE = 768
618
+ _MATCH_MAX_SAMPLES = 20000
619
+
620
+
621
+ def _premultiplied_fields(image, sigma_y=0.0, sigma_x=0.0, with_valid=False):
622
+ """Float64 fields prevent hidden RGB leakage during blur/interpolation."""
623
+ alpha = image[..., 3].astype(np.float64)
624
+ fields = np.concatenate((image[..., :3].astype(np.float64) * alpha[..., None],
625
+ alpha[..., None]), axis=-1)
626
+ if with_valid:
627
+ fields = np.concatenate((fields, (alpha > _ALPHA_EPSILON)[..., None].astype(np.float64)), axis=-1)
628
+ if sigma_y > 0.0 or sigma_x > 0.0:
629
+ fields = gaussian_filter(fields, sigma=(sigma_y, sigma_x, 0.0), mode="nearest")
630
+ return fields
631
+
632
+
633
+ def _straight_fields(fields):
634
+ alpha = np.clip(fields[..., 3], 0.0, 1.0)
635
+ rgb = np.zeros_like(fields[..., :3])
636
+ np.divide(fields[..., :3], alpha[..., None], out=rgb,
637
+ where=alpha[..., None] > _ALPHA_EPSILON)
638
+ return np.clip(rgb, 0.0, 1.0), alpha
639
+
640
+
641
+ class _RegistrationLevel:
642
+ """Fixed source samples and confidence; moving support cannot erase error.
643
+
644
+ Parameter vector: normalized center offsets and log width/height ratios.
645
+ A custom SciPy soft-L1 loss applies alpha AFTER robustification, so alpha
646
+ is a confidence weight rather than an RGB channel or a brightness change.
647
+ """
648
+ def __init__(self, background, template, center_x, center_y, initial_width,
649
+ initial_height, factor, robust_threshold, interrupt, on_call):
650
+ self.center_x, self.center_y = float(center_x), float(center_y)
651
+ self.initial_width, self.initial_height = float(initial_width), float(initial_height)
652
+ self.background_height, self.background_width = background.shape[:2]
653
+ self.robust_threshold = float(robust_threshold)
654
+ self.interrupt, self.on_call = interrupt, on_call
655
+ self.calls = 0
656
+ sigma = 0.5 * factor if factor > 1 else 0.0
657
+ source_fields = _premultiplied_fields(template, sigma, sigma)
658
+ source_rgb, source_alpha = _straight_fields(source_fields)
659
+ valid = np.flatnonzero(source_alpha.ravel() > _ALPHA_EPSILON)
660
+ if not valid.size:
661
+ raise ValueError("The overlay has no visible samples at this matching resolution.")
662
+ budget = max(1024, _MATCH_MAX_SAMPLES // factor)
663
+ if valid.size > budget:
664
+ # A fixed seed/subset for this level: never change the samples as
665
+ # a function of the transform being tested.
666
+ valid = np.sort(np.random.default_rng(0).choice(valid, budget, replace=False))
667
+ sy, sx = np.divmod(valid, template.shape[1])
668
+ self.u = (sx.astype(np.float64) + 0.5) / template.shape[1] - 0.5
669
+ self.v = (sy.astype(np.float64) + 0.5) / template.shape[0] - 0.5
670
+ self.source_rgb = source_rgb.reshape(-1, 3)[valid]
671
+ confidence = source_alpha.ravel()[valid]
672
+ self.confidence = confidence / confidence.sum()
673
+ self.count = len(valid)
674
+ self.loss_weights = np.concatenate((np.repeat(self.confidence / 3.0, 3),
675
+ self.confidence, np.full(4, 1.0e-7)))
676
+
677
+ # Match antialiasing to the initial physical size, including a source
678
+ # registration-resolution cap. This pyramid is for fitting only;
679
+ # final output is rendered directly from the original overlay.
680
+ ratio_x = initial_width / template.shape[1]
681
+ ratio_y = initial_height / template.shape[0]
682
+ sigma_x = max(sigma * ratio_x, 0.35 * max(0.0, ratio_x - 1.0))
683
+ sigma_y = max(sigma * ratio_y, 0.35 * max(0.0, ratio_y - 1.0))
684
+ interrupt()
685
+ background_fields = _premultiplied_fields(background, sigma_y, sigma_x, with_valid=True)
686
+ # Cubic interpolation needs coefficients computed just once per level.
687
+ self.coefficients = [spline_filter(background_fields[..., c], order=3, mode="mirror")
688
+ for c in range(5)]
689
+ interrupt()
690
+
691
+ def geometry(self, p):
692
+ return (self.center_x + p[0] * self.initial_width,
693
+ self.center_y + p[1] * self.initial_height,
694
+ self.initial_width * math.exp(float(p[2])),
695
+ self.initial_height * math.exp(float(p[3])))
696
+
697
+ def differences(self, p):
698
+ self.interrupt()
699
+ center_x, center_y, width, height = self.geometry(p)
700
+ x = center_x + self.u * width - 0.5
701
+ y = center_y + self.v * height - 0.5
702
+ coordinates = np.vstack((y, x))
703
+ sampled = np.stack([map_coordinates(c, coordinates, order=3, mode="constant",
704
+ cval=0.0, prefilter=False)
705
+ for c in self.coefficients], axis=-1)
706
+ rgb, alpha = _straight_fields(sampled[..., :4])
707
+ visible = np.clip(sampled[..., 4], 0.0, 1.0)
708
+ visible = np.where(alpha > _ALPHA_EPSILON, visible, 0.0)
709
+ delta = (rgb - self.source_rgb) * visible[:, None]
710
+ # Retain every fixed source sample. Off-canvas/transparent reference
711
+ # samples carry a penalty instead of dropping out of the objective.
712
+ # Outside distance supplies a gradient back toward the canvas.
713
+ outside_x = np.maximum(-x, 0.0) + np.maximum(x - (self.background_width - 1), 0.0)
714
+ outside_y = np.maximum(-y, 0.0) + np.maximum(y - (self.background_height - 1), 0.0)
715
+ outside = (outside_x / max(1.0, self.initial_width * 0.1)
716
+ + outside_y / max(1.0, self.initial_height * 0.1))
717
+ missing = 1.0 - visible + outside
718
+ return delta, missing
719
+
720
+ def residual(self, p):
721
+ self.calls += 1
722
+ self.on_call(self.calls)
723
+ delta, missing = self.differences(p)
724
+ return np.concatenate((delta.ravel(), missing, np.asarray(p, dtype=np.float64)))
725
+
726
+ def loss(self, z):
727
+ root = np.sqrt(1.0 + z)
728
+ rho = np.vstack((2.0 * (root - 1.0), 1.0 / root, -0.5 / (root ** 3)))
729
+ rho *= self.loss_weights[None, :]
730
+ # Tiny quadratic preference for the original geometry breaks exact
731
+ # appearance ties; it is not part of the reported image similarity.
732
+ rho[0, -4:] = self.loss_weights[-4:] * z[-4:]
733
+ rho[1, -4:] = self.loss_weights[-4:]
734
+ rho[2, -4:] = 0.0
735
+ return rho
736
+
737
+ def cost(self, p):
738
+ residual = self.residual(p)
739
+ scale = self.robust_threshold
740
+ return float(0.5 * scale * scale * self.loss((residual / scale) ** 2)[0].sum())
741
+
742
+ def similarity(self, p):
743
+ delta, missing = self.differences(p)
744
+ error = np.sum(self.confidence * (np.mean(delta * delta, axis=-1) + missing * missing))
745
+ return float(200.0 * (1.0 - np.clip(error, 0.0, 1.0)))
746
+
747
+
748
+ def _validate_registration_options(target_width, target_height, max_evaluations,
749
+ pyramid_levels, robust_threshold, scale_limit, min_tolerance=0.9):
750
+ for name, value, lo, hi in (
751
+ ("target_width", target_width, 0, _MAX_DIMENSION),
752
+ ("target_height", target_height, 0, _MAX_DIMENSION),
753
+ ("max_evaluations", max_evaluations, 5, 1000),
754
+ ("pyramid_levels", pyramid_levels, 1, 5),
755
+ ):
756
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not lo <= value <= hi:
757
+ raise ValueError("%s must be an integer in [%d,%d]." % (name, lo, hi))
758
+ for name, value, lo, hi in (("robust_threshold", robust_threshold, 0.001, 1.0),
759
+ ("scale_limit", scale_limit, 1.01, 8.0),
760
+ ("min_tolerance", min_tolerance, 0.0, 1.0)):
761
+ if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
762
+ raise ValueError("%s must be a finite number in [%g,%g]." % (name, lo, hi))
763
+ if not math.isfinite(float(value)) or not lo <= value <= hi:
764
+ raise ValueError("%s must be a finite number in [%g,%g]." % (name, lo, hi))
765
+
766
+
767
+ def _input_alpha_description(name, rgba, input_channels):
768
+ alpha = rgba[..., 3]
769
+ transparent = float(np.mean(alpha <= _ALPHA_EPSILON) * 100.0)
770
+ opaque = float(np.mean(alpha >= 1.0 - _ALPHA_EPSILON) * 100.0)
771
+ return ("%s=%dx%d, input_channels=%d, alpha_zero=%.2f%%, alpha_opaque=%.2f%%"
772
+ % (name, rgba.shape[1], rgba.shape[0], input_channels, transparent, opaque))
773
+
774
+
775
+ def align_arrays(background, overlay, unedited_rect, target_width=0, target_height=0,
776
+ max_evaluations=100, pyramid_levels=3, robust_threshold=0.05,
777
+ scale_limit=2.0, interrupt=lambda: None, progress=lambda value: None,
778
+ min_tolerance=0.9):
779
+ """Locate the crop, jointly optimize four continuous values, then render.
780
+
781
+ No pixel-step grid, alternating move/scale phase, rotation, shear, or
782
+ optical flow. SciPy's bounded robust least-squares optimizer works on an
783
+ alpha-safe antialiased matching pyramid. EWA renders the original once.
784
+ """
785
+ started = time.monotonic()
786
+ _validate_registration_options(target_width, target_height, max_evaluations,
787
+ pyramid_levels, robust_threshold, scale_limit, min_tolerance)
788
+ min_crop_similarity = float(min_tolerance) * 200.0
789
+ raw_inputs = (background, overlay, unedited_rect)
790
+ background = _rgba_array(background, "background")
791
+ overlay = _rgba_array(overlay, "overlay")
792
+ unedited_rect = _rgba_array(unedited_rect, "Unedited_Rect")
793
+ descriptions = [
794
+ _input_alpha_description(name, rgba, int(np.asarray(raw).shape[-1]))
795
+ for name, raw, rgba in zip(("background", "overlay", "Unedited_Rect"),
796
+ raw_inputs, (background, overlay, unedited_rect))
797
+ ]
798
+ input_diagnostics = "Inputs:\n" + "\n".join(descriptions)
799
+ if float(_weights(overlay).sum()) <= 0.0:
800
+ raise ValueError("overlay is fully transparent; there is nothing to align or paste.")
801
+ interrupt()
802
+ crop_x, crop_y, crop_error, ties = _locate_unedited(background, unedited_rect, interrupt)
803
+ crop_match_mode = "alpha-aware crop appearance"
804
+ crop_notes = []
805
+ # A Load Image IMAGE output is RGB. If its MASK is missing while the
806
+ # background retains alpha, treating that RGB crop as genuinely opaque
807
+ # turns matching transparent padding into a maximum-error penalty.
808
+ # Recover ONLY when the actual RGB values provide a near-exact copy
809
+ # match. Do not cherry-pick arbitrary low-scoring fallback locations.
810
+ if (crop_error > 1.0e-8
811
+ and np.all(unedited_rect[..., 3] >= 1.0 - _ALPHA_EPSILON)
812
+ and np.any(background[..., 3] <= _ALPHA_EPSILON)):
813
+ rgb_x, rgb_y, rgb_error, rgb_ties = _locate_unedited(
814
+ background, unedited_rect, interrupt, respect_background_alpha=False)
815
+ rgb_region = background[rgb_y:rgb_y + unedited_rect.shape[0],
816
+ rgb_x:rgb_x + unedited_rect.shape[1]]
817
+ visible_evidence = int(np.count_nonzero(rgb_region[..., 3] > _ALPHA_EPSILON))
818
+ minimum_evidence = min(16, unedited_rect.shape[0] * unedited_rect.shape[1])
819
+ rgb_texture = float(np.mean(np.var(unedited_rect[..., :3].astype(np.float64), axis=(0, 1))))
820
+ trustworthy_rgb = visible_evidence >= minimum_evidence and rgb_texture > 1.0e-10
821
+ if (rgb_error <= _RGB_COPY_ERROR_TOLERANCE and rgb_error < crop_error
822
+ and trustworthy_rgb):
823
+ crop_notes.append(
824
+ "Alpha-aware candidate (%d,%d) scored %.8f/200. A near-exact RGB copy instead matched (%d,%d)."
825
+ % (crop_x, crop_y, 200.0 * (1.0 - crop_error), rgb_x, rgb_y))
826
+ crop_notes.append(
827
+ "Crop alpha may be missing: connect the crop's matching Load Image MASK. "
828
+ "RGB fallback applies to crop location only; overlay output still needs its own real alpha/MASK.")
829
+ crop_x, crop_y, crop_error, ties = rgb_x, rgb_y, rgb_error, rgb_ties
830
+ crop_match_mode = "verified near-exact RGB-copy fallback"
831
+ elif rgb_error <= _RGB_COPY_ERROR_TOLERANCE and not trustworthy_rgb:
832
+ crop_notes.append(
833
+ "An RGB-only candidate had insufficient visible/texture evidence and was not accepted. "
834
+ "Hidden RGB in transparent pixels cannot establish a reliable visible match.")
835
+ crop_similarity = 200.0 * (1.0 - crop_error)
836
+ # The search above evaluates all placements and selects the highest
837
+ # score. Tolerance is an acceptance check ONLY, never an early exit.
838
+ if crop_similarity < min_crop_similarity:
839
+ # Solver convergence is not evidence of correct crop localization.
840
+ # Return an explicit failure through the existing status socket and
841
+ # preserve background instead of pasting a wrong result somewhere.
842
+ status = "\n".join([
843
+ "LOCATION FAILED: original crop was not located reliably. No overlay was pasted.",
844
+ "Closest candidate: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200; required >= %.4f/200."
845
+ % (crop_x, crop_y, unedited_rect.shape[1], unedited_rect.shape[0], crop_similarity,
846
+ min_crop_similarity),
847
+ "min_tolerance=%.6f. The highest-scoring location was selected before checking this minimum."
848
+ % float(min_tolerance),
849
+ "The best available crop match did not meet the configured minimum. "
850
+ "Check image wiring, crop resizing/flipping, and corresponding MASK/alpha inputs.",
851
+ "Output coordinates=-1 and dimensions=0 indicate no accepted placement.",
852
+ input_diagnostics, *crop_notes,
853
+ ])
854
+ progress(100)
855
+ _LOG.warning("Salia: rejected unverified crop at (%d,%d), similarity %.8f/200", crop_x, crop_y, crop_similarity)
856
+ return {"composite": background.copy(), "overlay_canvas": np.zeros_like(background),
857
+ "status": status, "x": -1.0, "y": -1.0, "width": 0.0, "height": 0.0,
858
+ "center_x": -1.0, "center_y": -1.0, "similarity": 0.0,
859
+ "registration_similarity": 0.0, "robust_cost": None, "initial_robust_cost": None,
860
+ "converged": False, "accepted": False, "location_verified": False,
861
+ "trace": [], "parameters": np.zeros(4), "crop_x": crop_x, "crop_y": crop_y,
862
+ "crop_similarity": float(crop_similarity), "crop_match_mode": crop_match_mode}
863
+ crop_height, crop_width = unedited_rect.shape[:2]
864
+ center_x, center_y = crop_x + crop_width / 2.0, crop_y + crop_height / 2.0
865
+ width0, height0 = float(target_width or crop_width), float(target_height or crop_height)
866
+ # Keep work bounded for very large patches without changing final output
867
+ # size or resolution. The original remains the only final render source.
868
+ matching_ratio = min(1.0, _MATCH_MAX_SIDE / max(width0, height0))
869
+ match_width = max(1, int(math.floor(width0 * matching_ratio + 0.5)))
870
+ match_height = max(1, int(math.floor(height0 * matching_ratio + 0.5)))
871
+ template = resize_rgba_ewa(overlay, match_width, match_height, interrupt)
872
+ confidence = _weights(template)
873
+ if confidence.sum() <= 0.0:
874
+ raise ValueError("The overlay became fully transparent at registration resolution.")
875
+ mean = np.sum(template[..., :3] * confidence[..., None], axis=(0, 1)) / confidence.sum()
876
+ variance = float(np.sum(confidence[..., None] * (template[..., :3] - mean) ** 2)
877
+ / (3.0 * confidence.sum()))
878
+ progress(8)
879
+ # Bounds are guardrails, not pixel search steps. Center can move by one
880
+ # initial rectangle width/height in either direction. Scale can vary by
881
+ # scale_limit or its reciprocal; actual dimensions always stay >=1.
882
+ low_width = max(1.0, width0 / float(scale_limit))
883
+ low_height = max(1.0, height0 / float(scale_limit))
884
+ high_width = min(float(_MAX_DIMENSION), width0 * float(scale_limit))
885
+ high_height = min(float(_MAX_DIMENSION), height0 * float(scale_limit))
886
+ # Positive bounds even for a 1px starting dimension at the upper limit.
887
+ lower = np.array((-1.0, -1.0, math.log(low_width / width0), math.log(low_height / height0)))
888
+ upper = np.array((1.0, 1.0, math.log(high_width / width0), math.log(high_height / height0)))
889
+ lower[2:] = np.minimum(lower[2:], -1.0e-12)
890
+ upper[2:] = np.maximum(upper[2:], 1.0e-12)
891
+ parameters = np.zeros(4, dtype=np.float64)
892
+ trace, notices = [], list(crop_notes)
893
+ final_problem = None
894
+ last_result = None
895
+ total_calls = 0
896
+ levels = [2 ** k for k in reversed(range(int(pyramid_levels)))]
897
+ if variance < 1.0e-10:
898
+ # A uniform-color patch cannot identify a unique width/height from
899
+ # color matching. Preserve the supplied crop geometry in that case.
900
+ notices.append("LOW TEXTURE: overlay is effectively uniform color; initial geometry retained.")
901
+ levels = [1]
902
+ for level_index, factor in enumerate(levels):
903
+ interrupt()
904
+ def on_call(calls, index=level_index):
905
+ fractional = min(0.98, calls / max(1, max_evaluations * 6))
906
+ progress(8 + int(78 * (index + fractional) / len(levels)))
907
+ problem = _RegistrationLevel(background, template, center_x, center_y,
908
+ width0, height0, factor, robust_threshold, interrupt, on_call)
909
+ initial_cost = problem.cost(parameters)
910
+ if variance >= 1.0e-10:
911
+ result = least_squares(
912
+ problem.residual, parameters, bounds=(lower, upper), method="trf", jac="2-point",
913
+ loss=problem.loss, f_scale=float(robust_threshold), x_scale=np.full(4, 0.1),
914
+ max_nfev=int(max_evaluations), ftol=1.0e-8, xtol=1.0e-7, gtol=1.0e-10,
915
+ )
916
+ candidate_cost = problem.cost(result.x)
917
+ if candidate_cost < initial_cost - 1.0e-14:
918
+ parameters = result.x.copy()
919
+ last_result = result
920
+ trace.append("factor=%d; samples=%d; cost %.10g -> %.10g; nfev=%d; solver_status=%d (%s)"
921
+ % (factor, problem.count, initial_cost, problem.cost(parameters), result.nfev,
922
+ result.status, str(result.message).strip()))
923
+ if result.status == 0:
924
+ notices.append("Evaluation limit reached at pyramid factor %d; best accepted fit retained." % factor)
925
+ else:
926
+ trace.append("factor=1; samples=%d; optimizer skipped for uniform color" % problem.count)
927
+ total_calls += problem.calls
928
+ final_problem = problem
929
+ # Validate every accumulated pyramid update on the SAME finest objective
930
+ # against the original transform. A coarse-only improvement is not enough.
931
+ base_cost = final_problem.cost(np.zeros(4))
932
+ fit_cost = final_problem.cost(parameters)
933
+ accepted = bool(fit_cost < base_cost - 1.0e-14)
934
+ if not accepted:
935
+ parameters[:] = 0.0
936
+ fit_cost = base_cost
937
+ center_x, center_y, width, height = final_problem.geometry(parameters)
938
+ width, height = max(1.0, min(_MAX_DIMENSION, width)), max(1.0, min(_MAX_DIMENSION, height))
939
+ x, y = center_x - width / 2.0, center_y - height / 2.0
940
+ registration_similarity = final_problem.similarity(parameters)
941
+ if accepted and np.any(np.minimum(parameters - lower, upper - parameters) < 1.0e-5):
942
+ notices.append("A fit parameter reached its allowed bound; inspect alignment or increase scale_limit if appropriate.")
943
+ if last_result is not None and accepted:
944
+ singular = np.linalg.svd(last_result.jac[:-4], compute_uv=False)
945
+ if singular.size and (singular[0] <= 1.0e-10 or singular[-1] < singular[0] * 1.0e-5):
946
+ notices.append("Weak geometry constraint: image detail does not reliably determine all four parameters.")
947
+ progress(88)
948
+ # The transform stays fractional: no rounding width, height, or top-left.
949
+ patch, paste_x, paste_y = render_rgba_ewa(
950
+ overlay, background.shape[1], background.shape[0], center_x, center_y, width, height, interrupt)
951
+ composite, canvas = _source_over(background, patch, paste_x, paste_y)
952
+ rendered_error = _error_at(background, patch, paste_x, paste_y) if patch.size else 1.0
953
+ similarity = float(200.0 * (1.0 - rendered_error))
954
+ if ties > 1:
955
+ notices.append("Crop location ambiguous: %d numerically tied locations; first confirmed best used." % ties)
956
+ if crop_error > 1.0e-8:
957
+ notices.append("Unedited_Rect was not an exact appearance match; closest crop location used.")
958
+ if x < 0.0 or y < 0.0 or x + width > background.shape[1] or y + height > background.shape[0]:
959
+ notices.append("Overlay extends outside canvas. Fitting penalizes missing samples; rendered similarity covers the visible paste only.")
960
+ converged = bool(last_result is not None and last_result.status > 0)
961
+ state = ("ALIGNED" if accepted else "INITIAL GEOMETRY KEPT")
962
+ status = "\n".join([
963
+ "%s; joint continuous X/Y/width/height registration; %s."
964
+ % (state, "solver converged numerically" if converged else "inspect solver notes"),
965
+ "Crop: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200"
966
+ % (crop_x, crop_y, crop_width, crop_height, 200.0 * (1.0 - crop_error)),
967
+ "Crop match mode: " + crop_match_mode,
968
+ "Crop acceptance: min_tolerance=%.6f (%.6f/200); highest score selected before threshold check."
969
+ % (float(min_tolerance), min_crop_similarity),
970
+ input_diagnostics,
971
+ "Overlay: top_left=(%.8f,%.8f), size=(%.8f,%.8f), center=(%.8f,%.8f)"
972
+ % (x, y, width, height, center_x, center_y),
973
+ "Rendered similarity=%.8f/200; registration similarity=%.8f/200; robust cost %.10g -> %.10g"
974
+ % (similarity, registration_similarity, base_cost, fit_cost),
975
+ "Registration uses alpha-weighted soft-L1, fixed source samples, and a coarse-to-fine pyramid."
976
+ " Robust cost is the fitted objective; raw similarity may decrease when changed pixels are rejected as outliers.",
977
+ "Matching image=%dx%d; residual calls=%d; render_bbox=(%d,%d,%d,%d); seconds=%.3f"
978
+ % (match_width, match_height, total_calls, paste_x, paste_y, patch.shape[1], patch.shape[0], time.monotonic() - started),
979
+ "EWA LanczosSharp: direct original-source rendering with fractional geometry; no rotation/shear/optical flow.",
980
+ *notices, "Pyramid trace:", *trace,
981
+ ])
982
+ progress(100)
983
+ _LOG.info("Salia Joint Align: center=(%.5f,%.5f), size=(%.5f,%.5f), accepted=%s, cost=%g -> %g",
984
+ center_x, center_y, width, height, accepted, base_cost, fit_cost)
985
+ return {"composite": composite, "overlay_canvas": canvas, "status": status,
986
+ "x": float(x), "y": float(y), "width": float(width), "height": float(height),
987
+ "center_x": float(center_x), "center_y": float(center_y), "similarity": similarity,
988
+ "registration_similarity": registration_similarity, "robust_cost": fit_cost,
989
+ "initial_robust_cost": base_cost, "converged": converged, "accepted": accepted,
990
+ "trace": trace, "parameters": parameters.copy(), "crop_x": crop_x, "crop_y": crop_y,
991
+ "location_verified": True, "crop_similarity": float(crop_similarity),
992
+ "crop_match_mode": crop_match_mode}
993
+
994
+
995
+
996
+ # Content-aware seam blending, embedded in this same module.
997
+ from scipy.ndimage import distance_transform_edt, binary_erosion
998
+ from PIL import Image, ImageDraw, ImageFont
999
+ _MAX_GRAPH_SIDE = 1536
1000
+ _BLEND_MODES = ("Graph cut + feather", "Graph cut + multiband")
1001
+ __version__ = "1.0.0"
1002
+
1003
+ def rgba_disagreement(background, overlay):
1004
+ """Visible disagreement in [0,1], independent of RGB beneath alpha zero.
1005
+
1006
+ Inputs: equal HWC straight RGBA float arrays in the same color space.
1007
+ Compute the RMS difference of their RGB composites over both black and
1008
+ white. This is a genuine alpha-aware cost; a single grey matte would miss
1009
+ alpha differences whenever a foreground color equals that grey.
1010
+ """
1011
+ a = np.asarray(background, dtype=np.float64)
1012
+ b = np.asarray(overlay, dtype=np.float64)
1013
+ if a.shape != b.shape or a.ndim != 3 or a.shape[-1] != 4:
1014
+ raise ValueError("RGBA disagreement requires equal HWC RGBA arrays.")
1015
+ if not np.isfinite(a).all() or not np.isfinite(b).all():
1016
+ raise ValueError("RGBA disagreement inputs must be finite.")
1017
+ a, b = np.clip(a, 0.0, 1.0), np.clip(b, 0.0, 1.0)
1018
+ delta_premultiplied = b[..., :3] * b[..., 3:4] - a[..., :3] * a[..., 3:4]
1019
+ delta_alpha = b[..., 3:4] - a[..., 3:4]
1020
+ squared = 0.5 * (np.mean(delta_premultiplied ** 2, axis=-1)
1021
+ + np.mean((delta_premultiplied - delta_alpha) ** 2, axis=-1))
1022
+ return np.ascontiguousarray(np.sqrt(np.clip(squared, 0.0, 1.0)), dtype=np.float32)
1023
+
1024
+
1025
+ def graphcut_mask(error, core, frame, interrupt=lambda: None):
1026
+ """Return bool mask selecting the overlay, using OpenCV's actual solver.
1027
+
1028
+ ``error`` is a finite HxW scalar disagreement in [0,1]. ``core`` forces
1029
+ edited/overlay pixels and ``frame`` forces original/background pixels.
1030
+ Availability masks are geometry constraints, NOT image alpha: a source
1031
+ pixel with alpha zero may intentionally erase an old opaque pixel.
1032
+
1033
+ OpenCV's GraphCutSeamFinder expects three-channel float cost images. Its
1034
+ COST_COLOR edge term is norm(image1[p]-image2[p]) plus the same at q plus
1035
+ one. Feed zero versus repeated(error*255/sqrt(3)) to make its color norm
1036
+ exactly the caller's RGBA-aware error. COST_COLOR_GRAD is deliberately
1037
+ not used: gradients of an error proxy are not gradients of the artwork.
1038
+ This calls the existing OpenCV graph-cut implementation; it does not
1039
+ reimplement max-flow/min-cut in Python.
1040
+ """
1041
+ error = np.asarray(error, dtype=np.float32)
1042
+ core, frame = np.asarray(core, dtype=bool), np.asarray(frame, dtype=bool)
1043
+ if error.ndim != 2 or min(error.shape) < 1 or core.shape != error.shape or frame.shape != error.shape:
1044
+ raise ValueError("Graph-cut error/core/frame must have matching nonempty HxW shapes.")
1045
+ if not np.isfinite(error).all():
1046
+ raise ValueError("Graph-cut error contains NaN or infinity.")
1047
+ if np.any(core & frame):
1048
+ raise ValueError("Protected overlay core and background frame must not overlap.")
1049
+ if not np.any(core):
1050
+ raise ValueError("Graph-cut requires at least one protected overlay core pixel.")
1051
+ try:
1052
+ import cv2
1053
+ except ImportError as exc:
1054
+ raise RuntimeError("OpenCV is required. Install opencv-python-headless in ComfyUI's Python environment.") from exc
1055
+ constructor = getattr(getattr(cv2, "detail", None), "GraphCutSeamFinder", None)
1056
+ if constructor is None:
1057
+ constructor = getattr(cv2, "detail_GraphCutSeamFinder", None)
1058
+ if constructor is None:
1059
+ raise RuntimeError("This OpenCV build does not include GraphCutSeamFinder (stitching module).")
1060
+
1061
+ interrupt()
1062
+ h, w = error.shape
1063
+ first = np.zeros((h, w, 3), dtype=np.float32)
1064
+ scalar = np.clip(error, 0.0, 1.0) * np.float32(255.0 / np.sqrt(3.0))
1065
+ second = np.ascontiguousarray(np.repeat(scalar[..., None], 3, axis=-1))
1066
+ background_available = np.full((h, w), 255, dtype=np.uint8)
1067
+ overlay_available = np.full((h, w), 255, dtype=np.uint8)
1068
+ background_available[core] = 0
1069
+ overlay_available[frame] = 0
1070
+ # UMat makes the in/out mutation behavior reliable across Python builds.
1071
+ masks = [cv2.UMat(background_available), cv2.UMat(overlay_available)]
1072
+ finder = constructor("COST_COLOR", 1.0e7, 0.0)
1073
+ changed = finder.find([cv2.UMat(first), cv2.UMat(second)], [(0, 0), (0, 0)], masks)
1074
+ if changed is not None:
1075
+ masks = list(changed)
1076
+ selected = masks[1].get() if hasattr(masks[1], "get") else np.asarray(masks[1])
1077
+ selected = np.asarray(selected) > 0
1078
+ # Explicit final constraints also guard against changed OpenCV penalties
1079
+ # or precision behavior in alternative builds.
1080
+ selected[core] = True
1081
+ selected[frame] = False
1082
+ interrupt()
1083
+ return np.ascontiguousarray(selected)
1084
+
1085
+
1086
+ def opencv_multiband_fields(background_fields, source_fields, source_weight,
1087
+ bands=4, interrupt=lambda: None):
1088
+ """Blend ``[linear-premultiplied R,G,B,alpha]`` arrays with OpenCV.
1089
+
1090
+ Inputs are equally sized HWC float arrays; source_weight is HW in [0,1]
1091
+ and is independent of either image's alpha. The source fields must be
1092
+ UNCOVERED fields (placement coverage is already part of source_weight).
1093
+
1094
+ Uses the actual cv2.detail.MultiBandBlender implementation in two passes:
1095
+ premultiplied RGB, then alpha in two channels plus a unit calibration
1096
+ channel. OpenCV requires
1097
+ signed 16-bit 3-channel images and 8-bit masks. Values are quantized at
1098
+ scale 32767 internally; output remains float32 premultiplied RGBA fields.
1099
+ The caller should constrain any pyramid overshoot, unpremultiply, and
1100
+ restamp protected/source or unchanged/background regions as appropriate.
1101
+
1102
+ This helper does not impose locality: multiband filters can affect pixels
1103
+ outside a simple mask's transition. The caller owns the permitted region.
1104
+ """
1105
+ interrupt()
1106
+ background = np.asarray(background_fields)
1107
+ source = np.asarray(source_fields)
1108
+ weight = np.asarray(source_weight)
1109
+ if (background.ndim != 3 or background.shape[-1] != 4
1110
+ or source.shape != background.shape or min(background.shape[:2]) < 1):
1111
+ raise ValueError("Multiband fields must be equal, nonempty HWC four-channel arrays.")
1112
+ if weight.shape != background.shape[:2]:
1113
+ raise ValueError("Multiband source_weight must match the image H/W.")
1114
+ if (not np.issubdtype(background.dtype, np.floating)
1115
+ or not np.issubdtype(source.dtype, np.floating)
1116
+ or not np.issubdtype(weight.dtype, np.floating)):
1117
+ raise ValueError("Multiband fields and source_weight must be floating point.")
1118
+ if (not np.isfinite(background).all() or not np.isfinite(source).all()
1119
+ or not np.isfinite(weight).all()):
1120
+ raise ValueError("Multiband fields contain NaN or infinity.")
1121
+ if isinstance(bands, bool) or not isinstance(bands, (int, np.integer)) or not 0 <= bands <= 10:
1122
+ raise ValueError("Multiband bands must be an integer from 0 to 10.")
1123
+ background = np.ascontiguousarray(np.clip(background, 0.0, 1.0), dtype=np.float32)
1124
+ source = np.ascontiguousarray(np.clip(source, 0.0, 1.0), dtype=np.float32)
1125
+ weight = np.clip(weight, 0.0, 1.0)
1126
+ if not np.any(weight > 0.0):
1127
+ return background.copy()
1128
+ if not np.any(weight < 1.0):
1129
+ return source.copy()
1130
+ if np.array_equal(background, source):
1131
+ return background.copy()
1132
+
1133
+ import cv2
1134
+ factory = getattr(cv2, "detail_MultiBandBlender", None)
1135
+ if factory is None:
1136
+ factory = getattr(getattr(cv2, "detail", None), "MultiBandBlender", None)
1137
+ if factory is None:
1138
+ raise RuntimeError("This OpenCV build does not provide MultiBandBlender.")
1139
+
1140
+ height, width = background.shape[:2]
1141
+ # Quantize once and construct the complement from the same integer mask.
1142
+ # This guarantees masks sum to 255 instead of independent rounding gaps.
1143
+ source_mask = np.ascontiguousarray(np.rint(weight * 255.0), dtype=np.uint8)
1144
+ background_mask = np.ascontiguousarray(255 - source_mask, dtype=np.uint8)
1145
+ if not np.any(source_mask):
1146
+ return background.copy()
1147
+ if np.all(source_mask == 255):
1148
+ return source.copy()
1149
+ value_scale = 32767.0
1150
+
1151
+ def blend_three(background_three, source_three):
1152
+ interrupt()
1153
+ blender = factory()
1154
+ blender.setNumBands(int(bands))
1155
+ blender.prepare((0, 0, int(width), int(height)))
1156
+ for values, mask in ((background_three, background_mask), (source_three, source_mask)):
1157
+ interrupt()
1158
+ # MultiBandBlender accepts CV_16SC3 rather than float color input.
1159
+ quantized = np.ascontiguousarray(np.rint(values * value_scale), dtype=np.int16)
1160
+ blender.feed(quantized, mask, (0, 0))
1161
+ interrupt()
1162
+ output, _output_mask = blender.blend(None, None)
1163
+ interrupt()
1164
+ output = np.asarray(output)
1165
+ if output.shape != (height, width, 3):
1166
+ raise RuntimeError("OpenCV returned an unexpected multiband image shape.")
1167
+ return output.astype(np.float32) / value_scale
1168
+
1169
+ premultiplied_rgb = blend_three(background[..., :3], source[..., :3])
1170
+ # The 16-bit implementation can produce a small mask-dependent gain
1171
+ # bias even for constant unit input. Carry a unit field alongside alpha
1172
+ # to measure/correct it using the very same masks and pyramid levels.
1173
+ ones = np.ones((height, width, 1), dtype=np.float32)
1174
+ background_alpha = np.concatenate((background[..., 3:4], background[..., 3:4], ones), axis=-1)
1175
+ source_alpha = np.concatenate((source[..., 3:4], source[..., 3:4], ones), axis=-1)
1176
+ alpha_three = blend_three(background_alpha, source_alpha)
1177
+ gain = alpha_three[..., 2:3]
1178
+ if not np.isfinite(gain).all() or np.any(gain <= 0.0):
1179
+ raise RuntimeError("OpenCV multiband normalization failed.")
1180
+ premultiplied_rgb = premultiplied_rgb / gain
1181
+ alpha = alpha_three[..., :1] / gain
1182
+ if np.array_equal(background[..., 3], source[..., 3]):
1183
+ alpha = background[..., 3:4].copy()
1184
+ return np.ascontiguousarray(np.concatenate((premultiplied_rgb, alpha), axis=-1), dtype=np.float32)
1185
+
1186
+
1187
+ def _coverage(x, y, width, height, x0, y0, out_width, out_height):
1188
+ px = np.arange(x0, x0 + out_width, dtype=np.float64)
1189
+ py = np.arange(y0, y0 + out_height, dtype=np.float64)
1190
+ kx = np.maximum(0.0, np.minimum(px + 1.0, x + width) - np.maximum(px, x))
1191
+ ky = np.maximum(0.0, np.minimum(py + 1.0, y + height) - np.maximum(py, y))
1192
+ return np.ascontiguousarray(ky[:, None] * kx[None, :], dtype=np.float32)
1193
+
1194
+
1195
+ def _linear_fields(rgba):
1196
+ alpha = rgba[..., 3:4]
1197
+ return np.concatenate((_to_linear(rgba[..., :3]) * alpha, alpha), axis=-1)
1198
+
1199
+
1200
+ def _seam_cost(background, overlay, gradient_weight):
1201
+ # Compare appearance over BOTH black and white, so neither hidden RGB
1202
+ # nor a lucky match to a single matte can hide an alpha disagreement.
1203
+ a, b = background.copy(), overlay.copy()
1204
+ a[..., :3], b[..., :3] = _to_linear(a[..., :3]), _to_linear(b[..., :3])
1205
+ error = rgba_disagreement(a, b)
1206
+ if gradient_weight > 0.0 and min(error.shape) >= 2:
1207
+ af, bf = _linear_fields(background), _linear_fields(overlay)
1208
+ ady, adx = np.gradient(af, axis=(0, 1))
1209
+ bdy, bdx = np.gradient(bf, axis=(0, 1))
1210
+ gradient_error = np.sqrt(np.mean((ady - bdy) ** 2 + (adx - bdx) ** 2, axis=-1))
1211
+ error = (error + float(gradient_weight) * gradient_error) / (1.0 + float(gradient_weight))
1212
+ return np.ascontiguousarray(np.clip(error, 0.0, 1.0), dtype=np.float32)
1213
+
1214
+
1215
+ def _bounded_graphcut(error, core, frame, interrupt):
1216
+ h, w = error.shape
1217
+ if max(h, w) <= _MAX_GRAPH_SIDE:
1218
+ return graphcut_mask(error, core, frame, interrupt), (w, h)
1219
+ import cv2
1220
+ ratio = _MAX_GRAPH_SIDE / max(h, w)
1221
+ gw, gh = max(3, int(round(w * ratio))), max(3, int(round(h * ratio)))
1222
+ small_error = cv2.resize(error, (gw, gh), interpolation=cv2.INTER_AREA)
1223
+ small_core = cv2.resize(core.astype(np.float32), (gw, gh), interpolation=cv2.INTER_AREA) > 0.0
1224
+ small_frame = cv2.resize(frame.astype(np.float32), (gw, gh), interpolation=cv2.INTER_AREA) > 0.0
1225
+ small_frame &= ~small_core
1226
+ small = graphcut_mask(small_error, small_core, small_frame, interrupt)
1227
+ result = cv2.resize(small.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) > 0
1228
+ result[core], result[frame] = True, False
1229
+ return result, (gw, gh)
1230
+
1231
+
1232
+ def _feather_seam(selected, core, frame, radius):
1233
+ if radius <= 0 or np.all(selected) or not np.any(selected):
1234
+ result = selected.astype(np.float32)
1235
+ else:
1236
+ signed = distance_transform_edt(selected) - distance_transform_edt(~selected)
1237
+ # The seam lies halfway between the two adjacent pixel centers.
1238
+ signed = np.sign(signed) * np.maximum(0.0, np.abs(signed) - 0.5)
1239
+ t = np.clip(0.5 + signed / (2.0 * float(radius)), 0.0, 1.0)
1240
+ result = (t * t * (3.0 - 2.0 * t)).astype(np.float32)
1241
+ result[core], result[frame] = 1.0, 0.0
1242
+ return result
1243
+
1244
+
1245
+ def _replace_rgba(background, source, weight, coverage, blend_mode, bands, interrupt):
1246
+ # k is rectangle coverage, a is object alpha, w is seam preference.
1247
+ # Keep them distinct. Source-over would thicken an unchanged alpha edge.
1248
+ effective = np.clip(weight * coverage, 0.0, 1.0)
1249
+ bg_fields, src_fields = _linear_fields(background), _linear_fields(source)
1250
+ base = bg_fields * (1.0 - effective[..., None]) + src_fields * effective[..., None]
1251
+ fields = base.copy()
1252
+ if blend_mode == _BLEND_MODES[1] and np.any((effective > 0.0) & (effective < 1.0)):
1253
+ mb = opencv_multiband_fields(bg_fields, src_fields, effective, bands, interrupt)
1254
+ # Keep exact replacement alpha so Laplacian bands do not spread the
1255
+ # transparent silhouette. Multiband adjusts color in the transition.
1256
+ mb_rgb = np.zeros_like(mb[..., :3])
1257
+ np.divide(mb[..., :3], mb[..., 3:4], out=mb_rgb,
1258
+ where=mb[..., 3:4] > _ALPHA_EPSILON)
1259
+ mb_premultiplied = np.clip(mb_rgb, 0.0, 1.0) * base[..., 3:4]
1260
+ gate = 4.0 * effective * (1.0 - effective)
1261
+ fields[..., :3] += gate[..., None] * (mb_premultiplied - base[..., :3])
1262
+ fields[..., 3] = np.clip(base[..., 3], 0.0, 1.0)
1263
+ fields[..., :3] = np.clip(fields[..., :3], 0.0, fields[..., 3:4])
1264
+ result = _finish_image(fields, 4)
1265
+ # Keep unselected original pixels byte-for-byte. Full-source pixels stay
1266
+ # byte-for-byte equal to the placed source; identical pairs stay identical.
1267
+ result[effective <= 0.0] = background[effective <= 0.0]
1268
+ result[effective >= 1.0] = source[effective >= 1.0]
1269
+ # Original-source EWA can leave ~1 ULP in a constant field. Do not let
1270
+ # OpenCV's internal 16-bit color path amplify that into a visible change.
1271
+ # Fully selected source/core pixels keep their exact placed-source values.
1272
+ identical = (np.all(np.abs(source - background) <= 2.0e-7, axis=-1)
1273
+ & (effective < 1.0))
1274
+ result[identical] = background[identical]
1275
+ return result, effective
1276
+
1277
+
1278
+ def _blend_verified_canvas(background, canvas, rectangle, source, coverage, bbox,
1279
+ seam_band, feather_pixels, multiband, interrupt, progress):
1280
+ x0, y0, w, h = bbox
1281
+ roi = background[y0:y0 + h, x0:x0 + w]
1282
+ valid = coverage > 0.0
1283
+ inward = distance_transform_edt(np.pad(valid, 1, constant_values=False))[1:-1, 1:-1]
1284
+ actual_band = min(int(seam_band), max(1, int(math.floor(inward.max() / 2.0))))
1285
+ core = (inward > actual_band) & valid
1286
+ frame = ((inward <= 1.0) | ~valid) & ~core
1287
+ progress(35)
1288
+ if min(h, w) < 3:
1289
+ core, frame, selected = valid.copy(), np.zeros_like(valid), valid.copy()
1290
+ graph_shape = (0, 0)
1291
+ else:
1292
+ error = _seam_cost(roi, source, 0.35)
1293
+ selected, graph_shape = _bounded_graphcut(error, core, frame, interrupt)
1294
+ selected &= valid
1295
+ weight = _feather_seam(selected, core, frame, int(feather_pixels))
1296
+ weight[~valid] = 0.0
1297
+ mode = _BLEND_MODES[1] if multiband else _BLEND_MODES[0]
1298
+ progress(65)
1299
+ mixed, effective = _replace_rgba(roi, source, weight, coverage, mode, 4, interrupt)
1300
+ output = background.copy()
1301
+ output[y0:y0 + h, x0:x0 + w] = mixed
1302
+ full_weight = np.zeros(background.shape[:2], np.float32)
1303
+ full_core = np.zeros(background.shape[:2], bool)
1304
+ full_frame = np.zeros(background.shape[:2], bool)
1305
+ full_selected = np.zeros(background.shape[:2], bool)
1306
+ full_weight[y0:y0 + h, x0:x0 + w] = effective
1307
+ full_core[y0:y0 + h, x0:x0 + w] = core
1308
+ full_frame[y0:y0 + h, x0:x0 + w] = frame
1309
+ full_selected[y0:y0 + h, x0:x0 + w] = selected
1310
+ return {"composite": output, "weight": full_weight, "core": full_core,
1311
+ "frame": full_frame, "selected": full_selected, "bbox": bbox,
1312
+ "graph_shape": graph_shape, "seam_band": actual_band, "mode": mode}
1313
+
1314
+
1315
+ def checker_preview(rgba):
1316
+ h, w = rgba.shape[:2]
1317
+ yy, xx = np.ogrid[:h, :w]
1318
+ tiles = ((xx // 24 + yy // 24) % 2).astype(np.float32)
1319
+ checker = 0.24 + 0.14 * tiles
1320
+ alpha = rgba[..., 3:4]
1321
+ return np.ascontiguousarray(rgba[..., :3] * alpha + checker[..., None] * (1.0 - alpha), dtype=np.float32)
1322
+
1323
+
1324
+ def _gray(value):
1325
+ return np.repeat(np.clip(value, 0.0, 1.0)[..., None], 3, axis=-1).astype(np.float32)
1326
+
1327
+
1328
+ def _source_over_debug(background, canvas):
1329
+ if background.shape != canvas.shape:
1330
+ return checker_preview(background)
1331
+ aa, ab = canvas[..., 3:4], background[..., 3:4]
1332
+ alpha = aa + ab * (1.0 - aa)
1333
+ premult = canvas[..., :3] * aa + background[..., :3] * ab * (1.0 - aa)
1334
+ color = np.zeros_like(premult)
1335
+ np.divide(premult, alpha, out=color, where=alpha > _ALPHA_EPSILON)
1336
+ return checker_preview(np.concatenate((color, alpha), axis=-1))
1337
+
1338
+
1339
+ def _debug_grid(panels, error_text=None):
1340
+ cell, title, gap = 320, 32, 8
1341
+ grid = Image.new("RGB", (4 * (cell + gap) + gap, 2 * (cell + title + gap) + gap), (22, 22, 26))
1342
+ draw = ImageDraw.Draw(grid)
1343
+ try:
1344
+ font = ImageFont.truetype("DejaVuSans.ttf", 14)
1345
+ except OSError:
1346
+ font = ImageFont.load_default()
1347
+ for index, (label, rgb) in enumerate(panels[:8]):
1348
+ col, row = index % 4, index // 4
1349
+ left, top = gap + col * (cell + gap), gap + row * (cell + title + gap)
1350
+ draw.text((left + 4, top + 7), label, fill=(235, 235, 235), font=font)
1351
+ image = Image.fromarray(np.rint(np.clip(rgb, 0.0, 1.0) * 255.0).astype(np.uint8), "RGB")
1352
+ try:
1353
+ resample = Image.Resampling.LANCZOS
1354
+ except AttributeError:
1355
+ resample = Image.LANCZOS
1356
+ image.thumbnail((cell, cell), resample)
1357
+ grid.paste(image, (left + (cell - image.width) // 2, top + title + (cell - image.height) // 2))
1358
+ if error_text:
1359
+ draw.rectangle((0, 0, grid.width - 1, grid.height - 1), outline=(255, 64, 64), width=5)
1360
+ return np.asarray(grid, dtype=np.float32) / 255.0
1361
+
1362
+
1363
+ def _debug_outputs(background, canvas, state, status, error=False):
1364
+ output = state["composite"]
1365
+ weight, core, frame, selected = state["weight"], state["core"], state["frame"], state["selected"]
1366
+ background_preview = checker_preview(background)
1367
+ overlay_preview = checker_preview(canvas)
1368
+ final_preview = checker_preview(output)
1369
+ alpha_preview = _gray(canvas[..., 3])
1370
+ weight_preview = _gray(weight)
1371
+ constraints = np.zeros((*core.shape, 3), np.float32)
1372
+ constraints[core] = (0.0, 0.7, 1.0)
1373
+ constraints[frame] = (1.0, 0.25, 0.1)
1374
+ constraints[(~core) & (~frame) & (selected | (weight > 0.0))] = (0.25, 0.25, 0.25)
1375
+ seam = final_preview.copy()
1376
+ seam_edge = selected ^ binary_erosion(selected, border_value=0)
1377
+ core_edge = core ^ binary_erosion(core, border_value=0)
1378
+ seam[seam_edge] = (0.0, 1.0, 0.0)
1379
+ seam[core_edge] = (0.0, 0.7, 1.0)
1380
+ panels = [
1381
+ ("A Original background", background_preview),
1382
+ ("B Internally aligned overlay", overlay_preview),
1383
+ ("C Overlay alpha (white=opaque)", alpha_preview),
1384
+ ("D Blend weight (white=edited)", weight_preview),
1385
+ ("E Core cyan / frame orange", constraints),
1386
+ ("F Seam green / core cyan", seam),
1387
+ ("G Simple source-over comparison", _source_over_debug(background, canvas)),
1388
+ ("H Final replacement blend", final_preview),
1389
+ ]
1390
+ return {"composite_rgba": output, "composite_preview": final_preview,
1391
+ "debug_grid": _debug_grid(panels, status if error else None),
1392
+ "aligned_overlay_preview": overlay_preview, "overlay_alpha": alpha_preview,
1393
+ "blend_weight": weight_preview, "seam_preview": seam,
1394
+ "blend_mask": weight, "status": status, "ok": not error, "state": state}
1395
+
1396
+
1397
+ # ---------------------------------------------------------------------------
1398
+ # Single-node pipeline. These are internal calls, never upstream node inputs.
1399
+ # ---------------------------------------------------------------------------
1400
+
1401
+ def _pipeline_alpha_description(name, image, mask):
1402
+ channels = int(image.shape[-1]) if hasattr(image, "shape") and len(image.shape) else -1
1403
+ if channels == 4:
1404
+ return name + ": embedded RGBA alpha; external MASK ignored."
1405
+ return name + (": RGB + Load Image MASK; alpha=1-MASK internally."
1406
+ if mask is not None else ": RGB without MASK; treated as opaque.")
1407
+
1408
+
1409
+ def _empty_pipeline_outputs(background, canvas, message, alignment=None):
1410
+ try:
1411
+ bg = _rgba_array(background, "background")
1412
+ except (ValueError, TypeError):
1413
+ bg = np.zeros((256, 256, 4), np.float32)
1414
+ bg[..., 3] = 1.0
1415
+ try:
1416
+ ov = _rgba_array(canvas, "overlay canvas")
1417
+ except (ValueError, TypeError):
1418
+ ov = np.zeros_like(bg)
1419
+ zeros = np.zeros(bg.shape[:2], np.float32)
1420
+ state = {"composite": bg.copy(), "weight": zeros, "core": zeros.astype(bool),
1421
+ "frame": zeros.astype(bool), "selected": zeros.astype(bool)}
1422
+ status = (message + "\nNo seam blend was applied; original background returned. "
1423
+ "Debug grid has a red border. Output coordinates=-1 and width/height=0. "
1424
+ "This node takes background, overlay and Unedited_Rect directly; no other alignment node is needed.")
1425
+ output = _debug_outputs(bg, ov, state, status, error=True)
1426
+ output["overlay_canvas_rgba"] = ov
1427
+ output["aligned_composite_rgba"] = (alignment["composite"] if alignment else bg.copy())
1428
+ output["alignment"] = alignment
1429
+ output.update(x=-1.0, y=-1.0, width=0.0, height=0.0, center_x=-1.0,
1430
+ center_y=-1.0, similarity=0.0,
1431
+ crop_similarity=float(alignment["crop_similarity"]) if alignment else 0.0)
1432
+ return output
1433
+
1434
+
1435
+ def _internal_placed_source(background, canvas, rectangle):
1436
+ """Recover object alpha from the internal EWA canvas's rectangle coverage."""
1437
+ x, y, width, height = rectangle
1438
+ if not np.isfinite(rectangle).all() or width < 1.0 or height < 1.0:
1439
+ raise ValueError("Internal fitted rectangle is invalid.")
1440
+ bh, bw = background.shape[:2]
1441
+ if canvas.shape != background.shape:
1442
+ raise ValueError("Internal EWA canvas dimensions differ from background.")
1443
+ x0, y0 = max(0, min(bw, math.floor(x))), max(0, min(bh, math.floor(y)))
1444
+ x1, y1 = max(0, min(bw, math.ceil(x + width))), max(0, min(bh, math.ceil(y + height)))
1445
+ if x1 <= x0 or y1 <= y0:
1446
+ raise ValueError("Fitted overlay has no overlap with the background.")
1447
+ coverage = _coverage(x, y, width, height, x0, y0, x1-x0, y1-y0)
1448
+ source = canvas[y0:y1, x0:x1].copy()
1449
+ if np.any(source[..., 3] > coverage + 2.0e-5):
1450
+ raise ValueError("Internal EWA alpha exceeds its fractional rectangle coverage.")
1451
+ if not np.any(source[..., 3] > _ALPHA_EPSILON):
1452
+ raise ValueError("Fitted overlay has no visible pixels on the background.")
1453
+ np.divide(source[..., 3], coverage, out=source[..., 3], where=coverage > 0.0)
1454
+ source[..., 3] = np.clip(source[..., 3], 0.0, 1.0)
1455
+ return source, coverage, (x0, y0, x1-x0, y1-y0)
1456
+
1457
+
1458
+ def run_align_and_blend(background, overlay, Unedited_Rect, target_width=0, target_height=0,
1459
+ max_evaluations=100, pyramid_levels=3, robust_threshold=0.05,
1460
+ scale_limit=2.0, min_tolerance=0.9, seam_band=48,
1461
+ feather_pixels=4, multiband=False, interrupt=lambda: None,
1462
+ progress=lambda value: None, input_notes=()):
1463
+ """Array-level pipeline. Comfy MASKs have already been handled once."""
1464
+ started, stage = time.monotonic(), "input validation"
1465
+ bg, canvas, alignment = background, None, None
1466
+ try:
1467
+ bg = _rgba_array(background, "background")
1468
+ canvas = np.zeros_like(bg)
1469
+ for name, value, low, high in (("seam_band", seam_band, 1, 4096),
1470
+ ("feather_pixels", feather_pixels, 0, 256)):
1471
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not low <= value <= high:
1472
+ raise ValueError("%s must be an integer in [%d,%d]." % (name, low, high))
1473
+ if not isinstance(multiband, (bool, np.bool_)):
1474
+ raise ValueError("multiband must be a boolean.")
1475
+ interrupt()
1476
+ stage = "crop location / registration / EWA"
1477
+ alignment = align_arrays(background, overlay, Unedited_Rect, target_width, target_height,
1478
+ max_evaluations, pyramid_levels, robust_threshold, scale_limit,
1479
+ interrupt, lambda v: progress(int(float(v) * 0.80)),
1480
+ min_tolerance=min_tolerance)
1481
+ canvas = alignment["overlay_canvas"]
1482
+ if not alignment["location_verified"]:
1483
+ progress(100)
1484
+ return _empty_pipeline_outputs(bg, canvas,
1485
+ "GPT_1 LOCATION FAILED\n" + alignment["status"] + "\n" + "\n".join(input_notes), alignment)
1486
+ stage = "content-aware seam blending"
1487
+ rectangle = tuple(alignment[k] for k in ("x", "y", "width", "height"))
1488
+ source, coverage, bbox = _internal_placed_source(bg, canvas, rectangle)
1489
+ state = _blend_verified_canvas(bg, canvas, rectangle, source, coverage, bbox,
1490
+ seam_band, feather_pixels, multiband, interrupt,
1491
+ lambda v: progress(80 + int(float(v) * 0.19)))
1492
+ status = "\n".join([
1493
+ "GPT_1 OK: crop location, continuous alignment, original-source EWA and seam blending completed internally.",
1494
+ "Inputs are background + overlay + Unedited_Rect. No external alignment outputs, coordinates or status are used.",
1495
+ *input_notes,
1496
+ "Blend: %s; requested seam_band=%d, actual=%d; feather_pixels=%d; graph=%dx%d; protected pixels=%d"
1497
+ % (state["mode"], seam_band, state["seam_band"], feather_pixels,
1498
+ *state["graph_shape"], int(state["core"].sum())),
1499
+ "RGBA replacement uses premultiplied linear RGB and separate object alpha, rectangle coverage and seam weight.",
1500
+ "Seam cost compares black AND white composites plus gradient disagreement. White blend weight means edited replacement, not object alpha.",
1501
+ "Debug grid: A original; B aligned overlay; C object alpha; D blend weight; E core/frame; F seam; G ordinary source-over; H final blend.",
1502
+ "Total seconds=%.3f" % (time.monotonic() - started),
1503
+ "--- INTERNAL ALIGNMENT ---", alignment["status"],
1504
+ ])
1505
+ output = _debug_outputs(bg, canvas, state, status)
1506
+ output["overlay_canvas_rgba"] = canvas
1507
+ output["aligned_composite_rgba"] = alignment["composite"]
1508
+ output["alignment"] = alignment
1509
+ for key in ("x", "y", "width", "height", "center_x", "center_y", "similarity", "crop_similarity"):
1510
+ output[key] = float(alignment[key])
1511
+ interrupt()
1512
+ progress(100)
1513
+ return output
1514
+ except Exception as exc:
1515
+ if type(exc).__name__ == "InterruptProcessingException":
1516
+ raise
1517
+ _LOG.warning("Salia standalone GPT_1 %s failed: %s", stage, exc)
1518
+ progress(100)
1519
+ message = "GPT_1 ERROR during %s: %s: %s\n%s" % (stage, type(exc).__name__, exc, "\n".join(input_notes))
1520
+ if alignment:
1521
+ message += "\n--- INTERNAL ALIGNMENT ---\n" + alignment["status"]
1522
+ return _empty_pipeline_outputs(bg, canvas, message, alignment)
1523
+
1524
+
1525
+ class Salia_Auto_Align_Seam_Blend_GPT_1:
1526
+ @classmethod
1527
+ def INPUT_TYPES(cls):
1528
+ inputs = {"required": {
1529
+ "background": ("IMAGE", {"tooltip": "Single full-size RGB/RGBA background."}),
1530
+ "overlay": ("IMAGE", {"tooltip": "Original full-resolution edited overlay. Final EWA render always uses this source."}),
1531
+ "Unedited_Rect": ("IMAGE", {"tooltip": "Original crop from background; locates initial center and default size."}),
1532
+ "target_width": ("INT", {"default": 0, "min": 0, "max": _MAX_DIMENSION, "step": 1,
1533
+ "tooltip": "INITIAL width; 0 uses Unedited_Rect width. Optimizer can refine it."}),
1534
+ "target_height": ("INT", {"default": 0, "min": 0, "max": _MAX_DIMENSION, "step": 1,
1535
+ "tooltip": "INITIAL height; 0 uses Unedited_Rect height. Optimized independently of width."}),
1536
+ "max_evaluations": ("INT", {"default": 100, "min": 5, "max": 1000, "step": 1,
1537
+ "tooltip": "Maximum solver function evaluations PER pyramid level. Status reports limits."}),
1538
+ "pyramid_levels": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1,
1539
+ "tooltip": "Coarse-to-fine registration levels. 3 uses smoothing factors 4,2,1."}),
1540
+ "robust_threshold": ("FLOAT", {"default": 0.05, "min": 0.001, "max": 1.0, "step": 0.005,
1541
+ "tooltip": "Soft-L1 RGB threshold: smaller values reduce influence of large appearance edits."}),
1542
+ "scale_limit": ("FLOAT", {"default": 2.0, "min": 1.01, "max": 8.0, "step": 0.1,
1543
+ "tooltip": "Independent width/height ratio bounds: 2 permits 0.5x..2x initial dimensions. Not a pixel increment."}),
1544
+ "min_tolerance": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01,
1545
+ "tooltip": "Minimum crop similarity / 200. 0.9 = 180/200. Always searches for the highest score first; never stops at the first passing location."}),
1546
+ }, "optional": {
1547
+ "background_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
1548
+ "overlay_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
1549
+ "Unedited_Rect_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
1550
+ }}
1551
+
1552
+ inputs["required"].update({
1553
+ "seam_band": ("INT", {"default": 48, "min": 1, "max": 4096, "step": 1,
1554
+ "tooltip": "Width of the rectangle border where a content-aware seam may be chosen. The edited center is protected automatically."}),
1555
+ "feather_pixels": ("INT", {"default": 4, "min": 0, "max": 256, "step": 1,
1556
+ "tooltip": "Small feather across the automatically chosen seam; 0 is a hard cut."}),
1557
+ "multiband": ("BOOLEAN", {"default": False,
1558
+ "tooltip": "Optional OpenCV multiband color correction in the seam transition. Replacement alpha remains exact."}),
1559
+ })
1560
+ return inputs
1561
+
1562
+
1563
+ RETURN_TYPES = ("IMAGE", "IMAGE", "STRING", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT",
1564
+ "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "MASK", "IMAGE", "FLOAT")
1565
+ RETURN_NAMES = ("composite_rgba", "overlay_canvas_rgba", "status", "x", "y", "width", "height", "center_x", "center_y", "similarity",
1566
+ "debug_grid", "composite_preview", "aligned_overlay_preview", "overlay_alpha", "blend_weight", "seam_preview",
1567
+ "blend_mask", "aligned_composite_rgba", "crop_similarity")
1568
+ FUNCTION = "align_and_blend"
1569
+ CATEGORY = "Salia/Image"
1570
+ DESCRIPTION = (
1571
+ "Self-contained GPT_1 node: background + overlay + Unedited_Rect -> crop location, robust continuous alignment, "
1572
+ "original-source EWA and content-aware seam blending. Same image, mask and alignment inputs as the working "
1573
+ "Salia aligner, plus blend controls. No other custom node or its outputs are required. "
1574
+ "RGBA uses embedded alpha; RGB accepts standard Load Image MASKs without inversion. Detailed status and debug views."
1575
+ )
1576
+
1577
+ def align_and_blend(self, background, overlay, Unedited_Rect, target_width=0, target_height=0,
1578
+ max_evaluations=100, pyramid_levels=3, robust_threshold=0.05, scale_limit=2.0,
1579
+ min_tolerance=0.9, seam_band=48, feather_pixels=4, multiband=False,
1580
+ background_mask=None, overlay_mask=None, Unedited_Rect_mask=None):
1581
+ import torch
1582
+ try:
1583
+ from comfy.model_management import throw_exception_if_processing_interrupted as interrupt
1584
+ except ImportError:
1585
+ interrupt = lambda: None
1586
+ try:
1587
+ from comfy.utils import ProgressBar
1588
+ bar, previous = ProgressBar(100), [-1]
1589
+ def progress(value):
1590
+ value = max(0, min(100, int(value)))
1591
+ if value > previous[0]:
1592
+ bar.update_absolute(value, 100)
1593
+ previous[0] = value
1594
+ except ImportError:
1595
+ progress = lambda value: None
1596
+ input_notes = tuple(_pipeline_alpha_description(name, image, mask)
1597
+ for name, image, mask in (("background", background, background_mask),
1598
+ ("overlay", overlay, overlay_mask), ("Unedited_Rect", Unedited_Rect, Unedited_Rect_mask)))
1599
+ bg, canvas = None, None
1600
+ with torch.inference_mode():
1601
+ try:
1602
+ interrupt()
1603
+ bg = _tensor_image(background, "background", background_mask)
1604
+ ov = _tensor_image(overlay, "overlay", overlay_mask)
1605
+ crop = _tensor_image(Unedited_Rect, "Unedited_Rect", Unedited_Rect_mask)
1606
+ output = run_align_and_blend(bg, ov, crop, target_width, target_height,
1607
+ max_evaluations, pyramid_levels, robust_threshold, scale_limit,
1608
+ min_tolerance, seam_band, feather_pixels, multiband,
1609
+ interrupt=interrupt, progress=progress, input_notes=input_notes)
1610
+ except Exception as exc:
1611
+ if type(exc).__name__ == "InterruptProcessingException":
1612
+ raise
1613
+ # If a later input is invalid, preserve the valid processed background.
1614
+ # If only background_mask was invalid, its RGB still makes a useful debug view.
1615
+ if bg is None:
1616
+ try:
1617
+ bg = _tensor_image(background, "background")
1618
+ except (ValueError, TypeError):
1619
+ pass
1620
+ output = _empty_pipeline_outputs(bg, canvas,
1621
+ "GPT_1 INPUT ERROR: %s: %s\n%s" % (type(exc).__name__, exc, "\n".join(input_notes)))
1622
+ values = []
1623
+ for name, kind in zip(self.RETURN_NAMES, self.RETURN_TYPES):
1624
+ if kind in ("IMAGE", "MASK"):
1625
+ values.append(torch.from_numpy(np.ascontiguousarray(output[name], dtype=np.float32)).unsqueeze(0))
1626
+ elif kind == "FLOAT":
1627
+ values.append(float(output[name]))
1628
+ else:
1629
+ values.append(output[name])
1630
+ return tuple(values)
1631
+
1632
+
1633
+ NODE_CLASS_MAPPINGS = {"Salia_Auto_Align_Seam_Blend_GPT_1": Salia_Auto_Align_Seam_Blend_GPT_1}
1634
+ NODE_DISPLAY_NAME_MAPPINGS = {"Salia_Auto_Align_Seam_Blend_GPT_1": "Salia Auto Align + Seam Blend GPT_1"}