saliacoel commited on
Commit
555e4ab
·
verified ·
1 Parent(s): d5518a2

Upload Salia_Auto_Align_Overlay.py

Browse files
Files changed (1) hide show
  1. Salia_Auto_Align_Overlay.py +731 -0
Salia_Auto_Align_Overlay.py ADDED
@@ -0,0 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Salia Auto Align Overlay -- single-file ComfyUI custom node
3
+ =========================================================
4
+ Install: copy this file to ComfyUI/custom_nodes/ and restart ComfyUI.
5
+ Menu: Salia/Image -> Salia Auto Align Overlay (EWA LanczosSharp).
6
+ Dependencies: NumPy, SciPy, PyTorch (normally installed with ComfyUI).
7
+ No models, downloads, sibling node files, or external processes are used.
8
+
9
+ Inputs
10
+ ------
11
+ background: full reference image, RGB or straight RGBA.
12
+ overlay: original, unscaled edited rectangle, RGB or straight RGBA.
13
+ Unedited_Rect: unedited crop taken from the background, before editing.
14
+ target_width/height: initial overlay size; each zero uses that crop dimension.
15
+ move_pixels: search +/- N pixels in X AND Y (default 2 = 25 candidates).
16
+ scale_pixels: search +/- N pixels in width AND height (default 2 = 25 sizes).
17
+ max_iterations: stop runaway refinement and report whether it converged.
18
+ Each input must contain one image; split batches before this node.
19
+
20
+ Standard ComfyUI Load Image separates alpha into an inverted MASK. If using
21
+ that loader for transparent inputs, connect its MASK to the matching optional
22
+ *_mask input. MASK means 1-alpha; a supplied mask REPLACES any embedded alpha.
23
+ RGBA-native image nodes can connect directly without these masks.
24
+
25
+ Similarity
26
+ ----------
27
+ 0 = maximum mismatch; 200 = equal compared colors. Squared differences in
28
+ straight sRGB punish larger color errors more strongly. Template alpha is a
29
+ confidence weight: alpha 0 ignores that pixel; green .5 can match green 1.
30
+ Visible template over invisible background is maximum mismatch. This is an
31
+ appearance matcher, not a test that two stored RGBA arrays are identical.
32
+ Hidden RGB does not affect scores. Completely transparent templates are an
33
+ error because they contain no location information.
34
+
35
+ GET_RECTS_SIMILARITY(rect1, rect2) is also exposed for symmetric same-size
36
+ comparison. The actual matcher uses its directional template semantics:
37
+ transparent overlay padding must not punish an opaque forest background.
38
+ See the helper's docstring for the precise distinction.
39
+
40
+ Algorithm
41
+ ---------
42
+ 1. Evaluate every full-size, fully-contained placement of Unedited_Rect.
43
+ Float64 FFT correlation accelerates weighted color SSD; near-best results
44
+ are checked directly. Original crop dimensions define the initial center.
45
+ 2. Resize the ORIGINAL overlay to the current dimensions with exactly the
46
+ supplied Salia_Rescale_Image EWA LanczosSharp numerical core (embedded
47
+ below). Test all integer movement combinations around the current center.
48
+ 3. At the winning position, resize the ORIGINAL overlay independently to all
49
+ valid width/height combinations. Keep the center while testing each size.
50
+ If current dimensions win, finish. Otherwise repeat step 2 with the winner.
51
+ Ties keep the current position/size, and only strict improvements are accepted.
52
+ The move/scale loop is local and does not promise a global size optimum.
53
+ No rotation, alpha-mask generation, blending feather, or pixel warping.
54
+
55
+ Coordinates use pixel edges: center=(x+width/2, y+height/2). On integer raster
56
+ placements an odd/even dimension change can round the center by half a pixel;
57
+ rounding is deterministic and actual final coordinates are returned.
58
+ Off-canvas visible overlay pixels count as maximum mismatch, and final paste
59
+ is clipped to the background. Transparent padding outside it is harmless.
60
+
61
+ Outputs
62
+ -------
63
+ composite_rgba: background with the aligned overlay pasted by alpha source-over.
64
+ overlay_canvas_rgba: aligned overlay alone on a transparent background-sized canvas.
65
+ status: convergence, crop location, final placement, scores, iterations and trace.
66
+ x/y: final top-left integers; width/height: final resampled rectangle dimensions.
67
+ center_x/center_y: actual geometric center floats; similarity: final 0..200 score.
68
+ Both IMAGE outputs have shape [1, background_height, background_width, 4].
69
+ Resampling uses linear RGB and premultiplied alpha as in the attached rescaler.
70
+ Final compositing uses ordinary straight-alpha source-over in sRGB.
71
+
72
+ Primary integration references:
73
+ https://docs.comfy.org/custom-nodes/backend/images_and_masks
74
+ https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.correlate.html
75
+ """
76
+ from __future__ import annotations
77
+ import math
78
+ from functools import lru_cache
79
+ from typing import Callable, Tuple
80
+ import numpy as np
81
+ from scipy import sparse
82
+ from scipy.special import j1, jn_zeros
83
+ _MODES = ("EWA LanczosSharp", "EWA LanczosRadius / Jinc-Jinc")
84
+ _PAIR_BUDGET = 262144
85
+ _LUT_INTERVALS = 65536
86
+ _ALPHA_EPSILON = 1.0e-8
87
+
88
+ def _to_linear(rgb: np.ndarray) -> np.ndarray:
89
+ return np.where(
90
+ rgb <= 0.04045,
91
+ rgb / 12.92,
92
+ np.power((rgb + 0.055) / 1.055, 2.4),
93
+ ).astype(np.float32, copy=False)
94
+
95
+ def _to_srgb(rgb: np.ndarray) -> np.ndarray:
96
+ rgb = np.clip(rgb, 0.0, 1.0)
97
+ return np.where(
98
+ rgb <= 0.0031308,
99
+ rgb * 12.92,
100
+ 1.055 * np.power(rgb, 1.0 / 2.4) - 0.055,
101
+ ).astype(np.float32, copy=False)
102
+
103
+ def _prepare_image(source: np.ndarray) -> np.ndarray:
104
+ if not np.isfinite(source).all():
105
+ raise ValueError("Salia_Rescale_Image: image contains NaN or infinity.")
106
+ image = np.clip(source, 0.0, 1.0).astype(np.float32, copy=True)
107
+ image[..., :3] = _to_linear(image[..., :3])
108
+ if image.shape[-1] == 4:
109
+ image[..., :3] *= image[..., 3:4]
110
+ return image
111
+
112
+ def _finish_image(filtered: np.ndarray, channels: int) -> np.ndarray:
113
+ filtered = np.asarray(filtered, dtype=np.float32)
114
+ rgb = filtered[..., :3]
115
+ if channels == 4:
116
+ raw_alpha = filtered[..., 3:4]
117
+ visible = raw_alpha > _ALPHA_EPSILON
118
+ # Divide by the ORIGINAL filtered alpha, before clipping alpha.
119
+ # Negative-lobe filters can overshoot 1; clipping before division
120
+ # would alter the color of those pixels.
121
+ straight_rgb = np.zeros_like(rgb)
122
+ np.divide(rgb, raw_alpha, out=straight_rgb, where=visible)
123
+ rgb = _to_srgb(straight_rgb)
124
+ alpha = np.where(visible, np.clip(raw_alpha, 0.0, 1.0), 0.0)
125
+ result = np.concatenate((rgb, alpha), axis=-1)
126
+ else:
127
+ result = _to_srgb(rgb)
128
+ return np.ascontiguousarray(np.clip(result, 0.0, 1.0), dtype=np.float32)
129
+
130
+ def _jinc(x: np.ndarray) -> np.ndarray:
131
+ # Normalized Jinc = 2 * J1(pi*x) / (pi*x), with value 1 at zero.
132
+ z = math.pi * np.asarray(x, dtype=np.float64)
133
+ result = np.ones_like(z)
134
+ np.divide(2.0 * j1(z), z, out=result, where=np.abs(z) > 1.0e-12)
135
+ return result
136
+
137
+ @lru_cache(maxsize=2)
138
+ def _ewa_definition(mode: str) -> Tuple[float, np.ndarray, float]:
139
+ first_zero, _, third_zero = jn_zeros(1, 3) / math.pi
140
+ if mode == _MODES[0]:
141
+ blur = 0.9812505644269356
142
+ elif mode == _MODES[1]:
143
+ blur = 3.0 / third_zero
144
+ else:
145
+ raise ValueError("Unknown EWA mode: " + str(mode))
146
+ radius = float(third_zero * blur)
147
+ squared_radius = radius * radius
148
+ # A uniform table in squared distance avoids per-weight square roots.
149
+ squared_distances = np.linspace(0.0, squared_radius, _LUT_INTERVALS + 1)
150
+ r = np.sqrt(squared_distances) / blur
151
+ table = _jinc(r) * _jinc(r * first_zero / third_zero)
152
+ table[-1] = 0.0
153
+ # Duplicate endpoint makes interpolation at/outside support safe.
154
+ table = np.concatenate((table, np.zeros(1, dtype=np.float64)))
155
+ table.setflags(write=False)
156
+ return radius, table, _LUT_INTERVALS / squared_radius
157
+
158
+ def _lookup_ewa(squared_distance: np.ndarray, table: np.ndarray,
159
+ table_scale: float) -> np.ndarray:
160
+ position = np.minimum(squared_distance * table_scale, float(_LUT_INTERVALS))
161
+ index = position.astype(np.intp)
162
+ fraction = position - index
163
+ return table[index] + fraction * (table[index + 1] - table[index])
164
+
165
+ def _ewa_axis(source_size: int, target_size: int,
166
+ radius: float) -> Tuple[np.ndarray, np.ndarray]:
167
+ ratio = source_size / target_size
168
+ footprint_scale = max(1.0, ratio)
169
+ support = radius * footprint_scale
170
+ centers = (np.arange(target_size, dtype=np.float64) + 0.5) * ratio - 0.5
171
+ # All source indices with nonzero support fit in this fixed-width table.
172
+ count = min(source_size, int(math.ceil(2.0 * support)) + 1)
173
+ starts = np.maximum(0, np.ceil(centers - support).astype(np.int64))
174
+ raw_indices = starts[:, None] + np.arange(count, dtype=np.int64)[None, :]
175
+ squared_distance = ((raw_indices - centers[:, None]) / footprint_scale) ** 2
176
+ valid = (raw_indices < source_size) & (squared_distance < radius * radius)
177
+ # Infinity is deliberately mapped to the zero endpoint of the lookup table.
178
+ squared_distance[~valid] = np.inf
179
+ indices = np.minimum(raw_indices, source_size - 1).astype(np.int32)
180
+ return indices, squared_distance
181
+
182
+ def _resize_ewa(image: np.ndarray, out_width: int, out_height: int,
183
+ definition: Tuple[float, np.ndarray, float],
184
+ x_axis: Tuple[np.ndarray, np.ndarray],
185
+ y_axis: Tuple[np.ndarray, np.ndarray],
186
+ interrupt: Callable[[], None],
187
+ progress: Callable[[float], None]) -> np.ndarray:
188
+ _, table, table_scale = definition
189
+ in_height, in_width, channels = image.shape
190
+ x_indices, x_squared = x_axis
191
+ y_indices, y_squared = y_axis
192
+ nx, ny = x_indices.shape[1], y_indices.shape[1]
193
+ total_pixels = out_width * out_height
194
+ output = np.empty((total_pixels, channels), dtype=np.float32)
195
+ # Match the float64 weights once; otherwise SciPy may repeatedly upcast
196
+ # the complete source image for every output tile.
197
+ source_flat = np.ascontiguousarray(image, dtype=np.float64).reshape(-1, channels)
198
+ pixel_block = max(1, min(2048, _PAIR_BUDGET // max(1, nx * ny)))
199
+ index_dtype = np.int32 if in_width * in_height < 2**31 else np.int64
200
+
201
+ for begin in range(0, total_pixels, pixel_block):
202
+ interrupt()
203
+ end = min(begin + pixel_block, total_pixels)
204
+ output_pixels = np.arange(begin, end, dtype=np.int64)
205
+ oy, ox = np.divmod(output_pixels, out_width)
206
+ count = end - begin
207
+ weighted_sum = np.zeros((count, channels), dtype=np.float64)
208
+ weight_sum = np.zeros(count, dtype=np.float64)
209
+ # Also tile source taps, so even a huge reduction to 1x1 doesn't
210
+ # allocate one enormous output_pixels x source_pixels weight array.
211
+ x_chunk = min(nx, max(1, _PAIR_BUDGET // count))
212
+ y_chunk = min(ny, max(1, _PAIR_BUDGET // (count * x_chunk)))
213
+
214
+ for ys in range(0, ny, y_chunk):
215
+ ye = min(ys + y_chunk, ny)
216
+ yi = y_indices[oy, ys:ye]
217
+ dy = y_squared[oy, ys:ye]
218
+ for xs in range(0, nx, x_chunk):
219
+ interrupt()
220
+ xe = min(xs + x_chunk, nx)
221
+ xi = x_indices[ox, xs:xe]
222
+ dx = x_squared[ox, xs:xe]
223
+ distance = dy[:, :, None] + dx[:, None, :]
224
+ weights = _lookup_ewa(distance, table, table_scale)
225
+ taps_per_pixel = (ye - ys) * (xe - xs)
226
+ flat_weights = weights.reshape(count, taps_per_pixel)
227
+ weight_sum += flat_weights.sum(axis=1)
228
+ source_indices = (
229
+ yi.astype(np.int64)[:, :, None] * in_width
230
+ + xi[:, None, :]
231
+ ).astype(index_dtype, copy=False)
232
+ row_pointers = np.arange(count + 1, dtype=np.int64) * taps_per_pixel
233
+ # Sparse multiply avoids materializing a large [pixel,tap,RGBA]
234
+ # gather. Each row is one target pixel's full 2-D footprint.
235
+ operator = sparse.csr_matrix(
236
+ (weights.ravel(), source_indices.ravel(), row_pointers),
237
+ shape=(count, in_width * in_height),
238
+ )
239
+ weighted_sum += operator @ source_flat
240
+ if not np.isfinite(weight_sum).all() or np.any(np.abs(weight_sum) < 1.0e-12):
241
+ raise RuntimeError("Salia_Rescale_Image: degenerate EWA normalization.")
242
+ output[begin:end] = weighted_sum / weight_sum[:, None]
243
+ progress(end / total_pixels)
244
+ return output.reshape(out_height, out_width, channels)
245
+
246
+ class EwaLanczosSharpResizer:
247
+ """Resample each requested size from the original prepared source.
248
+
249
+ Color preparation happens once. No candidate is resized from a previous
250
+ candidate. Axis tables are cheap and computed for each requested size.
251
+ The caller can cache finished candidate images when useful.
252
+ """
253
+ def __init__(self, source: np.ndarray, interrupt: Callable[[], None] = lambda: None):
254
+ source = np.asarray(source)
255
+ if source.ndim != 3 or source.shape[2] not in (3, 4) or min(source.shape[:2]) < 1:
256
+ raise ValueError("EWA source must be a nonempty HWC RGB/RGBA array.")
257
+ if not np.isfinite(source).all():
258
+ raise ValueError("EWA source contains NaN or infinity.")
259
+ self.source = np.ascontiguousarray(source, dtype=np.float32)
260
+ self.prepared = _prepare_image(self.source)
261
+ self.definition = _ewa_definition(_MODES[0])
262
+ self.interrupt = interrupt
263
+
264
+ def resize(self, width: int, height: int) -> np.ndarray:
265
+ if width < 1 or height < 1:
266
+ raise ValueError("EWA dimensions must be positive.")
267
+ self.interrupt()
268
+ if (int(width), int(height)) == (self.source.shape[1], self.source.shape[0]):
269
+ return self.source.copy()
270
+ radius = self.definition[0]
271
+ x_axis = _ewa_axis(self.source.shape[1], int(width), radius)
272
+ y_axis = _ewa_axis(self.source.shape[0], int(height), radius)
273
+ filtered = _resize_ewa(
274
+ self.prepared, int(width), int(height), self.definition,
275
+ x_axis, y_axis, self.interrupt, lambda value: None,
276
+ )
277
+ self.interrupt()
278
+ return _finish_image(filtered, self.source.shape[2])
279
+
280
+
281
+ def resize_rgba_ewa(source: np.ndarray, width: int, height: int,
282
+ interrupt: Callable[[], None] = lambda: None) -> np.ndarray:
283
+ """Standalone original-source EWA LanczosSharp resize (RGB or RGBA)."""
284
+ return EwaLanczosSharpResizer(source, interrupt).resize(width, height)
285
+
286
+
287
+ # ---------------------------------------------------------------------------
288
+ # Similarity and full-resolution crop location.
289
+ # ---------------------------------------------------------------------------
290
+
291
+ import logging
292
+ import time
293
+ from collections import OrderedDict
294
+ from scipy.signal import correlate
295
+
296
+ _LOG = logging.getLogger(__name__)
297
+ _MAX_DIMENSION = 32768
298
+ _IMPROVEMENT_EPS = 1.0e-12 # In normalized error units, not the 0..200 score.
299
+
300
+
301
+ def _rgba_array(image, name="image"):
302
+ """Private normalized float32 copy; hidden RGB is retained but never scored."""
303
+ result = np.asarray(image)
304
+ if result.ndim != 3 or result.shape[-1] not in (3, 4):
305
+ raise ValueError("%s must be HWC RGB or RGBA." % name)
306
+ if min(result.shape[:2]) < 1:
307
+ raise ValueError("%s is empty." % name)
308
+ if not np.issubdtype(result.dtype, np.floating):
309
+ raise ValueError("%s must contain floating-point values in [0, 1]." % name)
310
+ if not np.isfinite(result).all():
311
+ raise ValueError("%s contains NaN or infinity." % name)
312
+ result = np.clip(result, 0.0, 1.0).astype(np.float32, copy=True)
313
+ if result.shape[-1] == 3:
314
+ result = np.concatenate((result, np.ones((*result.shape[:2], 1), np.float32)), axis=-1)
315
+ return np.ascontiguousarray(result)
316
+
317
+
318
+ def _weights(template):
319
+ alpha = template[..., 3].astype(np.float64)
320
+ return np.where(alpha > _ALPHA_EPSILON, alpha, 0.0)
321
+
322
+
323
+ def _color_error(background, template):
324
+ # Straight sRGB, not premultiplied RGB: half-alpha green can match green.
325
+ delta = background[..., :3].astype(np.float64) - template[..., :3]
326
+ error = np.mean(delta * delta, axis=-1)
327
+ return np.where(background[..., 3] > _ALPHA_EPSILON, error, 1.0)
328
+
329
+
330
+ def GET_RECTS_SIMILARITY(rect1, rect2, template_mode=False):
331
+ """Compare equal-size HWC float RGB/RGBA rectangles; return 0..200.
332
+
333
+ Default is symmetric: weight by max(alpha1, alpha2); RGB differences
334
+ count only when BOTH pixels are visible. A visible/invisible pair has
335
+ maximum error. If both pixels are invisible, hidden RGB is irrelevant.
336
+ Positive alpha magnitudes are confidence weights, not color darkness.
337
+ Thus solid green at alpha .5 and at alpha 1 have similarity 200.
338
+
339
+ template_mode=True is directional: rect1 is background; rect2 is the
340
+ template. Only rect2 alpha weights the score, so its transparent padding
341
+ does not punish a visible background. Used for locating and refining.
342
+ A fully transparent template raises ValueError (no matching evidence).
343
+ """
344
+ a, b = _rgba_array(rect1, "rect1"), _rgba_array(rect2, "rect2")
345
+ if a.shape != b.shape:
346
+ raise ValueError("GET_RECTS_SIMILARITY requires equal rectangle dimensions.")
347
+ if template_mode:
348
+ weight = _weights(b)
349
+ total = float(weight.sum())
350
+ if total <= 0.0:
351
+ raise ValueError("A fully transparent template has no matching information.")
352
+ error = float(np.sum(weight * _color_error(a, b)) / total)
353
+ else:
354
+ aa, ba = _weights(a), _weights(b)
355
+ weight = np.maximum(aa, ba)
356
+ total = float(weight.sum())
357
+ if total <= 0.0:
358
+ return 200.0
359
+ visible_both = (aa > 0.0) & (ba > 0.0)
360
+ delta = a[..., :3].astype(np.float64) - b[..., :3]
361
+ pixel_error = np.where(visible_both, np.mean(delta * delta, axis=-1), 1.0)
362
+ error = float(np.sum(weight * pixel_error) / total)
363
+ return float(200.0 * (1.0 - np.clip(error, 0.0, 1.0)))
364
+
365
+
366
+ def _overlap(background, template, x, y):
367
+ bh, bw = background.shape[:2]
368
+ th, tw = template.shape[:2]
369
+ x0, y0 = max(0, x), max(0, y)
370
+ x1, y1 = min(bw, x + tw), min(bh, y + th)
371
+ if x1 <= x0 or y1 <= y0:
372
+ return None
373
+ return (slice(y0, y1), slice(x0, x1),
374
+ slice(y0 - y, y1 - y), slice(x0 - x, x1 - x))
375
+
376
+
377
+ def _error_at(background, template, x, y):
378
+ """Full template normalization: clipping outside the canvas cannot win."""
379
+ weight = _weights(template)
380
+ total = float(weight.sum())
381
+ if total <= 0.0:
382
+ return float("inf")
383
+ overlap = _overlap(background, template, x, y)
384
+ if overlap is None:
385
+ return 1.0
386
+ by, bx, ty, tx = overlap
387
+ inside_weight = weight[ty, tx]
388
+ # Off-canvas visible pixels are maximum mismatch, not discarded samples.
389
+ outside_error = max(0.0, total - float(inside_weight.sum()))
390
+ inside_error = np.sum(inside_weight * _color_error(background[by, bx], template[ty, tx]))
391
+ return float(np.clip((outside_error + inside_error) / total, 0.0, 1.0))
392
+
393
+
394
+ def _locate_unedited(background, template, interrupt=lambda: None):
395
+ """Evaluate every fully-contained placement using weighted RGB SSD.
396
+
397
+ FFT correlation is an algebraic acceleration of the SAME per-pixel
398
+ error. No image pyramid, approximate search, or reduced-resolution crop.
399
+ Re-evaluate near-best candidates directly to remove FFT roundoff.
400
+ """
401
+ bh, bw = background.shape[:2]
402
+ th, tw = template.shape[:2]
403
+ if tw > bw or th > bh:
404
+ raise ValueError("Unedited_Rect is larger than background; it cannot be a crop of it.")
405
+ weight = _weights(template)
406
+ total = float(weight.sum())
407
+ if total <= 0.0:
408
+ raise ValueError("Unedited_Rect is fully transparent; its position cannot be located.")
409
+ visible = (background[..., 3] > _ALPHA_EPSILON).astype(np.float64)
410
+ rgb = background[..., :3].astype(np.float64)
411
+ template_rgb = template[..., :3].astype(np.float64)
412
+
413
+ def corr(a, b):
414
+ interrupt()
415
+ result = correlate(a, b, mode="valid", method="fft")
416
+ interrupt()
417
+ return result
418
+
419
+ background_square = np.mean(rgb * rgb, axis=-1)
420
+ template_square = np.mean(template_rgb * template_rgb, axis=-1)
421
+ if np.all(visible):
422
+ errors = corr(background_square, weight)
423
+ errors += float(np.sum(weight * template_square))
424
+ for channel in range(3):
425
+ errors -= (2.0 / 3.0) * corr(rgb[..., channel], weight * template_rgb[..., channel])
426
+ else:
427
+ errors = corr(1.0 - visible + visible * background_square, weight)
428
+ errors += corr(visible, weight * template_square)
429
+ for channel in range(3):
430
+ errors -= (2.0 / 3.0) * corr(visible * rgb[..., channel], weight * template_rgb[..., channel])
431
+ errors /= total
432
+ np.clip(errors, 0.0, 1.0, out=errors)
433
+ minimum = float(errors.min())
434
+ near_best = np.flatnonzero(errors.ravel() <= minimum + 1.0e-12)
435
+ # Never drop a possible best match because many low-contrast positions
436
+ # share a near-equal FFT score. Check the earliest candidate and the FFT
437
+ # argmin first, then every remaining near-best candidate if necessary.
438
+ # A directly verified EXACT zero is the mathematical lower bound, so
439
+ # only that allows early exit. Uniform duplicate crops stop immediately.
440
+ fft_best = int(np.argmin(errors))
441
+ first = int(near_best[0])
442
+ candidates = (first, fft_best)
443
+ best_error, best_x, best_y = float("inf"), 0, 0
444
+ from itertools import chain
445
+ for flat in chain(candidates, (int(k) for k in near_best if k != first and k != fft_best)):
446
+ interrupt()
447
+ y, x = divmod(int(flat), errors.shape[1])
448
+ error = _error_at(background, template, x, y)
449
+ if error < best_error:
450
+ best_error, best_x, best_y = error, x, y
451
+ if best_error == 0.0:
452
+ break
453
+ return best_x, best_y, best_error, int(near_best.size)
454
+
455
+
456
+ def _offsets(radius):
457
+ # Current center first; for equal improvements, favor the smallest change.
458
+ return sorted(((dx, dy) for dy in range(-radius, radius + 1)
459
+ for dx in range(-radius, radius + 1)),
460
+ key=lambda p: (p[0] * p[0] + p[1] * p[1], abs(p[1]), abs(p[0]), p[1], p[0]))
461
+
462
+
463
+ def _top_left(center_x, center_y, width, height):
464
+ # Pixel-edge coordinates: geometric center is (x + width/2, y + height/2).
465
+ # Odd/even size changes can require a half-pixel rounding to paste pixels.
466
+ return (int(math.floor(center_x - width / 2.0 + 0.5)),
467
+ int(math.floor(center_y - height / 2.0 + 0.5)))
468
+
469
+
470
+ class _ResizeCache:
471
+ """Bound retained candidate arrays to 64 MiB; always resize the original."""
472
+ def __init__(self, source, interrupt):
473
+ self.resizer = EwaLanczosSharpResizer(source, interrupt)
474
+ self.cache = OrderedDict()
475
+ self.bytes = 0
476
+ self.limit = 64 * 1024 * 1024
477
+ self.count = 0
478
+
479
+ def get(self, width, height):
480
+ key = (width, height)
481
+ if key in self.cache:
482
+ self.cache.move_to_end(key)
483
+ return self.cache[key]
484
+ value = self.resizer.resize(width, height)
485
+ self.count += 1
486
+ if value.nbytes <= self.limit:
487
+ while self.cache and self.bytes + value.nbytes > self.limit:
488
+ _, old = self.cache.popitem(last=False)
489
+ self.bytes -= old.nbytes
490
+ self.cache[key] = value
491
+ self.bytes += value.nbytes
492
+ return value
493
+
494
+
495
+ def _source_over(background, template, x, y):
496
+ """Straight-alpha source-over in sRGB; only the pasted region changes."""
497
+ composite = background.copy()
498
+ canvas = np.zeros_like(background)
499
+ overlap = _overlap(background, template, x, y)
500
+ if overlap is None:
501
+ return composite, canvas
502
+ by, bx, ty, tx = overlap
503
+ source, target = template[ty, tx], background[by, bx]
504
+ canvas[by, bx] = source
505
+ source_alpha, target_alpha = source[..., 3:4], target[..., 3:4]
506
+ alpha = source_alpha + target_alpha * (1.0 - source_alpha)
507
+ premultiplied = (source[..., :3] * source_alpha
508
+ + target[..., :3] * target_alpha * (1.0 - source_alpha))
509
+ rgb = np.zeros_like(premultiplied)
510
+ np.divide(premultiplied, alpha, out=rgb, where=alpha > _ALPHA_EPSILON)
511
+ result = np.concatenate((np.clip(rgb, 0.0, 1.0), alpha), axis=-1)
512
+ # Preserve the background exactly under fully transparent overlay pixels.
513
+ composite[by, bx] = np.where(source_alpha > 0.0, result, target)
514
+ # Canonical invisible RGB on the otherwise empty overlay canvas.
515
+ canvas[..., :3][canvas[..., 3] <= 0.0] = 0.0
516
+ return composite, canvas
517
+
518
+
519
+ def align_arrays(background, overlay, unedited_rect, target_width=0, target_height=0,
520
+ move_pixels=2, scale_pixels=2, max_iterations=100,
521
+ interrupt=lambda: None, progress=lambda value: None):
522
+ """Pure NumPy core, usable without ComfyUI/PyTorch; inputs HWC float arrays."""
523
+ started = time.monotonic()
524
+ background = _rgba_array(background, "background")
525
+ overlay = _rgba_array(overlay, "overlay")
526
+ unedited_rect = _rgba_array(unedited_rect, "Unedited_Rect")
527
+ for name, value, lo, hi in (
528
+ ("target_width", target_width, 0, _MAX_DIMENSION),
529
+ ("target_height", target_height, 0, _MAX_DIMENSION),
530
+ ("move_pixels", move_pixels, 0, 32),
531
+ ("scale_pixels", scale_pixels, 0, 32),
532
+ ("max_iterations", max_iterations, 1, 10000),
533
+ ):
534
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not lo <= value <= hi:
535
+ raise ValueError("%s must be an integer in [%d, %d]." % (name, lo, hi))
536
+ if float(_weights(overlay).sum()) <= 0.0:
537
+ raise ValueError("overlay is fully transparent; there is nothing to align or paste.")
538
+ interrupt()
539
+ initial_x, initial_y, crop_error, ties = _locate_unedited(background, unedited_rect, interrupt)
540
+ crop_height, crop_width = unedited_rect.shape[:2]
541
+ crop_center_x, crop_center_y = initial_x + crop_width / 2.0, initial_y + crop_height / 2.0
542
+ width, height = int(target_width or crop_width), int(target_height or crop_height)
543
+ x, y = _top_left(crop_center_x, crop_center_y, width, height)
544
+ cache = _ResizeCache(overlay, interrupt)
545
+ current = cache.get(width, height)
546
+ if float(_weights(current).sum()) <= 0.0:
547
+ raise ValueError("overlay became fully transparent at the starting target size.")
548
+ current_error = _error_at(background, current, x, y)
549
+ start_error = current_error
550
+ progress(5)
551
+ moves, scales = _offsets(move_pixels), _offsets(scale_pixels)
552
+ comparisons = 1
553
+ converged = False
554
+ trace = []
555
+ for iteration in range(1, int(max_iterations) + 1):
556
+ interrupt()
557
+ # Phase 2: ALL translations relative to the same pre-move position.
558
+ move_x, move_y, move_error, move_delta = x, y, current_error, (0, 0)
559
+ for dx, dy in moves:
560
+ interrupt()
561
+ error = _error_at(background, current, x + dx, y + dy)
562
+ comparisons += 1
563
+ if error < move_error - _IMPROVEMENT_EPS:
564
+ move_x, move_y, move_error, move_delta = x + dx, y + dy, error, (dx, dy)
565
+ x, y, current_error = move_x, move_y, move_error
566
+ center_x, center_y = x + width / 2.0, y + height / 2.0
567
+
568
+ # Phase 3: ALL sizes relative to the same pre-scale dimensions.
569
+ best_width, best_height, best_x, best_y = width, height, x, y
570
+ best_image, best_error, scale_delta = current, current_error, (0, 0)
571
+ valid_scales = 0
572
+ for dw, dh in scales:
573
+ interrupt()
574
+ candidate_width, candidate_height = width + dw, height + dh
575
+ if not (1 <= candidate_width <= _MAX_DIMENSION and 1 <= candidate_height <= _MAX_DIMENSION):
576
+ continue
577
+ candidate = cache.get(candidate_width, candidate_height)
578
+ candidate_x, candidate_y = _top_left(center_x, center_y, candidate_width, candidate_height)
579
+ error = _error_at(background, candidate, candidate_x, candidate_y)
580
+ comparisons += 1
581
+ valid_scales += 1
582
+ if error < best_error - _IMPROVEMENT_EPS:
583
+ best_width, best_height = candidate_width, candidate_height
584
+ best_x, best_y, best_image, best_error = candidate_x, candidate_y, candidate, error
585
+ scale_delta = (dw, dh)
586
+ width, height, x, y = best_width, best_height, best_x, best_y
587
+ current, current_error = best_image, best_error
588
+ trace.append("%d: move=(%+d,%+d), scale=(%+d,%+d), size=%dx%d, score=%.8f, scale_tests=%d"
589
+ % (iteration, *move_delta, *scale_delta, width, height,
590
+ 200.0 * (1.0 - current_error), valid_scales))
591
+ progress(5 + int(90 * iteration / max_iterations))
592
+ if scale_delta == (0, 0):
593
+ converged = True
594
+ break
595
+ interrupt()
596
+ composite, canvas = _source_over(background, current, x, y)
597
+ progress(100)
598
+ score = float(200.0 * (1.0 - current_error))
599
+ center_x, center_y = x + width / 2.0, y + height / 2.0
600
+ notices = []
601
+ if ties > 1:
602
+ notices.append("Crop location ambiguous: %d numerically tied placements; first confirmed best used." % ties)
603
+ if crop_error > 1.0e-8:
604
+ notices.append("Unedited_Rect was not an exact appearance match; closest crop location used.")
605
+ if x < 0 or y < 0 or x + width > background.shape[1] or y + height > background.shape[0]:
606
+ notices.append("Overlay extends outside background; pasted output is clipped. Missing visible pixels were penalized.")
607
+ reason = ("CONVERGED: current size won the scale phase (ties keep current size)."
608
+ if converged else "ITERATION LIMIT: returned best result reached; convergence not established.")
609
+ status = "\n".join([
610
+ reason,
611
+ "Crop: top_left=(%d,%d), size=%dx%d, center=(%.1f,%.1f), similarity=%.8f/200"
612
+ % (initial_x, initial_y, crop_width, crop_height, crop_center_x, crop_center_y,
613
+ 200.0 * (1.0 - crop_error)),
614
+ "Overlay: top_left=(%d,%d), size=%dx%d, center=(%.1f,%.1f), similarity=%.8f/200 (start %.8f)"
615
+ % (x, y, width, height, center_x, center_y, score, 200.0 * (1.0 - start_error)),
616
+ "Iterations=%d; move_radius=%d (%d tests/phase); scale_radius=%d (up to %d tests/phase); comparisons=%d; EWA resizes=%d; seconds=%.3f"
617
+ % (iteration, move_pixels, len(moves), scale_pixels, len(scales), comparisons,
618
+ cache.count, time.monotonic() - started),
619
+ "Algorithm: exhaustive crop location, then requested local move/scale loop; no global scale guarantee.",
620
+ *notices,
621
+ "Iteration trace:",
622
+ *trace,
623
+ ])
624
+ _LOG.info("Salia Auto Align Overlay: position=(%d,%d), size=%dx%d, score=%.8f, iterations=%d, converged=%s",
625
+ x, y, width, height, score, iteration, converged)
626
+ return {"composite": composite, "overlay_canvas": canvas, "status": status,
627
+ "x": x, "y": y, "width": width, "height": height,
628
+ "center_x": center_x, "center_y": center_y, "similarity": score,
629
+ "converged": converged, "iterations": iteration, "trace": trace,
630
+ "crop_x": initial_x, "crop_y": initial_y}
631
+
632
+
633
+ # ---------------------------------------------------------------------------
634
+ # ComfyUI adapter: RGBA-native images, plus optional standard Load Image masks.
635
+ # ---------------------------------------------------------------------------
636
+
637
+ def _tensor_image(image, name, mask=None):
638
+ import torch
639
+ if not isinstance(image, torch.Tensor) or image.ndim != 4 or image.shape[0] != 1:
640
+ raise ValueError("%s must be one IMAGE shaped [1,H,W,3 or 4]; split batches first." % name)
641
+ if not image.is_floating_point():
642
+ raise ValueError("%s must be a floating-point IMAGE." % name)
643
+ result = _rgba_array(image[0].detach().to(device="cpu", dtype=torch.float32).numpy(), name)
644
+ if mask is not None:
645
+ if not isinstance(mask, torch.Tensor):
646
+ raise ValueError("%s_mask must be a ComfyUI MASK tensor." % name)
647
+ value = mask.detach().to(device="cpu", dtype=torch.float32).numpy()
648
+ if value.ndim == 3 and value.shape[0] == 1:
649
+ value = value[0]
650
+ if value.shape != result.shape[:2]:
651
+ # Standard Load Image's no-alpha placeholder is a 64x64 all-zero
652
+ # MASK even when its RGB image has another resolution.
653
+ if value.shape == (64, 64) and not np.any(value):
654
+ value = np.zeros(result.shape[:2], dtype=np.float32)
655
+ else:
656
+ raise ValueError("%s_mask resolution must match %s. Masks are not resized." % (name, name))
657
+ if not np.isfinite(value).all():
658
+ raise ValueError("%s_mask contains NaN or infinity." % name)
659
+ # Comfy Load Image MASK is 1-alpha; supplying it REPLACES image alpha.
660
+ result[..., 3] = 1.0 - np.clip(value, 0.0, 1.0)
661
+ return result
662
+
663
+
664
+ class Salia_Auto_Align_Overlay:
665
+ @classmethod
666
+ def INPUT_TYPES(cls):
667
+ return {"required": {
668
+ "background": ("IMAGE", {"tooltip": "Single RGB/RGBA background image."}),
669
+ "overlay": ("IMAGE", {"tooltip": "Original, unscaled overlay. Every candidate is resized from this image."}),
670
+ "Unedited_Rect": ("IMAGE", {"tooltip": "Original crop from background; used only to locate the initial center and default size."}),
671
+ "target_width": ("INT", {"default": 0, "min": 0, "max": _MAX_DIMENSION, "step": 1,
672
+ "tooltip": "0 = Unedited_Rect width. Independent of target_height."}),
673
+ "target_height": ("INT", {"default": 0, "min": 0, "max": _MAX_DIMENSION, "step": 1,
674
+ "tooltip": "0 = Unedited_Rect height. Independent of target_width."}),
675
+ "move_pixels": ("INT", {"default": 2, "min": 0, "max": 32, "step": 1,
676
+ "tooltip": "Search -N..+N in X and Y. 2 = 25 positions each move phase."}),
677
+ "scale_pixels": ("INT", {"default": 2, "min": 0, "max": 32, "step": 1,
678
+ "tooltip": "Search width/height -N..+N. 2 = 25 sizes each scale phase."}),
679
+ "max_iterations": ("INT", {"default": 100, "min": 1, "max": 10000, "step": 1,
680
+ "tooltip": "Maximum move/scale cycles. Status reports if limit is reached."}),
681
+ }, "optional": {
682
+ "background_mask": ("MASK", {"tooltip": "Optional Load Image MASK (1-alpha). Replaces background alpha."}),
683
+ "overlay_mask": ("MASK", {"tooltip": "Optional Load Image MASK (1-alpha). Replaces overlay alpha."}),
684
+ "Unedited_Rect_mask": ("MASK", {"tooltip": "Optional Load Image MASK (1-alpha). Replaces Unedited_Rect alpha."}),
685
+ }}
686
+
687
+ RETURN_TYPES = ("IMAGE", "IMAGE", "STRING", "INT", "INT", "INT", "INT", "FLOAT", "FLOAT", "FLOAT")
688
+ RETURN_NAMES = ("composite_rgba", "overlay_canvas_rgba", "status", "x", "y", "width", "height",
689
+ "center_x", "center_y", "similarity")
690
+ FUNCTION = "align"
691
+ CATEGORY = "Salia/Image"
692
+ DESCRIPTION = (
693
+ "Locate an original crop anywhere in background, then align an edited overlay using repeated "
694
+ "position/size searches. Original-source EWA LanczosSharp, same implementation as the supplied "
695
+ "Salia_Rescale_Image. Transparent template pixels are ignored. Similarity 0..200. "
696
+ "Outputs two background-sized RGBA images plus status and placement. One image per input."
697
+ )
698
+
699
+ def align(self, background, overlay, Unedited_Rect, target_width=0, target_height=0,
700
+ move_pixels=2, scale_pixels=2, max_iterations=100,
701
+ background_mask=None, overlay_mask=None, Unedited_Rect_mask=None):
702
+ import torch
703
+ try:
704
+ from comfy.model_management import throw_exception_if_processing_interrupted as interrupt
705
+ except ImportError:
706
+ interrupt = lambda: None
707
+ try:
708
+ from comfy.utils import ProgressBar
709
+ bar = ProgressBar(100)
710
+ progress = lambda value: bar.update_absolute(int(value), 100)
711
+ except ImportError:
712
+ progress = lambda value: None
713
+ with torch.inference_mode():
714
+ interrupt()
715
+ result = align_arrays(
716
+ _tensor_image(background, "background", background_mask),
717
+ _tensor_image(overlay, "overlay", overlay_mask),
718
+ _tensor_image(Unedited_Rect, "Unedited_Rect", Unedited_Rect_mask),
719
+ target_width, target_height, move_pixels, scale_pixels, max_iterations,
720
+ interrupt, progress,
721
+ )
722
+ # Comfy image nodes conventionally return CPU float32 IMAGE tensors.
723
+ composite = torch.from_numpy(np.ascontiguousarray(result["composite"])).unsqueeze(0)
724
+ canvas = torch.from_numpy(np.ascontiguousarray(result["overlay_canvas"])).unsqueeze(0)
725
+ return (composite, canvas, result["status"], result["x"], result["y"],
726
+ result["width"], result["height"], result["center_x"], result["center_y"],
727
+ result["similarity"])
728
+
729
+
730
+ NODE_CLASS_MAPPINGS = {"Salia_Auto_Align_Overlay": Salia_Auto_Align_Overlay}
731
+ NODE_DISPLAY_NAME_MAPPINGS = {"Salia_Auto_Align_Overlay": "Salia Auto Align Overlay (EWA LanczosSharp)"}