saliacoel commited on
Commit
8af973e
·
verified ·
1 Parent(s): 3eeab39

Upload Salia_Auto_Align_Seam_Blend_GPT_2_retry.py

Browse files
Salia_Auto_Align_Seam_Blend_GPT_2_retry.py ADDED
@@ -0,0 +1,1390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Salia Head + Torso Fusion _2_retry.py -- ONE SELF-CONTAINED COMFYUI NODE
3
+ ===================================================================
4
+ Install this ONE file in ComfyUI/custom_nodes/ and restart ComfyUI.
5
+ Menu: Salia/Image -> Salia Head + Torso Fusion _2_retry.py.
6
+ Dependencies: NumPy, SciPy, PyTorch. No other Salia file/node is needed.
7
+
8
+ FOUR SOURCE IMAGES
9
+ background: OLD torso + OLD head; used ONLY to find/align the replacement.
10
+ overlay: ORIGINAL upscaled NEW head, with its real alpha.
11
+ Unedited_Rect: OLD head crop from background, before editing/upscaling.
12
+ background_2: HEADLESS TORSO on the SAME full-size canvas as background.
13
+ The fourth image is the actual lower layer for the final fusion.
14
+
15
+ The original working registration/EWA code is embedded, with the same
16
+ alignment controls and original background/overlay/Unedited_Rect masks.
17
+ Coordinates and the positioned head are handled entirely inside this node.
18
+
19
+ TRANSPARENT PNGs
20
+ Native RGBA uses its embedded alpha. If Load Image splits PNG into RGB+MASK,
21
+ connect each image's matching MASK unchanged to its *_mask input. This node
22
+ converts MASK=1-alpha internally. Do not invert object masks externally.
23
+
24
+ ACTUAL NECK FUSION
25
+ The hard preview is placed NEW head OVER background_2, never over the OLD head.
26
+ The fusion follows the head's lower alpha contour near torso contact, not the
27
+ rectangular crop border. Colors from VISIBLE torso pixels are extended locally
28
+ into the head-side neck and mixed in linear RGB. Normalized local color blur
29
+ ignores hidden RGB. Existing alpha/face/hair outside the neck is preserved.
30
+ Two touching pieces can blend even without an overlap: nearby visible torso
31
+ color supplies the neck-side color reference without creating coverage.
32
+
33
+ neck_blend_width=24: transition length inward from the neck join, output pixels.
34
+ neck_smooth_px=1.5: local alpha-normalized color smoothing, not whole-head blur.
35
+ fusion_strength=1: full fusion. 0 gives the ordinary head-on-headless-torso result.
36
+ bridge_gap_px=4: optional repair of ONLY gaps this small in shared neck columns.
37
+ 0 disables adding pixels. Wider gaps are left unchanged and reported; this
38
+ does not warp geometry or invent an entire missing neck.
39
+
40
+ NECK REGION
41
+ Default: heuristic detection of lower CENTRAL head-to-torso contact. This is
42
+ not semantic human-neck recognition; long hair/poses can need an override.
43
+ Set neck_x/y/width/height (full-canvas pixels; width AND height >0) for a manual
44
+ neck rectangle. Or supply neck_blend_mask: WHITE=neck editable, BLACK=preserve.
45
+ That drawn blend mask is distinct from each sprite's inverted-alpha MASK.
46
+ neck_blend_mask overrides the rectangle. See debug_neck_rgb before tuning.
47
+
48
+ OUTPUTS
49
+ fused_rgba: FINAL fused sprite; use this for saving.
50
+ status: placement, real fusion target, alpha/contact/region/gap details and errors.
51
+ aligned_head_rgba: positioned HEAD ONLY on full-canvas transparency.
52
+ hard_composite_rgba: comparison BEFORE fusion, NEW head over HEADLESS torso.
53
+ debug_fused_rgb / debug_hard_rgb / debug_head_rgb / debug_torso_rgb: checkerboards.
54
+ debug_neck_rgb: cyan=selected neck, green=actual contact, pink=small-gap repair.
55
+ debug_blend_amount_rgb: WHITE=strongest torso-color fusion, BLACK=unchanged.
56
+ debug_gap_fill_rgb: where explicit gap repair added coverage.
57
+ debug_difference_x8_rgb: visible final-vs-hard difference amplified x8.
58
+ output_mask: standard Comfy MASK=1-final alpha.
59
+ All debug_* outputs are RGB IMAGEs suitable for Preview Image.
60
+
61
+ If alignment fails, the final image is background_2 alone, with failure status.
62
+ If no neck contact is found, the hard head-on-torso result is returned with a
63
+ clear warning; inspect real alpha and select a neck rectangle/mask as needed.
64
+ One image per input. No images or geometry from another alignment node needed.
65
+ """
66
+ from __future__ import annotations
67
+ import math
68
+ from functools import lru_cache
69
+ from typing import Callable, Tuple
70
+ import numpy as np
71
+ from scipy import sparse
72
+ from scipy.special import j1, jn_zeros
73
+ _MODES = ("EWA LanczosSharp", "EWA LanczosRadius / Jinc-Jinc")
74
+ _PAIR_BUDGET = 262144
75
+ _LUT_INTERVALS = 65536
76
+ _ALPHA_EPSILON = 1.0e-8
77
+
78
+ def _to_linear(rgb: np.ndarray) -> np.ndarray:
79
+ return np.where(
80
+ rgb <= 0.04045,
81
+ rgb / 12.92,
82
+ np.power((rgb + 0.055) / 1.055, 2.4),
83
+ ).astype(np.float32, copy=False)
84
+
85
+ def _to_srgb(rgb: np.ndarray) -> np.ndarray:
86
+ rgb = np.clip(rgb, 0.0, 1.0)
87
+ return np.where(
88
+ rgb <= 0.0031308,
89
+ rgb * 12.92,
90
+ 1.055 * np.power(rgb, 1.0 / 2.4) - 0.055,
91
+ ).astype(np.float32, copy=False)
92
+
93
+ def _prepare_image(source: np.ndarray) -> np.ndarray:
94
+ if not np.isfinite(source).all():
95
+ raise ValueError("Salia_Rescale_Image: image contains NaN or infinity.")
96
+ image = np.clip(source, 0.0, 1.0).astype(np.float32, copy=True)
97
+ image[..., :3] = _to_linear(image[..., :3])
98
+ if image.shape[-1] == 4:
99
+ image[..., :3] *= image[..., 3:4]
100
+ return image
101
+
102
+ def _finish_image(filtered: np.ndarray, channels: int) -> np.ndarray:
103
+ filtered = np.asarray(filtered, dtype=np.float32)
104
+ rgb = filtered[..., :3]
105
+ if channels == 4:
106
+ raw_alpha = filtered[..., 3:4]
107
+ visible = raw_alpha > _ALPHA_EPSILON
108
+ # Divide by the ORIGINAL filtered alpha, before clipping alpha.
109
+ # Negative-lobe filters can overshoot 1; clipping before division
110
+ # would alter the color of those pixels.
111
+ straight_rgb = np.zeros_like(rgb)
112
+ np.divide(rgb, raw_alpha, out=straight_rgb, where=visible)
113
+ rgb = _to_srgb(straight_rgb)
114
+ alpha = np.where(visible, np.clip(raw_alpha, 0.0, 1.0), 0.0)
115
+ result = np.concatenate((rgb, alpha), axis=-1)
116
+ else:
117
+ result = _to_srgb(rgb)
118
+ return np.ascontiguousarray(np.clip(result, 0.0, 1.0), dtype=np.float32)
119
+
120
+ def _jinc(x: np.ndarray) -> np.ndarray:
121
+ # Normalized Jinc = 2 * J1(pi*x) / (pi*x), with value 1 at zero.
122
+ z = math.pi * np.asarray(x, dtype=np.float64)
123
+ result = np.ones_like(z)
124
+ np.divide(2.0 * j1(z), z, out=result, where=np.abs(z) > 1.0e-12)
125
+ return result
126
+
127
+ @lru_cache(maxsize=2)
128
+ def _ewa_definition(mode: str) -> Tuple[float, np.ndarray, float]:
129
+ first_zero, _, third_zero = jn_zeros(1, 3) / math.pi
130
+ if mode == _MODES[0]:
131
+ blur = 0.9812505644269356
132
+ elif mode == _MODES[1]:
133
+ blur = 3.0 / third_zero
134
+ else:
135
+ raise ValueError("Unknown EWA mode: " + str(mode))
136
+ radius = float(third_zero * blur)
137
+ squared_radius = radius * radius
138
+ # A uniform table in squared distance avoids per-weight square roots.
139
+ squared_distances = np.linspace(0.0, squared_radius, _LUT_INTERVALS + 1)
140
+ r = np.sqrt(squared_distances) / blur
141
+ table = _jinc(r) * _jinc(r * first_zero / third_zero)
142
+ table[-1] = 0.0
143
+ # Duplicate endpoint makes interpolation at/outside support safe.
144
+ table = np.concatenate((table, np.zeros(1, dtype=np.float64)))
145
+ table.setflags(write=False)
146
+ return radius, table, _LUT_INTERVALS / squared_radius
147
+
148
+ def _lookup_ewa(squared_distance: np.ndarray, table: np.ndarray,
149
+ table_scale: float) -> np.ndarray:
150
+ position = np.minimum(squared_distance * table_scale, float(_LUT_INTERVALS))
151
+ index = position.astype(np.intp)
152
+ fraction = position - index
153
+ return table[index] + fraction * (table[index + 1] - table[index])
154
+
155
+ def _ewa_axis(source_size: int, target_size: int,
156
+ radius: float) -> Tuple[np.ndarray, np.ndarray]:
157
+ ratio = source_size / target_size
158
+ footprint_scale = max(1.0, ratio)
159
+ support = radius * footprint_scale
160
+ centers = (np.arange(target_size, dtype=np.float64) + 0.5) * ratio - 0.5
161
+ # All source indices with nonzero support fit in this fixed-width table.
162
+ count = min(source_size, int(math.ceil(2.0 * support)) + 1)
163
+ starts = np.maximum(0, np.ceil(centers - support).astype(np.int64))
164
+ raw_indices = starts[:, None] + np.arange(count, dtype=np.int64)[None, :]
165
+ squared_distance = ((raw_indices - centers[:, None]) / footprint_scale) ** 2
166
+ valid = (raw_indices < source_size) & (squared_distance < radius * radius)
167
+ # Infinity is deliberately mapped to the zero endpoint of the lookup table.
168
+ squared_distance[~valid] = np.inf
169
+ indices = np.minimum(raw_indices, source_size - 1).astype(np.int32)
170
+ return indices, squared_distance
171
+
172
+ def _resize_ewa(image: np.ndarray, out_width: int, out_height: int,
173
+ definition: Tuple[float, np.ndarray, float],
174
+ x_axis: Tuple[np.ndarray, np.ndarray],
175
+ y_axis: Tuple[np.ndarray, np.ndarray],
176
+ interrupt: Callable[[], None],
177
+ progress: Callable[[float], None]) -> np.ndarray:
178
+ _, table, table_scale = definition
179
+ in_height, in_width, channels = image.shape
180
+ x_indices, x_squared = x_axis
181
+ y_indices, y_squared = y_axis
182
+ nx, ny = x_indices.shape[1], y_indices.shape[1]
183
+ total_pixels = out_width * out_height
184
+ output = np.empty((total_pixels, channels), dtype=np.float32)
185
+ # Match the float64 weights once; otherwise SciPy may repeatedly upcast
186
+ # the complete source image for every output tile.
187
+ source_flat = np.ascontiguousarray(image, dtype=np.float64).reshape(-1, channels)
188
+ pixel_block = max(1, min(2048, _PAIR_BUDGET // max(1, nx * ny)))
189
+ index_dtype = np.int32 if in_width * in_height < 2**31 else np.int64
190
+
191
+ for begin in range(0, total_pixels, pixel_block):
192
+ interrupt()
193
+ end = min(begin + pixel_block, total_pixels)
194
+ output_pixels = np.arange(begin, end, dtype=np.int64)
195
+ oy, ox = np.divmod(output_pixels, out_width)
196
+ count = end - begin
197
+ weighted_sum = np.zeros((count, channels), dtype=np.float64)
198
+ weight_sum = np.zeros(count, dtype=np.float64)
199
+ # Also tile source taps, so even a huge reduction to 1x1 doesn't
200
+ # allocate one enormous output_pixels x source_pixels weight array.
201
+ x_chunk = min(nx, max(1, _PAIR_BUDGET // count))
202
+ y_chunk = min(ny, max(1, _PAIR_BUDGET // (count * x_chunk)))
203
+
204
+ for ys in range(0, ny, y_chunk):
205
+ ye = min(ys + y_chunk, ny)
206
+ yi = y_indices[oy, ys:ye]
207
+ dy = y_squared[oy, ys:ye]
208
+ for xs in range(0, nx, x_chunk):
209
+ interrupt()
210
+ xe = min(xs + x_chunk, nx)
211
+ xi = x_indices[ox, xs:xe]
212
+ dx = x_squared[ox, xs:xe]
213
+ distance = dy[:, :, None] + dx[:, None, :]
214
+ weights = _lookup_ewa(distance, table, table_scale)
215
+ taps_per_pixel = (ye - ys) * (xe - xs)
216
+ flat_weights = weights.reshape(count, taps_per_pixel)
217
+ weight_sum += flat_weights.sum(axis=1)
218
+ source_indices = (
219
+ yi.astype(np.int64)[:, :, None] * in_width
220
+ + xi[:, None, :]
221
+ ).astype(index_dtype, copy=False)
222
+ row_pointers = np.arange(count + 1, dtype=np.int64) * taps_per_pixel
223
+ # Sparse multiply avoids materializing a large [pixel,tap,RGBA]
224
+ # gather. Each row is one target pixel's full 2-D footprint.
225
+ operator = sparse.csr_matrix(
226
+ (weights.ravel(), source_indices.ravel(), row_pointers),
227
+ shape=(count, in_width * in_height),
228
+ )
229
+ weighted_sum += operator @ source_flat
230
+ if not np.isfinite(weight_sum).all() or np.any(np.abs(weight_sum) < 1.0e-12):
231
+ raise RuntimeError("Salia_Rescale_Image: degenerate EWA normalization.")
232
+ output[begin:end] = weighted_sum / weight_sum[:, None]
233
+ progress(end / total_pixels)
234
+ return output.reshape(out_height, out_width, channels)
235
+
236
+ class EwaLanczosSharpResizer:
237
+ """Resample each requested size from the original prepared source.
238
+
239
+ Color preparation happens once. No candidate is resized from a previous
240
+ candidate. Axis tables are cheap and computed for each requested size.
241
+ The caller can cache finished candidate images when useful.
242
+ """
243
+ def __init__(self, source: np.ndarray, interrupt: Callable[[], None] = lambda: None):
244
+ source = np.asarray(source)
245
+ if source.ndim != 3 or source.shape[2] not in (3, 4) or min(source.shape[:2]) < 1:
246
+ raise ValueError("EWA source must be a nonempty HWC RGB/RGBA array.")
247
+ if not np.isfinite(source).all():
248
+ raise ValueError("EWA source contains NaN or infinity.")
249
+ self.source = np.ascontiguousarray(source, dtype=np.float32)
250
+ self.prepared = _prepare_image(self.source)
251
+ self.definition = _ewa_definition(_MODES[0])
252
+ self.interrupt = interrupt
253
+
254
+ def resize(self, width: int, height: int) -> np.ndarray:
255
+ if width < 1 or height < 1:
256
+ raise ValueError("EWA dimensions must be positive.")
257
+ self.interrupt()
258
+ if (int(width), int(height)) == (self.source.shape[1], self.source.shape[0]):
259
+ return self.source.copy()
260
+ radius = self.definition[0]
261
+ x_axis = _ewa_axis(self.source.shape[1], int(width), radius)
262
+ y_axis = _ewa_axis(self.source.shape[0], int(height), radius)
263
+ filtered = _resize_ewa(
264
+ self.prepared, int(width), int(height), self.definition,
265
+ x_axis, y_axis, self.interrupt, lambda value: None,
266
+ )
267
+ self.interrupt()
268
+ return _finish_image(filtered, self.source.shape[2])
269
+
270
+
271
+ def resize_rgba_ewa(source: np.ndarray, width: int, height: int,
272
+ interrupt: Callable[[], None] = lambda: None) -> np.ndarray:
273
+ """Standalone original-source EWA LanczosSharp resize (RGB or RGBA)."""
274
+ return EwaLanczosSharpResizer(source, interrupt).resize(width, height)
275
+
276
+
277
+
278
+ import logging
279
+ import time
280
+ from scipy.signal import correlate
281
+ __version__ = "2.2.0"
282
+ _LOG = logging.getLogger(__name__)
283
+ _MAX_DIMENSION = 32768
284
+ _RGB_COPY_ERROR_TOLERANCE = 1.0e-6
285
+
286
+ def _rgba_array(image, name="image"):
287
+ """Private normalized float32 copy; hidden RGB is retained but never scored."""
288
+ result = np.asarray(image)
289
+ if result.ndim != 3 or result.shape[-1] not in (3, 4):
290
+ raise ValueError("%s must be HWC RGB or RGBA." % name)
291
+ if min(result.shape[:2]) < 1:
292
+ raise ValueError("%s is empty." % name)
293
+ if not np.issubdtype(result.dtype, np.floating):
294
+ raise ValueError("%s must contain floating-point values in [0, 1]." % name)
295
+ if not np.isfinite(result).all():
296
+ raise ValueError("%s contains NaN or infinity." % name)
297
+ result = np.clip(result, 0.0, 1.0).astype(np.float32, copy=True)
298
+ if result.shape[-1] == 3:
299
+ result = np.concatenate((result, np.ones((*result.shape[:2], 1), np.float32)), axis=-1)
300
+ return np.ascontiguousarray(result)
301
+
302
+ def _weights(template):
303
+ alpha = template[..., 3].astype(np.float64)
304
+ return np.where(alpha > _ALPHA_EPSILON, alpha, 0.0)
305
+
306
+ def _color_error(background, template):
307
+ # Straight sRGB, not premultiplied RGB: half-alpha green can match green.
308
+ delta = background[..., :3].astype(np.float64) - template[..., :3]
309
+ error = np.mean(delta * delta, axis=-1)
310
+ return np.where(background[..., 3] > _ALPHA_EPSILON, error, 1.0)
311
+
312
+ def GET_RECTS_SIMILARITY(rect1, rect2, template_mode=False):
313
+ """Compare equal-size HWC float RGB/RGBA rectangles; return 0..200.
314
+
315
+ Default is symmetric: weight by max(alpha1, alpha2); RGB differences
316
+ count only when BOTH pixels are visible. A visible/invisible pair has
317
+ maximum error. If both pixels are invisible, hidden RGB is irrelevant.
318
+ Positive alpha magnitudes are confidence weights, not color darkness.
319
+ Thus solid green at alpha .5 and at alpha 1 have similarity 200.
320
+
321
+ template_mode=True is directional: rect1 is background; rect2 is the
322
+ template. Only rect2 alpha weights the score, so its transparent padding
323
+ does not punish a visible background. Used for locating and refining.
324
+ A fully transparent template raises ValueError (no matching evidence).
325
+ """
326
+ a, b = _rgba_array(rect1, "rect1"), _rgba_array(rect2, "rect2")
327
+ if a.shape != b.shape:
328
+ raise ValueError("GET_RECTS_SIMILARITY requires equal rectangle dimensions.")
329
+ if template_mode:
330
+ weight = _weights(b)
331
+ total = float(weight.sum())
332
+ if total <= 0.0:
333
+ raise ValueError("A fully transparent template has no matching information.")
334
+ error = float(np.sum(weight * _color_error(a, b)) / total)
335
+ else:
336
+ aa, ba = _weights(a), _weights(b)
337
+ weight = np.maximum(aa, ba)
338
+ total = float(weight.sum())
339
+ if total <= 0.0:
340
+ return 200.0
341
+ visible_both = (aa > 0.0) & (ba > 0.0)
342
+ delta = a[..., :3].astype(np.float64) - b[..., :3]
343
+ pixel_error = np.where(visible_both, np.mean(delta * delta, axis=-1), 1.0)
344
+ error = float(np.sum(weight * pixel_error) / total)
345
+ return float(200.0 * (1.0 - np.clip(error, 0.0, 1.0)))
346
+
347
+ def _overlap(background, template, x, y):
348
+ bh, bw = background.shape[:2]
349
+ th, tw = template.shape[:2]
350
+ x0, y0 = max(0, x), max(0, y)
351
+ x1, y1 = min(bw, x + tw), min(bh, y + th)
352
+ if x1 <= x0 or y1 <= y0:
353
+ return None
354
+ return (slice(y0, y1), slice(x0, x1),
355
+ slice(y0 - y, y1 - y), slice(x0 - x, x1 - x))
356
+
357
+ def _error_at(background, template, x, y, respect_background_alpha=True):
358
+ """Full template normalization: clipping outside the canvas cannot win."""
359
+ weight = _weights(template)
360
+ total = float(weight.sum())
361
+ if total <= 0.0:
362
+ return float("inf")
363
+ overlap = _overlap(background, template, x, y)
364
+ if overlap is None:
365
+ return 1.0
366
+ by, bx, ty, tx = overlap
367
+ inside_weight = weight[ty, tx]
368
+ # Off-canvas visible pixels are maximum mismatch, not discarded samples.
369
+ outside_error = max(0.0, total - float(inside_weight.sum()))
370
+ if respect_background_alpha:
371
+ pixel_error = _color_error(background[by, bx], template[ty, tx])
372
+ else:
373
+ delta = background[by, bx, :3].astype(np.float64) - template[ty, tx, :3]
374
+ pixel_error = np.mean(delta * delta, axis=-1)
375
+ inside_error = np.sum(inside_weight * pixel_error)
376
+ return float(np.clip((outside_error + inside_error) / total, 0.0, 1.0))
377
+
378
+ def _locate_unedited(background, template, interrupt=lambda: None, respect_background_alpha=True):
379
+ """Evaluate every fully-contained placement using weighted RGB SSD.
380
+
381
+ FFT correlation is an algebraic acceleration of the SAME per-pixel
382
+ error. No image pyramid, approximate search, or reduced-resolution crop.
383
+ Re-evaluate near-best candidates directly to remove FFT roundoff.
384
+ """
385
+ bh, bw = background.shape[:2]
386
+ th, tw = template.shape[:2]
387
+ if tw > bw or th > bh:
388
+ raise ValueError("Unedited_Rect is larger than background; it cannot be a crop of it.")
389
+ weight = _weights(template)
390
+ total = float(weight.sum())
391
+ if total <= 0.0:
392
+ raise ValueError("Unedited_Rect is fully transparent; its position cannot be located.")
393
+ visible = ((background[..., 3] > _ALPHA_EPSILON).astype(np.float64)
394
+ if respect_background_alpha else np.ones((bh, bw), dtype=np.float64))
395
+ if not np.any(visible):
396
+ # Every placement has the same maximum appearance error. Avoid
397
+ # directly rescoring every all-transparent location in a large image.
398
+ return 0, 0, 1.0, (bh - th + 1) * (bw - tw + 1)
399
+ rgb = background[..., :3].astype(np.float64)
400
+ template_rgb = template[..., :3].astype(np.float64)
401
+
402
+ def corr(a, b):
403
+ interrupt()
404
+ result = correlate(a, b, mode="valid", method="fft")
405
+ interrupt()
406
+ return result
407
+
408
+ background_square = np.mean(rgb * rgb, axis=-1)
409
+ template_square = np.mean(template_rgb * template_rgb, axis=-1)
410
+ if np.all(visible):
411
+ errors = corr(background_square, weight)
412
+ errors += float(np.sum(weight * template_square))
413
+ for channel in range(3):
414
+ errors -= (2.0 / 3.0) * corr(rgb[..., channel], weight * template_rgb[..., channel])
415
+ else:
416
+ errors = corr(1.0 - visible + visible * background_square, weight)
417
+ errors += corr(visible, weight * template_square)
418
+ for channel in range(3):
419
+ errors -= (2.0 / 3.0) * corr(visible * rgb[..., channel], weight * template_rgb[..., channel])
420
+ errors /= total
421
+ np.clip(errors, 0.0, 1.0, out=errors)
422
+ minimum = float(errors.min())
423
+ near_best = np.flatnonzero(errors.ravel() <= minimum + 1.0e-12)
424
+ # Never drop a possible best match because many low-contrast positions
425
+ # share a near-equal FFT score. Check the earliest candidate and the FFT
426
+ # argmin first, then every remaining near-best candidate if necessary.
427
+ # A directly verified EXACT zero is the mathematical lower bound, so
428
+ # only that allows early exit. Uniform duplicate crops stop immediately.
429
+ fft_best = int(np.argmin(errors))
430
+ first = int(near_best[0])
431
+ candidates = (first, fft_best)
432
+ best_error, best_x, best_y = float("inf"), 0, 0
433
+ from itertools import chain
434
+ for flat in chain(candidates, (int(k) for k in near_best if k != first and k != fft_best)):
435
+ interrupt()
436
+ y, x = divmod(int(flat), errors.shape[1])
437
+ error = _error_at(background, template, x, y, respect_background_alpha)
438
+ if error < best_error:
439
+ best_error, best_x, best_y = error, x, y
440
+ if best_error == 0.0:
441
+ break
442
+ return best_x, best_y, best_error, int(near_best.size)
443
+
444
+ def _source_over(background, template, x, y):
445
+ """Straight-alpha source-over in sRGB; only the pasted region changes."""
446
+ composite = background.copy()
447
+ canvas = np.zeros_like(background)
448
+ overlap = _overlap(background, template, x, y)
449
+ if overlap is None:
450
+ return composite, canvas
451
+ by, bx, ty, tx = overlap
452
+ source, target = template[ty, tx], background[by, bx]
453
+ canvas[by, bx] = source
454
+ source_alpha, target_alpha = source[..., 3:4], target[..., 3:4]
455
+ alpha = source_alpha + target_alpha * (1.0 - source_alpha)
456
+ premultiplied = (source[..., :3] * source_alpha
457
+ + target[..., :3] * target_alpha * (1.0 - source_alpha))
458
+ rgb = np.zeros_like(premultiplied)
459
+ np.divide(premultiplied, alpha, out=rgb, where=alpha > _ALPHA_EPSILON)
460
+ result = np.concatenate((np.clip(rgb, 0.0, 1.0), alpha), axis=-1)
461
+ # Preserve the background exactly under fully transparent overlay pixels.
462
+ composite[by, bx] = np.where(source_alpha > 0.0, result, target)
463
+ # Canonical invisible RGB on the otherwise empty overlay canvas.
464
+ canvas[..., :3][canvas[..., 3] <= 0.0] = 0.0
465
+ return composite, canvas
466
+
467
+ def _tensor_image(image, name, mask=None):
468
+ import torch
469
+ if not isinstance(image, torch.Tensor) or image.ndim != 4 or image.shape[0] != 1:
470
+ raise ValueError("%s must be one IMAGE shaped [1,H,W,3 or 4]; split batches first." % name)
471
+ if not image.is_floating_point():
472
+ raise ValueError("%s must be a floating-point IMAGE." % name)
473
+ result = _rgba_array(image[0].detach().to(device="cpu", dtype=torch.float32).numpy(), name)
474
+ # Embedded alpha is authoritative for RGBA. Do not replace, multiply or
475
+ # invert it through the external MASK, even if that mask is connected.
476
+ if int(image.shape[-1]) == 4:
477
+ return result
478
+ if mask is not None:
479
+ if not isinstance(mask, torch.Tensor):
480
+ raise ValueError("%s_mask must be a ComfyUI MASK tensor." % name)
481
+ value = mask.detach().to(device="cpu", dtype=torch.float32).numpy()
482
+ if value.ndim == 3 and value.shape[0] == 1:
483
+ value = value[0]
484
+ if value.shape != result.shape[:2]:
485
+ # Standard Load Image's no-alpha placeholder is a 64x64 all-zero
486
+ # MASK even when its RGB image has another resolution.
487
+ if value.shape == (64, 64) and not np.any(value):
488
+ value = np.zeros(result.shape[:2], dtype=np.float32)
489
+ else:
490
+ raise ValueError("%s_mask resolution must match %s. Masks are not resized." % (name, name))
491
+ if not np.isfinite(value).all():
492
+ raise ValueError("%s_mask contains NaN or infinity." % name)
493
+ # RGB has no alpha: reconstruct it from the Comfy Load Image MASK.
494
+ result[..., 3] = 1.0 - np.clip(value, 0.0, 1.0)
495
+ # Preserve the fact that RGB had NO alpha. Promoting it here used to erase
496
+ # that information before crop-location diagnostics and recovery.
497
+ if mask is None and int(image.shape[-1]) == 3:
498
+ return np.ascontiguousarray(result[..., :3])
499
+ return result
500
+
501
+ # ---------------------------------------------------------------------------
502
+ # Original-source EWA rendering with continuous rectangle geometry.
503
+ # The numerical filter/color helpers above are intentionally shared with the
504
+ # supplied Salia_Rescale_Image implementation. There is no second resize pass.
505
+ # ---------------------------------------------------------------------------
506
+
507
+ def _ewa_axis_at_centers(source_size, centers, source_per_output_pixel, radius):
508
+ """EWA source taps for arbitrary source-coordinate pixel centers.
509
+
510
+ ``centers`` are source pixel-center coordinates (first center is zero).
511
+ Footprint widening uses the continuous source/output scale, independent
512
+ of how many destination pixels happen to survive canvas clipping.
513
+ """
514
+ centers = np.asarray(centers, dtype=np.float64)
515
+ footprint = max(1.0, float(source_per_output_pixel))
516
+ support = radius * footprint
517
+ count = min(int(source_size), int(math.ceil(2.0 * support)) + 1)
518
+ starts = np.maximum(0, np.ceil(centers - support).astype(np.int64))
519
+ raw_indices = starts[:, None] + np.arange(count, dtype=np.int64)[None, :]
520
+ squared_distance = ((raw_indices - centers[:, None]) / footprint) ** 2
521
+ valid = (raw_indices < source_size) & (squared_distance < radius * radius)
522
+ squared_distance[~valid] = np.inf
523
+ indices = np.minimum(raw_indices, source_size - 1).astype(np.int32)
524
+ return indices, squared_distance
525
+
526
+
527
+ def render_rgba_ewa(source, background_width, background_height,
528
+ center_x, center_y, width, height, interrupt=lambda: None):
529
+ """Render a continuous RGBA rectangle from its original source, once.
530
+
531
+ Return ``(patch_rgba, x0, y0)``. ``x0/y0`` are integer pixel-edge canvas
532
+ coordinates; ``patch_rgba`` contains only the clipped destination bbox.
533
+ The requested rectangle has floating pixel-edge bounds
534
+ ``[center_x-width/2, center_x+width/2]`` and corresponding Y bounds.
535
+ Destination pixel centers are inverse-mapped directly to the original
536
+ source. RGB filtering is linear-light and alpha-premultiplied. Source
537
+ edge taps are truncated and normalized just as in the original rescaler.
538
+
539
+ The fraction of a destination pixel covered by the rectangle multiplies
540
+ filtered alpha (not RGB). This antialiases fractional outer bounds without
541
+ darkening their straight RGB. Filtering and placement stay continuous;
542
+ width, height and position are never rounded to an integer transform.
543
+
544
+ For integer-aligned geometry the output is the original resizer's output
545
+ cropped to the background. Same-size integer-aligned requests are exact
546
+ no-ops on pixel values, including hidden RGB, matching that resizer.
547
+ Empty overlap returns float32 array ``(0,0,4)`` and a clipped origin.
548
+ """
549
+ interrupt()
550
+ source = np.asarray(source)
551
+ if (source.ndim != 3 or source.shape[-1] != 4
552
+ or min(source.shape[:2]) < 1
553
+ or not np.issubdtype(source.dtype, np.floating)):
554
+ raise ValueError("render_rgba_ewa expects a nonempty floating HWC RGBA image.")
555
+ geometry = np.asarray((center_x, center_y, width, height), dtype=np.float64)
556
+ if not np.isfinite(geometry).all() or width < 1.0 or height < 1.0:
557
+ raise ValueError("EWA rectangle geometry must be finite with width/height >= 1.")
558
+ if (isinstance(background_width, bool) or isinstance(background_height, bool)
559
+ or int(background_width) != background_width
560
+ or int(background_height) != background_height
561
+ or background_width < 1 or background_height < 1):
562
+ raise ValueError("EWA background dimensions must be positive integers.")
563
+ if not np.isfinite(source).all():
564
+ raise ValueError("EWA source contains NaN or infinity.")
565
+ source = np.ascontiguousarray(np.clip(source, 0.0, 1.0), dtype=np.float32)
566
+ bw, bh = int(background_width), int(background_height)
567
+ left, top = float(center_x - width / 2.0), float(center_y - height / 2.0)
568
+ right, bottom = left + float(width), top + float(height)
569
+ x0 = max(0, min(bw, int(math.floor(left))))
570
+ y0 = max(0, min(bh, int(math.floor(top))))
571
+ x1 = max(0, min(bw, int(math.ceil(right))))
572
+ y1 = max(0, min(bh, int(math.ceil(bottom))))
573
+ if x1 <= x0 or y1 <= y0:
574
+ return np.empty((0, 0, 4), dtype=np.float32), x0, y0
575
+ source_height, source_width = source.shape[:2]
576
+ if (float(width) == source_width and float(height) == source_height
577
+ and left == math.floor(left) and top == math.floor(top)):
578
+ return (source[y0 - int(top):y1 - int(top),
579
+ x0 - int(left):x1 - int(left)].copy(), x0, y0)
580
+
581
+ definition = _ewa_definition(_MODES[0])
582
+ ratio_x, ratio_y = source_width / float(width), source_height / float(height)
583
+ output_x = np.arange(x0, x1, dtype=np.float64)
584
+ output_y = np.arange(y0, y1, dtype=np.float64)
585
+ source_x = (output_x + 0.5 - left) * ratio_x - 0.5
586
+ source_y = (output_y + 0.5 - top) * ratio_y - 0.5
587
+ x_axis = _ewa_axis_at_centers(source_width, source_x, ratio_x, definition[0])
588
+ y_axis = _ewa_axis_at_centers(source_height, source_y, ratio_y, definition[0])
589
+ filtered = _resize_ewa(_prepare_image(source), x1 - x0, y1 - y0,
590
+ definition, x_axis, y_axis, interrupt, lambda value: None)
591
+ result = _finish_image(filtered, 4)
592
+ coverage_x = np.maximum(0.0, np.minimum(output_x + 1.0, right)
593
+ - np.maximum(output_x, left))
594
+ coverage_y = np.maximum(0.0, np.minimum(output_y + 1.0, bottom)
595
+ - np.maximum(output_y, top))
596
+ result[..., 3] *= (coverage_y[:, None] * coverage_x[None, :]).astype(np.float32)
597
+ result[..., :3][result[..., 3] <= 0.0] = 0.0
598
+ interrupt()
599
+ return np.ascontiguousarray(result, dtype=np.float32), x0, y0
600
+
601
+
602
+ # ---------------------------------------------------------------------------
603
+ # Joint continuous alpha-aware registration (X, Y, width and height together).
604
+ # ---------------------------------------------------------------------------
605
+
606
+ from scipy.ndimage import gaussian_filter, map_coordinates, spline_filter
607
+ from scipy.optimize import least_squares
608
+
609
+ _MATCH_MAX_SIDE = 768
610
+ _MATCH_MAX_SAMPLES = 20000
611
+
612
+
613
+ def _premultiplied_fields(image, sigma_y=0.0, sigma_x=0.0, with_valid=False):
614
+ """Float64 fields prevent hidden RGB leakage during blur/interpolation."""
615
+ alpha = image[..., 3].astype(np.float64)
616
+ fields = np.concatenate((image[..., :3].astype(np.float64) * alpha[..., None],
617
+ alpha[..., None]), axis=-1)
618
+ if with_valid:
619
+ fields = np.concatenate((fields, (alpha > _ALPHA_EPSILON)[..., None].astype(np.float64)), axis=-1)
620
+ if sigma_y > 0.0 or sigma_x > 0.0:
621
+ fields = gaussian_filter(fields, sigma=(sigma_y, sigma_x, 0.0), mode="nearest")
622
+ return fields
623
+
624
+
625
+ def _straight_fields(fields):
626
+ alpha = np.clip(fields[..., 3], 0.0, 1.0)
627
+ rgb = np.zeros_like(fields[..., :3])
628
+ np.divide(fields[..., :3], alpha[..., None], out=rgb,
629
+ where=alpha[..., None] > _ALPHA_EPSILON)
630
+ return np.clip(rgb, 0.0, 1.0), alpha
631
+
632
+
633
+ class _RegistrationLevel:
634
+ """Fixed source samples and confidence; moving support cannot erase error.
635
+
636
+ Parameter vector: normalized center offsets and log width/height ratios.
637
+ A custom SciPy soft-L1 loss applies alpha AFTER robustification, so alpha
638
+ is a confidence weight rather than an RGB channel or a brightness change.
639
+ """
640
+ def __init__(self, background, template, center_x, center_y, initial_width,
641
+ initial_height, factor, robust_threshold, interrupt, on_call):
642
+ self.center_x, self.center_y = float(center_x), float(center_y)
643
+ self.initial_width, self.initial_height = float(initial_width), float(initial_height)
644
+ self.background_height, self.background_width = background.shape[:2]
645
+ self.robust_threshold = float(robust_threshold)
646
+ self.interrupt, self.on_call = interrupt, on_call
647
+ self.calls = 0
648
+ sigma = 0.5 * factor if factor > 1 else 0.0
649
+ source_fields = _premultiplied_fields(template, sigma, sigma)
650
+ source_rgb, source_alpha = _straight_fields(source_fields)
651
+ valid = np.flatnonzero(source_alpha.ravel() > _ALPHA_EPSILON)
652
+ if not valid.size:
653
+ raise ValueError("The overlay has no visible samples at this matching resolution.")
654
+ budget = max(1024, _MATCH_MAX_SAMPLES // factor)
655
+ if valid.size > budget:
656
+ # A fixed seed/subset for this level: never change the samples as
657
+ # a function of the transform being tested.
658
+ valid = np.sort(np.random.default_rng(0).choice(valid, budget, replace=False))
659
+ sy, sx = np.divmod(valid, template.shape[1])
660
+ self.u = (sx.astype(np.float64) + 0.5) / template.shape[1] - 0.5
661
+ self.v = (sy.astype(np.float64) + 0.5) / template.shape[0] - 0.5
662
+ self.source_rgb = source_rgb.reshape(-1, 3)[valid]
663
+ confidence = source_alpha.ravel()[valid]
664
+ self.confidence = confidence / confidence.sum()
665
+ self.count = len(valid)
666
+ self.loss_weights = np.concatenate((np.repeat(self.confidence / 3.0, 3),
667
+ self.confidence, np.full(4, 1.0e-7)))
668
+
669
+ # Match antialiasing to the initial physical size, including a source
670
+ # registration-resolution cap. This pyramid is for fitting only;
671
+ # final output is rendered directly from the original overlay.
672
+ ratio_x = initial_width / template.shape[1]
673
+ ratio_y = initial_height / template.shape[0]
674
+ sigma_x = max(sigma * ratio_x, 0.35 * max(0.0, ratio_x - 1.0))
675
+ sigma_y = max(sigma * ratio_y, 0.35 * max(0.0, ratio_y - 1.0))
676
+ interrupt()
677
+ background_fields = _premultiplied_fields(background, sigma_y, sigma_x, with_valid=True)
678
+ # Cubic interpolation needs coefficients computed just once per level.
679
+ self.coefficients = [spline_filter(background_fields[..., c], order=3, mode="mirror")
680
+ for c in range(5)]
681
+ interrupt()
682
+
683
+ def geometry(self, p):
684
+ return (self.center_x + p[0] * self.initial_width,
685
+ self.center_y + p[1] * self.initial_height,
686
+ self.initial_width * math.exp(float(p[2])),
687
+ self.initial_height * math.exp(float(p[3])))
688
+
689
+ def differences(self, p):
690
+ self.interrupt()
691
+ center_x, center_y, width, height = self.geometry(p)
692
+ x = center_x + self.u * width - 0.5
693
+ y = center_y + self.v * height - 0.5
694
+ coordinates = np.vstack((y, x))
695
+ sampled = np.stack([map_coordinates(c, coordinates, order=3, mode="constant",
696
+ cval=0.0, prefilter=False)
697
+ for c in self.coefficients], axis=-1)
698
+ rgb, alpha = _straight_fields(sampled[..., :4])
699
+ visible = np.clip(sampled[..., 4], 0.0, 1.0)
700
+ visible = np.where(alpha > _ALPHA_EPSILON, visible, 0.0)
701
+ delta = (rgb - self.source_rgb) * visible[:, None]
702
+ # Retain every fixed source sample. Off-canvas/transparent reference
703
+ # samples carry a penalty instead of dropping out of the objective.
704
+ # Outside distance supplies a gradient back toward the canvas.
705
+ outside_x = np.maximum(-x, 0.0) + np.maximum(x - (self.background_width - 1), 0.0)
706
+ outside_y = np.maximum(-y, 0.0) + np.maximum(y - (self.background_height - 1), 0.0)
707
+ outside = (outside_x / max(1.0, self.initial_width * 0.1)
708
+ + outside_y / max(1.0, self.initial_height * 0.1))
709
+ missing = 1.0 - visible + outside
710
+ return delta, missing
711
+
712
+ def residual(self, p):
713
+ self.calls += 1
714
+ self.on_call(self.calls)
715
+ delta, missing = self.differences(p)
716
+ return np.concatenate((delta.ravel(), missing, np.asarray(p, dtype=np.float64)))
717
+
718
+ def loss(self, z):
719
+ root = np.sqrt(1.0 + z)
720
+ rho = np.vstack((2.0 * (root - 1.0), 1.0 / root, -0.5 / (root ** 3)))
721
+ rho *= self.loss_weights[None, :]
722
+ # Tiny quadratic preference for the original geometry breaks exact
723
+ # appearance ties; it is not part of the reported image similarity.
724
+ rho[0, -4:] = self.loss_weights[-4:] * z[-4:]
725
+ rho[1, -4:] = self.loss_weights[-4:]
726
+ rho[2, -4:] = 0.0
727
+ return rho
728
+
729
+ def cost(self, p):
730
+ residual = self.residual(p)
731
+ scale = self.robust_threshold
732
+ return float(0.5 * scale * scale * self.loss((residual / scale) ** 2)[0].sum())
733
+
734
+ def similarity(self, p):
735
+ delta, missing = self.differences(p)
736
+ error = np.sum(self.confidence * (np.mean(delta * delta, axis=-1) + missing * missing))
737
+ return float(200.0 * (1.0 - np.clip(error, 0.0, 1.0)))
738
+
739
+
740
+ def _validate_registration_options(target_width, target_height, max_evaluations,
741
+ pyramid_levels, robust_threshold, scale_limit, min_tolerance=0.9):
742
+ for name, value, lo, hi in (
743
+ ("target_width", target_width, 0, _MAX_DIMENSION),
744
+ ("target_height", target_height, 0, _MAX_DIMENSION),
745
+ ("max_evaluations", max_evaluations, 5, 1000),
746
+ ("pyramid_levels", pyramid_levels, 1, 5),
747
+ ):
748
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not lo <= value <= hi:
749
+ raise ValueError("%s must be an integer in [%d,%d]." % (name, lo, hi))
750
+ for name, value, lo, hi in (("robust_threshold", robust_threshold, 0.001, 1.0),
751
+ ("scale_limit", scale_limit, 1.01, 8.0),
752
+ ("min_tolerance", min_tolerance, 0.0, 1.0)):
753
+ if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
754
+ raise ValueError("%s must be a finite number in [%g,%g]." % (name, lo, hi))
755
+ if not math.isfinite(float(value)) or not lo <= value <= hi:
756
+ raise ValueError("%s must be a finite number in [%g,%g]." % (name, lo, hi))
757
+
758
+
759
+ def _input_alpha_description(name, rgba, input_channels):
760
+ alpha = rgba[..., 3]
761
+ transparent = float(np.mean(alpha <= _ALPHA_EPSILON) * 100.0)
762
+ opaque = float(np.mean(alpha >= 1.0 - _ALPHA_EPSILON) * 100.0)
763
+ return ("%s=%dx%d, input_channels=%d, alpha_zero=%.2f%%, alpha_opaque=%.2f%%"
764
+ % (name, rgba.shape[1], rgba.shape[0], input_channels, transparent, opaque))
765
+
766
+
767
+ def align_arrays(background, overlay, unedited_rect, target_width=0, target_height=0,
768
+ max_evaluations=100, pyramid_levels=3, robust_threshold=0.05,
769
+ scale_limit=2.0, interrupt=lambda: None, progress=lambda value: None,
770
+ min_tolerance=0.9):
771
+ """Locate the crop, jointly optimize four continuous values, then render.
772
+
773
+ No pixel-step grid, alternating move/scale phase, rotation, shear, or
774
+ optical flow. SciPy's bounded robust least-squares optimizer works on an
775
+ alpha-safe antialiased matching pyramid. EWA renders the original once.
776
+ """
777
+ started = time.monotonic()
778
+ _validate_registration_options(target_width, target_height, max_evaluations,
779
+ pyramid_levels, robust_threshold, scale_limit, min_tolerance)
780
+ min_crop_similarity = float(min_tolerance) * 200.0
781
+ raw_inputs = (background, overlay, unedited_rect)
782
+ background = _rgba_array(background, "background")
783
+ overlay = _rgba_array(overlay, "overlay")
784
+ unedited_rect = _rgba_array(unedited_rect, "Unedited_Rect")
785
+ descriptions = [
786
+ _input_alpha_description(name, rgba, int(np.asarray(raw).shape[-1]))
787
+ for name, raw, rgba in zip(("background", "overlay", "Unedited_Rect"),
788
+ raw_inputs, (background, overlay, unedited_rect))
789
+ ]
790
+ input_diagnostics = "Inputs:\n" + "\n".join(descriptions)
791
+ if float(_weights(overlay).sum()) <= 0.0:
792
+ raise ValueError("overlay is fully transparent; there is nothing to align or paste.")
793
+ interrupt()
794
+ crop_x, crop_y, crop_error, ties = _locate_unedited(background, unedited_rect, interrupt)
795
+ crop_match_mode = "alpha-aware crop appearance"
796
+ crop_notes = []
797
+ # A Load Image IMAGE output is RGB. If its MASK is missing while the
798
+ # background retains alpha, treating that RGB crop as genuinely opaque
799
+ # turns matching transparent padding into a maximum-error penalty.
800
+ # Recover ONLY when the actual RGB values provide a near-exact copy
801
+ # match. Do not cherry-pick arbitrary low-scoring fallback locations.
802
+ if (crop_error > 1.0e-8
803
+ and np.all(unedited_rect[..., 3] >= 1.0 - _ALPHA_EPSILON)
804
+ and np.any(background[..., 3] <= _ALPHA_EPSILON)):
805
+ rgb_x, rgb_y, rgb_error, rgb_ties = _locate_unedited(
806
+ background, unedited_rect, interrupt, respect_background_alpha=False)
807
+ rgb_region = background[rgb_y:rgb_y + unedited_rect.shape[0],
808
+ rgb_x:rgb_x + unedited_rect.shape[1]]
809
+ visible_evidence = int(np.count_nonzero(rgb_region[..., 3] > _ALPHA_EPSILON))
810
+ minimum_evidence = min(16, unedited_rect.shape[0] * unedited_rect.shape[1])
811
+ rgb_texture = float(np.mean(np.var(unedited_rect[..., :3].astype(np.float64), axis=(0, 1))))
812
+ trustworthy_rgb = visible_evidence >= minimum_evidence and rgb_texture > 1.0e-10
813
+ if (rgb_error <= _RGB_COPY_ERROR_TOLERANCE and rgb_error < crop_error
814
+ and trustworthy_rgb):
815
+ crop_notes.append(
816
+ "Alpha-aware candidate (%d,%d) scored %.8f/200. A near-exact RGB copy instead matched (%d,%d)."
817
+ % (crop_x, crop_y, 200.0 * (1.0 - crop_error), rgb_x, rgb_y))
818
+ crop_notes.append(
819
+ "Crop alpha may be missing: connect the crop's matching Load Image MASK. "
820
+ "RGB fallback applies to crop location only; overlay output still needs its own real alpha/MASK.")
821
+ crop_x, crop_y, crop_error, ties = rgb_x, rgb_y, rgb_error, rgb_ties
822
+ crop_match_mode = "verified near-exact RGB-copy fallback"
823
+ elif rgb_error <= _RGB_COPY_ERROR_TOLERANCE and not trustworthy_rgb:
824
+ crop_notes.append(
825
+ "An RGB-only candidate had insufficient visible/texture evidence and was not accepted. "
826
+ "Hidden RGB in transparent pixels cannot establish a reliable visible match.")
827
+ crop_similarity = 200.0 * (1.0 - crop_error)
828
+ # The search above evaluates all placements and selects the highest
829
+ # score. Tolerance is an acceptance check ONLY, never an early exit.
830
+ if crop_similarity < min_crop_similarity:
831
+ # Solver convergence is not evidence of correct crop localization.
832
+ # Return an explicit failure through the existing status socket and
833
+ # preserve background instead of pasting a wrong result somewhere.
834
+ status = "\n".join([
835
+ "LOCATION FAILED: original crop was not located reliably. No overlay was pasted.",
836
+ "Closest candidate: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200; required >= %.4f/200."
837
+ % (crop_x, crop_y, unedited_rect.shape[1], unedited_rect.shape[0], crop_similarity,
838
+ min_crop_similarity),
839
+ "min_tolerance=%.6f. The highest-scoring location was selected before checking this minimum."
840
+ % float(min_tolerance),
841
+ "The best available crop match did not meet the configured minimum. "
842
+ "Check image wiring, crop resizing/flipping, and corresponding MASK/alpha inputs.",
843
+ "Output coordinates=-1 and dimensions=0 indicate no accepted placement.",
844
+ input_diagnostics, *crop_notes,
845
+ ])
846
+ progress(100)
847
+ _LOG.warning("Salia: rejected unverified crop at (%d,%d), similarity %.8f/200", crop_x, crop_y, crop_similarity)
848
+ return {"composite": background.copy(), "overlay_canvas": np.zeros_like(background),
849
+ "status": status, "x": -1.0, "y": -1.0, "width": 0.0, "height": 0.0,
850
+ "center_x": -1.0, "center_y": -1.0, "similarity": 0.0,
851
+ "registration_similarity": 0.0, "robust_cost": None, "initial_robust_cost": None,
852
+ "converged": False, "accepted": False, "location_verified": False,
853
+ "trace": [], "parameters": np.zeros(4), "crop_x": crop_x, "crop_y": crop_y,
854
+ "crop_similarity": float(crop_similarity), "crop_match_mode": crop_match_mode}
855
+ crop_height, crop_width = unedited_rect.shape[:2]
856
+ center_x, center_y = crop_x + crop_width / 2.0, crop_y + crop_height / 2.0
857
+ width0, height0 = float(target_width or crop_width), float(target_height or crop_height)
858
+ # Keep work bounded for very large patches without changing final output
859
+ # size or resolution. The original remains the only final render source.
860
+ matching_ratio = min(1.0, _MATCH_MAX_SIDE / max(width0, height0))
861
+ match_width = max(1, int(math.floor(width0 * matching_ratio + 0.5)))
862
+ match_height = max(1, int(math.floor(height0 * matching_ratio + 0.5)))
863
+ template = resize_rgba_ewa(overlay, match_width, match_height, interrupt)
864
+ confidence = _weights(template)
865
+ if confidence.sum() <= 0.0:
866
+ raise ValueError("The overlay became fully transparent at registration resolution.")
867
+ mean = np.sum(template[..., :3] * confidence[..., None], axis=(0, 1)) / confidence.sum()
868
+ variance = float(np.sum(confidence[..., None] * (template[..., :3] - mean) ** 2)
869
+ / (3.0 * confidence.sum()))
870
+ progress(8)
871
+ # Bounds are guardrails, not pixel search steps. Center can move by one
872
+ # initial rectangle width/height in either direction. Scale can vary by
873
+ # scale_limit or its reciprocal; actual dimensions always stay >=1.
874
+ low_width = max(1.0, width0 / float(scale_limit))
875
+ low_height = max(1.0, height0 / float(scale_limit))
876
+ high_width = min(float(_MAX_DIMENSION), width0 * float(scale_limit))
877
+ high_height = min(float(_MAX_DIMENSION), height0 * float(scale_limit))
878
+ # Positive bounds even for a 1px starting dimension at the upper limit.
879
+ lower = np.array((-1.0, -1.0, math.log(low_width / width0), math.log(low_height / height0)))
880
+ upper = np.array((1.0, 1.0, math.log(high_width / width0), math.log(high_height / height0)))
881
+ lower[2:] = np.minimum(lower[2:], -1.0e-12)
882
+ upper[2:] = np.maximum(upper[2:], 1.0e-12)
883
+ parameters = np.zeros(4, dtype=np.float64)
884
+ trace, notices = [], list(crop_notes)
885
+ final_problem = None
886
+ last_result = None
887
+ total_calls = 0
888
+ levels = [2 ** k for k in reversed(range(int(pyramid_levels)))]
889
+ if variance < 1.0e-10:
890
+ # A uniform-color patch cannot identify a unique width/height from
891
+ # color matching. Preserve the supplied crop geometry in that case.
892
+ notices.append("LOW TEXTURE: overlay is effectively uniform color; initial geometry retained.")
893
+ levels = [1]
894
+ for level_index, factor in enumerate(levels):
895
+ interrupt()
896
+ def on_call(calls, index=level_index):
897
+ fractional = min(0.98, calls / max(1, max_evaluations * 6))
898
+ progress(8 + int(78 * (index + fractional) / len(levels)))
899
+ problem = _RegistrationLevel(background, template, center_x, center_y,
900
+ width0, height0, factor, robust_threshold, interrupt, on_call)
901
+ initial_cost = problem.cost(parameters)
902
+ if variance >= 1.0e-10:
903
+ result = least_squares(
904
+ problem.residual, parameters, bounds=(lower, upper), method="trf", jac="2-point",
905
+ loss=problem.loss, f_scale=float(robust_threshold), x_scale=np.full(4, 0.1),
906
+ max_nfev=int(max_evaluations), ftol=1.0e-8, xtol=1.0e-7, gtol=1.0e-10,
907
+ )
908
+ candidate_cost = problem.cost(result.x)
909
+ if candidate_cost < initial_cost - 1.0e-14:
910
+ parameters = result.x.copy()
911
+ last_result = result
912
+ trace.append("factor=%d; samples=%d; cost %.10g -> %.10g; nfev=%d; solver_status=%d (%s)"
913
+ % (factor, problem.count, initial_cost, problem.cost(parameters), result.nfev,
914
+ result.status, str(result.message).strip()))
915
+ if result.status == 0:
916
+ notices.append("Evaluation limit reached at pyramid factor %d; best accepted fit retained." % factor)
917
+ else:
918
+ trace.append("factor=1; samples=%d; optimizer skipped for uniform color" % problem.count)
919
+ total_calls += problem.calls
920
+ final_problem = problem
921
+ # Validate every accumulated pyramid update on the SAME finest objective
922
+ # against the original transform. A coarse-only improvement is not enough.
923
+ base_cost = final_problem.cost(np.zeros(4))
924
+ fit_cost = final_problem.cost(parameters)
925
+ accepted = bool(fit_cost < base_cost - 1.0e-14)
926
+ if not accepted:
927
+ parameters[:] = 0.0
928
+ fit_cost = base_cost
929
+ center_x, center_y, width, height = final_problem.geometry(parameters)
930
+ width, height = max(1.0, min(_MAX_DIMENSION, width)), max(1.0, min(_MAX_DIMENSION, height))
931
+ x, y = center_x - width / 2.0, center_y - height / 2.0
932
+ registration_similarity = final_problem.similarity(parameters)
933
+ if accepted and np.any(np.minimum(parameters - lower, upper - parameters) < 1.0e-5):
934
+ notices.append("A fit parameter reached its allowed bound; inspect alignment or increase scale_limit if appropriate.")
935
+ if last_result is not None and accepted:
936
+ singular = np.linalg.svd(last_result.jac[:-4], compute_uv=False)
937
+ if singular.size and (singular[0] <= 1.0e-10 or singular[-1] < singular[0] * 1.0e-5):
938
+ notices.append("Weak geometry constraint: image detail does not reliably determine all four parameters.")
939
+ progress(88)
940
+ # The transform stays fractional: no rounding width, height, or top-left.
941
+ patch, paste_x, paste_y = render_rgba_ewa(
942
+ overlay, background.shape[1], background.shape[0], center_x, center_y, width, height, interrupt)
943
+ composite, canvas = _source_over(background, patch, paste_x, paste_y)
944
+ rendered_error = _error_at(background, patch, paste_x, paste_y) if patch.size else 1.0
945
+ similarity = float(200.0 * (1.0 - rendered_error))
946
+ if ties > 1:
947
+ notices.append("Crop location ambiguous: %d numerically tied locations; first confirmed best used." % ties)
948
+ if crop_error > 1.0e-8:
949
+ notices.append("Unedited_Rect was not an exact appearance match; closest crop location used.")
950
+ if x < 0.0 or y < 0.0 or x + width > background.shape[1] or y + height > background.shape[0]:
951
+ notices.append("Overlay extends outside canvas. Fitting penalizes missing samples; rendered similarity covers the visible paste only.")
952
+ converged = bool(last_result is not None and last_result.status > 0)
953
+ state = ("ALIGNED" if accepted else "INITIAL GEOMETRY KEPT")
954
+ status = "\n".join([
955
+ "%s; joint continuous X/Y/width/height registration; %s."
956
+ % (state, "solver converged numerically" if converged else "inspect solver notes"),
957
+ "Crop: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200"
958
+ % (crop_x, crop_y, crop_width, crop_height, 200.0 * (1.0 - crop_error)),
959
+ "Crop match mode: " + crop_match_mode,
960
+ "Crop acceptance: min_tolerance=%.6f (%.6f/200); highest score selected before threshold check."
961
+ % (float(min_tolerance), min_crop_similarity),
962
+ input_diagnostics,
963
+ "Overlay: top_left=(%.8f,%.8f), size=(%.8f,%.8f), center=(%.8f,%.8f)"
964
+ % (x, y, width, height, center_x, center_y),
965
+ "Rendered similarity=%.8f/200; registration similarity=%.8f/200; robust cost %.10g -> %.10g"
966
+ % (similarity, registration_similarity, base_cost, fit_cost),
967
+ "Registration uses alpha-weighted soft-L1, fixed source samples, and a coarse-to-fine pyramid."
968
+ " Robust cost is the fitted objective; raw similarity may decrease when changed pixels are rejected as outliers.",
969
+ "Matching image=%dx%d; residual calls=%d; render_bbox=(%d,%d,%d,%d); seconds=%.3f"
970
+ % (match_width, match_height, total_calls, paste_x, paste_y, patch.shape[1], patch.shape[0], time.monotonic() - started),
971
+ "EWA LanczosSharp: direct original-source rendering with fractional geometry; no rotation/shear/optical flow.",
972
+ *notices, "Pyramid trace:", *trace,
973
+ ])
974
+ progress(100)
975
+ _LOG.info("Salia Joint Align: center=(%.5f,%.5f), size=(%.5f,%.5f), accepted=%s, cost=%g -> %g",
976
+ center_x, center_y, width, height, accepted, base_cost, fit_cost)
977
+ return {"composite": composite, "overlay_canvas": canvas, "status": status,
978
+ "x": float(x), "y": float(y), "width": float(width), "height": float(height),
979
+ "center_x": float(center_x), "center_y": float(center_y), "similarity": similarity,
980
+ "registration_similarity": registration_similarity, "robust_cost": fit_cost,
981
+ "initial_robust_cost": base_cost, "converged": converged, "accepted": accepted,
982
+ "trace": trace, "parameters": parameters.copy(), "crop_x": crop_x, "crop_y": crop_y,
983
+ "location_verified": True, "crop_similarity": float(crop_similarity),
984
+ "crop_match_mode": crop_match_mode}
985
+
986
+
987
+
988
+ from scipy.ndimage import distance_transform_edt, gaussian_filter, label, binary_erosion
989
+
990
+
991
+ def _neck_smooth(value):
992
+ value = np.clip(value, 0.0, 1.0)
993
+ return value * value * (3.0 - 2.0 * value)
994
+
995
+
996
+ def _neck_preview(rgba):
997
+ yy, xx = np.indices(rgba.shape[:2])
998
+ gray = np.where((xx // 16 + yy // 16) % 2, .35, .60).astype(np.float32)
999
+ return (rgba[..., :3] * rgba[..., 3:4] + gray[..., None] * (1.0 - rgba[..., 3:4])).astype(np.float32)
1000
+
1001
+
1002
+ def _neck_gray(value):
1003
+ return np.repeat(np.clip(value, 0., 1.)[..., None], 3, axis=-1).astype(np.float32)
1004
+
1005
+
1006
+ def _neck_mask_array(mask, shape):
1007
+ if hasattr(mask, "detach"):
1008
+ mask = mask.detach().cpu().float().numpy()
1009
+ mask = np.asarray(mask)
1010
+ if mask.ndim == 3 and mask.shape[0] == 1:
1011
+ mask = mask[0]
1012
+ if mask.shape != shape or not np.isfinite(mask).all():
1013
+ raise ValueError("neck_blend_mask must match the full background canvas; WHITE=neck to blend, BLACK=preserve. Do not use an inverted object-alpha mask here.")
1014
+ return np.clip(mask, 0., 1.).astype(np.float32)
1015
+
1016
+
1017
+ def _neck_rectangle(shape, rect, feather):
1018
+ h, w = shape
1019
+ x, y, rw, rh = rect
1020
+ yy, xx = np.ogrid[:h, :w]
1021
+ d = np.minimum(np.minimum(xx - x + .5, x + rw - xx - .5),
1022
+ np.minimum(yy - y + .5, y + rh - yy - .5))
1023
+ return _neck_smooth(d / max(.5, min(feather, rw / 4., rh / 4.))).astype(np.float32)
1024
+
1025
+
1026
+ def fuse_neck_arrays(background_2, aligned_head, neck_blend_width=24., neck_smooth_px=1.5,
1027
+ fusion_strength=1., bridge_gap_px=4, neck_blend_mask=None,
1028
+ neck_x=0, neck_y=0, neck_width=0, neck_height=0,
1029
+ interrupt=lambda: None):
1030
+ """Fuse ALIGNED head with headless torso at its actual lower alpha contour.
1031
+
1032
+ The old torso/head image has no role in this function. Color is borrowed
1033
+ only from visible torso pixels, never from their hidden transparent RGB.
1034
+ Alpha stays exactly at head-over-torso baseline except explicitly bounded
1035
+ small-gap pixels; no outer contour is globally blurred.
1036
+ """
1037
+ torso = _rgba_array(background_2, "background_2")
1038
+ head = _rgba_array(aligned_head, "aligned_head")
1039
+ if torso.shape != head.shape:
1040
+ raise ValueError("background_2 must use the SAME full canvas dimensions as background. It is not moved or resized independently.")
1041
+ vals = np.asarray((neck_blend_width, neck_smooth_px, fusion_strength, neck_x, neck_y, neck_width, neck_height), np.float64)
1042
+ if (not np.isfinite(vals).all() or not 0. <= fusion_strength <= 1.
1043
+ or not 0. <= neck_blend_width <= 512. or not 0. <= neck_smooth_px <= 32.
1044
+ or min(neck_width, neck_height) < 0):
1045
+ raise ValueError("Invalid neck controls: finite values, width 0..512, smoothing 0..32 and strength 0..1 required.")
1046
+ if isinstance(bridge_gap_px, bool) or int(bridge_gap_px) != bridge_gap_px or not 0 <= bridge_gap_px <= 32:
1047
+ raise ValueError("bridge_gap_px must be an integer 0..32; 0 disables adding gap pixels.")
1048
+ if (neck_width > 0) != (neck_height > 0):
1049
+ raise ValueError("Set BOTH neck_width and neck_height for a manual neck rectangle; leave both 0 for automatic detection.")
1050
+ hard, _ = _source_over(torso, head, 0, 0)
1051
+ result = hard.copy()
1052
+ h, w = hard.shape[:2]
1053
+ region = np.zeros((h, w), np.float32)
1054
+ amount = np.zeros_like(region)
1055
+ gap_fill = np.zeros_like(region)
1056
+ contact = np.zeros_like(region, dtype=bool)
1057
+ lines = ["Fusion target: positioned NEW HEAD over HEADLESS TORSO (background_2).",
1058
+ "Original background is used only by registration; it is never the final fusion background."]
1059
+ for name, image in (("aligned_head", head), ("background_2", torso)):
1060
+ a = image[..., 3]
1061
+ lines.append("%s: alpha min=%.6f max=%.6f transparent=%.2f%%." % (name, a.min(), a.max(), 100 * np.mean(a <= 1.e-8)))
1062
+ def finish(headline):
1063
+ visual = _neck_preview(result)
1064
+ region_edge = (region > .05) & ~binary_erosion(region > .05)
1065
+ visual[region_edge] = (0., .9, 1.)
1066
+ visual[contact] = (0., 1., .1)
1067
+ visual[gap_fill > .01] = (1., .25, .8)
1068
+ before = hard[..., :3] * hard[..., 3:4] + .5 * (1 - hard[..., 3:4])
1069
+ after = result[..., :3] * result[..., 3:4] + .5 * (1 - result[..., 3:4])
1070
+ delta = np.max(np.abs(after - before), axis=-1)
1071
+ outside = region <= 0.
1072
+ outside_error = float(np.max(np.abs(result[outside] - hard[outside]), initial=0.))
1073
+ lines.append("Changed visible pixels=%d; gap-added pixels=%d; outside-neck error=%.9g."
1074
+ % (np.count_nonzero(delta > 1.e-6), np.count_nonzero(gap_fill > .001), outside_error))
1075
+ lines.append("Debug neck: cyan=selected region; green=actual head/torso contact; pink=bounded gap repair.")
1076
+ return {"fused_rgba": result, "hard_composite_rgba": hard, "aligned_head_rgba": head,
1077
+ "status": "\n".join([headline, *lines]),
1078
+ "debug_fused_rgb": _neck_preview(result), "debug_hard_rgb": _neck_preview(hard),
1079
+ "debug_head_rgb": _neck_preview(head), "debug_torso_rgb": _neck_preview(torso),
1080
+ "debug_neck_rgb": visual, "debug_blend_amount_rgb": _neck_gray(amount),
1081
+ "debug_gap_fill_rgb": _neck_gray(gap_fill),
1082
+ "debug_difference_x8_rgb": np.clip(np.abs(after - before) * 8., 0., 1.).astype(np.float32),
1083
+ "output_mask": (1. - result[..., 3]).astype(np.float32),
1084
+ "region": region, "blend_amount": amount, "gap_fill": gap_fill}
1085
+ hm, tm = head[..., 3] > .01, torso[..., 3] > .05
1086
+ if not np.any(hm):
1087
+ return finish("NO HEAD: alignment produced no visible head; background_2 retained.")
1088
+ if not np.any(tm):
1089
+ return finish("NO TORSO: background_2 has no visible pixels; aligned head retained.")
1090
+ if (np.all(torso[..., 3] >= 1. - 1.e-7) and neck_blend_mask is None
1091
+ and not (neck_width > 0 and neck_height > 0)):
1092
+ lines.append("background_2 is opaque across the entire canvas. Automatic socket detection needs real sprite alpha: use native RGBA or connect background_2_mask from Load Image unchanged.")
1093
+ return finish("NECK FUSION SKIPPED / ALPHA WARNING: background_2 has no transparent canvas; select a neck rectangle explicitly or supply its real alpha.")
1094
+ if fusion_strength == 0. or neck_blend_width == 0.:
1095
+ return finish("BYPASS: head-on-headless-torso composition; neck fusion disabled.")
1096
+ interrupt()
1097
+ # Restrict donor colors to actually visible torso pixels. Normalized
1098
+ # Gaussian smoothing ignores arbitrary RGB stored under zero alpha.
1099
+ donor_valid = torso[..., 3] >= .25
1100
+ if not np.any(donor_valid):
1101
+ donor_valid = tm
1102
+ torso_distance, nearest_torso = distance_transform_edt(~donor_valid, return_indices=True)
1103
+ rows = np.arange(h)[:, None]
1104
+ bottom = np.max(np.where(hm, rows, -1), axis=0)
1105
+ columns = np.flatnonzero(bottom >= 0)
1106
+ lower = np.zeros((h, w), bool)
1107
+ lower[bottom[columns], columns] = True
1108
+ hy, hx = np.nonzero(hm)
1109
+ center = .5 * (hx.min() + hx.max())
1110
+ max_contact_distance = max(2., float(bridge_gap_px) + 2.)
1111
+ if neck_blend_mask is not None:
1112
+ region[:] = _neck_mask_array(neck_blend_mask, (h, w))
1113
+ allowed = distance_transform_edt(region <= 0.) <= neck_blend_width if np.any(region) else region > 0.
1114
+ candidates = lower & allowed
1115
+ lines.append("Neck region: user WHITE=blend mask (full canvas, no inversion).")
1116
+ elif neck_width > 0 and neck_height > 0:
1117
+ region[:] = _neck_rectangle((h, w), (neck_x, neck_y, neck_width, neck_height), 3.)
1118
+ allowed = distance_transform_edt(region <= 0.) <= neck_blend_width if np.any(region) else region > 0.
1119
+ candidates = lower & allowed
1120
+ lines.append("Neck region: user rectangle x=%g y=%g width=%g height=%g." % (neck_x, neck_y, neck_width, neck_height))
1121
+ else:
1122
+ xx = np.arange(w)[None, :]
1123
+ half_width = max(2., .25 * (hx.max() - hx.min() + 1))
1124
+ candidates = lower & (np.abs(xx - center) <= half_width) & (rows >= hy.min() + .55 * (hy.max() - hy.min()))
1125
+ lines.append("Neck region: automatic LOWER CENTRAL contact heuristic; use the neck rectangle/mask if hair or pose confuses it.")
1126
+ available = candidates.copy()
1127
+ candidates &= torso_distance <= max_contact_distance
1128
+ # A donor belongs to the lower layer: reject a distant piece above the
1129
+ # candidate when a pose/hair shape makes the central heuristic ambiguous.
1130
+ candidates &= nearest_torso[0] >= rows - neck_blend_width
1131
+ if not np.any(candidates):
1132
+ min_distance = float(np.min(torso_distance[available], initial=np.inf))
1133
+ lines.append("Nearest candidate torso distance=%.3fpx; contact limit=%.3fpx; bridge_gap_px=%d."
1134
+ % (min_distance, max_contact_distance, bridge_gap_px))
1135
+ if not np.any(head[..., 3] < .01) or not np.any(torso[..., 3] < .01):
1136
+ lines.append("Missing transparency detected: for RGB from Load Image, connect each sprite's matching MASK unchanged. RGBA uses embedded alpha.")
1137
+ return finish("NECK CONTACT NOT FOUND: no blind blur applied. Check debug alpha/neck position; provide a neck rectangle/mask or inspect the gap.")
1138
+ if neck_blend_mask is None and not (neck_width > 0 and neck_height > 0):
1139
+ groups, count = label(candidates, structure=np.ones((3, 3), np.uint8))
1140
+ best, score = None, np.inf
1141
+ for group in range(1, count + 1):
1142
+ gy, gx = np.nonzero(groups == group)
1143
+ value = abs(float(np.mean(gx)) - center) - .05 * gx.size
1144
+ if value < score:
1145
+ score, best = value, group
1146
+ contact[:] = groups == best
1147
+ cy, cx = np.nonzero(contact)
1148
+ pad = max(3., neck_blend_width * .45)
1149
+ rx, ry = float(cx.min() - pad), float(cy.min() - neck_blend_width * 1.2)
1150
+ # Do not spend a long blend width on the chin/face when the head
1151
+ # contains only a very short neck. Follow the narrow lower silhouette
1152
+ # upward until it widens into the face; masks/rectangles can override.
1153
+ narrow_limit = max(1.35 * (cx.max() - cx.min() + 1), .35 * (hx.max() - hx.min() + 1))
1154
+ neck_top = int(cy.min())
1155
+ while (neck_top > hy.min() + .5 * (hy.max() - hy.min())
1156
+ and np.count_nonzero(hm[neck_top - 1]) <= narrow_limit):
1157
+ neck_top -= 1
1158
+ ry = max(ry, float(neck_top))
1159
+ rw = float(cx.max() - cx.min() + 1 + 2 * pad)
1160
+ rh = float(cy.max() - ry + max(3., neck_blend_width * .4))
1161
+ region[:] = _neck_rectangle((h, w), (rx, ry, rw, rh), 3.)
1162
+ lines.append("Automatic neck rectangle: x=%.2f y=%.2f width=%.2f height=%.2f." % (rx, ry, rw, rh))
1163
+ else:
1164
+ contact[:] = candidates
1165
+ if not np.any(region > 0.):
1166
+ return finish("EMPTY NECK REGION: no visible change requested.")
1167
+ # Optional repair of ONLY a small vertical gap between the head and the
1168
+ # torso in a common column. No dilation around the sprite/hair silhouette.
1169
+ gap_columns, unfilled_columns = 0, 0
1170
+ if bridge_gap_px > 0:
1171
+ for col in np.flatnonzero(np.any(region > .05, axis=0) & (bottom >= 0)):
1172
+ interrupt()
1173
+ top = int(bottom[col])
1174
+ if tm[top, col]:
1175
+ continue
1176
+ target = np.flatnonzero(tm[top + 1:, col])
1177
+ if not target.size:
1178
+ continue
1179
+ end = top + 1 + int(target[0])
1180
+ gap = end - top - 1
1181
+ if gap < 0:
1182
+ continue
1183
+ if gap > bridge_gap_px or not np.all(region[top:end + 1, col] > .05):
1184
+ unfilled_columns += 1
1185
+ continue
1186
+ head_rows = np.arange(max(0, top - 3), top + 1)
1187
+ torso_rows = np.arange(end, min(h, end + 4))
1188
+ ha = float(np.max(head[head_rows, col, 3]))
1189
+ ta = float(np.max(torso[torso_rows, col, 3]))
1190
+ if min(ha, ta) < .5:
1191
+ continue
1192
+ head_row = int(head_rows[np.argmax(head[head_rows, col, 3])])
1193
+ torso_row = int(torso_rows[np.argmax(torso[torso_rows, col, 3])])
1194
+ hc = _to_linear(head[head_row, col, :3])
1195
+ tc = _to_linear(torso[torso_row, col, :3])
1196
+ # The fused head-side endpoint already moves toward the torso.
1197
+ # Match that endpoint here, rather than reintroducing the old
1198
+ # head skin color on the first newly repaired gap pixel.
1199
+ hc = (1. - fusion_strength) * hc + fusion_strength * tc
1200
+ # Include the two fractional-AA endpoints. Filling only fully
1201
+ # empty interior rows leaves a faint transparent horizontal line
1202
+ # at the old cut edge even after the larger gap is repaired.
1203
+ for row in range(top, end + 1):
1204
+ if hard[row, col, 3] >= 1. - 1.e-7:
1205
+ continue
1206
+ t = (row - top) / max(1, end - top)
1207
+ color = _to_srgb((1 - t) * hc + t * tc)
1208
+ alpha = min(ha, ta) * region[row, col] * fusion_strength
1209
+ old_alpha = result[row, col, 3]
1210
+ out_alpha = alpha + old_alpha * (1 - alpha)
1211
+ if out_alpha > 1.e-8:
1212
+ result[row, col, :3] = (color * alpha + result[row, col, :3] * old_alpha * (1 - alpha)) / out_alpha
1213
+ result[row, col, 3] = out_alpha
1214
+ gap_fill[row, col] = max(0., out_alpha - old_alpha)
1215
+ gap_columns += 1
1216
+ else:
1217
+ lines.append("Gap repair is disabled; transparent gaps are intentionally not filled.")
1218
+ lines.append("Gap repair: limit=%dpx; repaired columns=%d; wider/uncovered columns left alone=%d."
1219
+ % (bridge_gap_px, gap_columns, unfilled_columns))
1220
+ interrupt()
1221
+ contact_distance = distance_transform_edt(~contact)
1222
+ amount[:] = _neck_smooth(1. - np.maximum(contact_distance - .5, 0.) / neck_blend_width)
1223
+ amount *= region * fusion_strength * hm
1224
+ amount[torso_distance > neck_blend_width + max_contact_distance] = 0.
1225
+ torso_linear = _to_linear(torso[..., :3])
1226
+ # Multiplication by actual alpha removes hidden-RGB contamination before
1227
+ # smoothing. Borrow the nearest visible torso color above the socket as
1228
+ # well, so two TOUCHING pieces can blend without requiring an overlap.
1229
+ if neck_smooth_px > 0.:
1230
+ a = torso[..., 3]
1231
+ denominator = gaussian_filter(a, neck_smooth_px, mode="constant")
1232
+ filtered = gaussian_filter(torso_linear * a[..., None], (neck_smooth_px, neck_smooth_px, 0.), mode="constant")
1233
+ smoothed_torso = np.zeros_like(torso_linear)
1234
+ np.divide(filtered, denominator[..., None], out=smoothed_torso, where=denominator[..., None] > 1.e-8)
1235
+ else:
1236
+ smoothed_torso = torso_linear
1237
+ donor = smoothed_torso[nearest_torso[0], nearest_torso[1]]
1238
+ original_linear = _to_linear(result[..., :3])
1239
+ base_color = original_linear.copy()
1240
+ if neck_smooth_px > 0.:
1241
+ confidence = result[..., 3] * region
1242
+ denominator = gaussian_filter(confidence, neck_smooth_px, mode="constant")
1243
+ filtered = gaussian_filter(original_linear * confidence[..., None], (neck_smooth_px, neck_smooth_px, 0.), mode="constant")
1244
+ smooth_color = original_linear.copy()
1245
+ np.divide(filtered, denominator[..., None], out=smooth_color, where=denominator[..., None] > 1.e-8)
1246
+ base_color += (.35 * amount[..., None]) * (smooth_color - base_color)
1247
+ mixed = _to_srgb((1. - amount[..., None]) * base_color + amount[..., None] * donor)
1248
+ active = (amount > 0.) & (result[..., 3] > 1.e-8)
1249
+ result[active, :3] = mixed[active]
1250
+ result[region <= 0.] = hard[region <= 0.]
1251
+ # Do not create numerical changes where colors were already equal.
1252
+ equal = np.max(np.abs(result - hard), axis=-1) <= 2.e-7
1253
+ result[equal] = hard[equal]
1254
+ alpha_outside_repairs = float(np.max(np.abs(result[..., 3][gap_fill <= 0.] - hard[..., 3][gap_fill <= 0.]), initial=0.))
1255
+ lines.append("Actual contact pixels=%d; blend width=%.3fpx; normalized color smoothing=%.3fpx; strength=%.3f."
1256
+ % (np.count_nonzero(contact), neck_blend_width, neck_smooth_px, fusion_strength))
1257
+ lines.append("Alpha change outside explicit gap repair=%.9g (must be 0)." % alpha_outside_repairs)
1258
+ headline = "FUSED: new head + background_2, with local neck color fusion."
1259
+ if unfilled_columns > 0:
1260
+ headline += " GAP WARNING: some gaps exceed the allowed repair or neck region."
1261
+ return finish(headline)
1262
+
1263
+ def _original_input_types():
1264
+ return {"required": {
1265
+ "background": ("IMAGE", {"tooltip": "Single full-size RGB/RGBA background."}),
1266
+ "overlay": ("IMAGE", {"tooltip": "Original full-resolution edited overlay. Final EWA render always uses this source."}),
1267
+ "Unedited_Rect": ("IMAGE", {"tooltip": "Original crop from background; locates initial center and default size."}),
1268
+ "target_width": ("INT", {"default": 0, "min": 0, "max": _MAX_DIMENSION, "step": 1,
1269
+ "tooltip": "INITIAL width; 0 uses Unedited_Rect width. Optimizer can refine it."}),
1270
+ "target_height": ("INT", {"default": 0, "min": 0, "max": _MAX_DIMENSION, "step": 1,
1271
+ "tooltip": "INITIAL height; 0 uses Unedited_Rect height. Optimized independently of width."}),
1272
+ "max_evaluations": ("INT", {"default": 100, "min": 5, "max": 1000, "step": 1,
1273
+ "tooltip": "Maximum solver function evaluations PER pyramid level. Status reports limits."}),
1274
+ "pyramid_levels": ("INT", {"default": 3, "min": 1, "max": 5, "step": 1,
1275
+ "tooltip": "Coarse-to-fine registration levels. 3 uses smoothing factors 4,2,1."}),
1276
+ "robust_threshold": ("FLOAT", {"default": 0.05, "min": 0.001, "max": 1.0, "step": 0.005,
1277
+ "tooltip": "Soft-L1 RGB threshold: smaller values reduce influence of large appearance edits."}),
1278
+ "scale_limit": ("FLOAT", {"default": 2.0, "min": 1.01, "max": 8.0, "step": 0.1,
1279
+ "tooltip": "Independent width/height ratio bounds: 2 permits 0.5x..2x initial dimensions. Not a pixel increment."}),
1280
+ "min_tolerance": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01,
1281
+ "tooltip": "Minimum crop similarity / 200. 0.9 = 180/200. Always searches for the highest score first; never stops at the first passing location."}),
1282
+ }, "optional": {
1283
+ "background_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
1284
+ "overlay_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
1285
+ "Unedited_Rect_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
1286
+ }}
1287
+
1288
+
1289
+ class Salia_Head_Torso_Fusion_2_retry:
1290
+ @classmethod
1291
+ def INPUT_TYPES(cls):
1292
+ schema = _original_input_types()
1293
+ old = schema["required"]
1294
+ images = ("background", "overlay", "Unedited_Rect")
1295
+ schema["required"] = {**{name: old[name] for name in images},
1296
+ "background_2": ("IMAGE", {"tooltip": "FULL-SIZE HEADLESS TORSO. Final fusion uses this image, not the old head/torso background. Same canvas dimensions."}),
1297
+ **{name: config for name, config in old.items() if name not in images},
1298
+ "neck_blend_width": ("FLOAT", {"default": 24., "min": 0., "max": 512., "step": 1., "tooltip": "Color-transition width inward from the actual lower head alpha boundary, in final-image pixels. 0 disables fusion."}),
1299
+ "neck_smooth_px": ("FLOAT", {"default": 1.5, "min": 0., "max": 32., "step": .5, "tooltip": "Alpha-normalized local color blur near the neck. Does not blur the whole head/silhouette."}),
1300
+ "fusion_strength": ("FLOAT", {"default": 1., "min": 0., "max": 1., "step": .05, "tooltip": "1=neck fusion, 0=ordinary head-on-headless-torso for comparison."}),
1301
+ "bridge_gap_px": ("INT", {"default": 4, "min": 0, "max": 32, "step": 1, "tooltip": "May fill ONLY a gap this small between head and torso within the neck. 0 disables adding pixels. Larger gaps are left alone and reported."}),
1302
+ "neck_x": ("INT", {"default": 0, "min": -32768, "max": 32768, "tooltip": "Optional manual neck rectangle X, full-canvas pixels. Used only when width AND height > 0."}),
1303
+ "neck_y": ("INT", {"default": 0, "min": -32768, "max": 32768}),
1304
+ "neck_width": ("INT", {"default": 0, "min": 0, "max": 32768, "tooltip": "0 with height=0 uses automatic neck contact. Set both >0 to select neck manually; see debug_neck_rgb."}),
1305
+ "neck_height": ("INT", {"default": 0, "min": 0, "max": 32768}),
1306
+ }
1307
+ schema["optional"].update({
1308
+ "background_2_mask": ("MASK", {"tooltip": "For RGB headless torso only: connect its Load Image MASK unchanged (1-alpha). Native RGBA takes priority."}),
1309
+ "neck_blend_mask": ("MASK", {"tooltip": "Optional full-canvas region: WHITE=neck to blend, BLACK=preserve. This is a drawn blend region, not object alpha. Overrides automatic/manual rectangle."}),
1310
+ })
1311
+ return schema
1312
+
1313
+ RETURN_TYPES = ("IMAGE", "STRING", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "MASK")
1314
+ RETURN_NAMES = ("fused_rgba", "status", "aligned_head_rgba", "hard_composite_rgba",
1315
+ "debug_fused_rgb", "debug_hard_rgb", "debug_head_rgb", "debug_torso_rgb",
1316
+ "debug_neck_rgb", "debug_blend_amount_rgb", "debug_gap_fill_rgb",
1317
+ "debug_difference_x8_rgb", "output_mask")
1318
+ FUNCTION = "process"
1319
+ CATEGORY = "Salia/Image"
1320
+ DESCRIPTION = ("_2_retry.py: FOUR source images. Old background + original crop position the new head; "
1321
+ "the positioned head is then fused with background_2 (HEADLESS TORSO) at the actual neck, "
1322
+ "with local color blending/blur, optional small-gap repair and debug previews. One self-contained file.")
1323
+
1324
+ def process(self, background, overlay, Unedited_Rect, background_2,
1325
+ target_width=0, target_height=0, max_evaluations=100, pyramid_levels=3,
1326
+ robust_threshold=.05, scale_limit=2., min_tolerance=.9,
1327
+ neck_blend_width=24., neck_smooth_px=1.5, fusion_strength=1., bridge_gap_px=4,
1328
+ neck_x=0, neck_y=0, neck_width=0, neck_height=0,
1329
+ background_mask=None, overlay_mask=None, Unedited_Rect_mask=None,
1330
+ background_2_mask=None, neck_blend_mask=None):
1331
+ import torch
1332
+ try:
1333
+ from comfy.model_management import throw_exception_if_processing_interrupted as interrupt
1334
+ except ImportError:
1335
+ interrupt = lambda: None
1336
+ try:
1337
+ from comfy.utils import ProgressBar
1338
+ bar, previous = ProgressBar(100), [-1]
1339
+ def progress(value):
1340
+ value = max(previous[0], min(100, int(value)))
1341
+ if value != previous[0]:
1342
+ bar.update_absolute(value, 100)
1343
+ previous[0] = value
1344
+ except ImportError:
1345
+ progress = lambda value: None
1346
+ started = time.monotonic()
1347
+ with torch.inference_mode():
1348
+ interrupt()
1349
+ bg = _tensor_image(background, "background", background_mask)
1350
+ head = _tensor_image(overlay, "overlay", overlay_mask)
1351
+ crop = _tensor_image(Unedited_Rect, "Unedited_Rect", Unedited_Rect_mask)
1352
+ torso = _tensor_image(background_2, "background_2", background_2_mask)
1353
+ if bg.shape[:2] != torso.shape[:2]:
1354
+ raise ValueError("background_2 (headless torso) must have the SAME full-canvas dimensions as background. It is not independently resized.")
1355
+ alignment = align_arrays(bg, head, crop, target_width=target_width, target_height=target_height,
1356
+ max_evaluations=max_evaluations, pyramid_levels=pyramid_levels,
1357
+ robust_threshold=robust_threshold, scale_limit=scale_limit, min_tolerance=min_tolerance,
1358
+ interrupt=interrupt, progress=lambda value: progress(.75 * value))
1359
+ progress(78)
1360
+ # Only the positioned HEAD is taken from registration. The old
1361
+ # head/torso composite is deliberately NOT a fusion input.
1362
+ fused = fuse_neck_arrays(torso, alignment["overlay_canvas"],
1363
+ neck_blend_width=neck_blend_width, neck_smooth_px=neck_smooth_px,
1364
+ fusion_strength=fusion_strength, bridge_gap_px=bridge_gap_px,
1365
+ neck_blend_mask=neck_blend_mask, neck_x=neck_x, neck_y=neck_y,
1366
+ neck_width=neck_width, neck_height=neck_height, interrupt=interrupt)
1367
+ alpha_notes = []
1368
+ if int(overlay.shape[-1]) == 3 and overlay_mask is None:
1369
+ alpha_notes.append("ALPHA WARNING: overlay is RGB without overlay_mask; the head was treated as an opaque rectangle. For a transparent PNG, connect its Load Image MASK unchanged.")
1370
+ if int(background_2.shape[-1]) == 3 and background_2_mask is None:
1371
+ alpha_notes.append("ALPHA WARNING: background_2 is RGB without background_2_mask. For a transparent headless torso, connect its matching Load Image MASK unchanged.")
1372
+ fused["status"] = "\n".join([
1373
+ "Salia Head + Torso Fusion _2_retry.py -- FOUR SOURCE IMAGES, ONE NODE",
1374
+ fused["status"],
1375
+ *alpha_notes,
1376
+ "Total seconds=%.3f." % (time.monotonic() - started),
1377
+ "INTERNAL HEAD POSITIONING (old background used only here):", alignment["status"],
1378
+ ])
1379
+ outputs = []
1380
+ for name in self.RETURN_NAMES:
1381
+ if name == "status":
1382
+ outputs.append(fused[name])
1383
+ else:
1384
+ outputs.append(torch.from_numpy(np.ascontiguousarray(fused[name], dtype=np.float32)).unsqueeze(0))
1385
+ progress(100)
1386
+ return tuple(outputs)
1387
+
1388
+
1389
+ NODE_CLASS_MAPPINGS = {"Salia_Head_Torso_Fusion_2_retry": Salia_Head_Torso_Fusion_2_retry}
1390
+ NODE_DISPLAY_NAME_MAPPINGS = {"Salia_Head_Torso_Fusion_2_retry": "Salia Head + Torso Fusion _2_retry.py"}