Upload Salia_Auto_Align_Overlay.py
Browse files- Salia_Auto_Align_Overlay.py +40 -22
Salia_Auto_Align_Overlay.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
Salia Auto Align Overlay -- continuous registration, v2.
|
| 3 |
=======================================================
|
| 4 |
Install this single file in ComfyUI/custom_nodes/, replacing the earlier
|
| 5 |
Salia_Auto_Align_Overlay.py. Restart ComfyUI and add a NEW copy of the node
|
|
@@ -20,21 +20,25 @@ pyramid_levels: coarse-to-fine matching levels (3).
|
|
| 20 |
robust_threshold: RGB-error scale for soft-L1 outlier suppression (0.05).
|
| 21 |
scale_limit: allowed scale ratio relative to each initial dimension (2.0
|
| 22 |
permits half to double independently). A bound is not a pixel search step.
|
|
|
|
|
|
|
|
|
|
| 23 |
Center can move by one initial width/height around the located crop center.
|
| 24 |
One image per input. Split batches upstream.
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
so connect its MASK when loading
|
|
|
|
| 30 |
|
| 31 |
Algorithm
|
| 32 |
---------
|
| 33 |
1. Locate the original crop with full-resolution masked template matching
|
| 34 |
(weighted color SSD accelerated by float64 FFT correlation). Directly
|
| 35 |
verify near-best matches; report ambiguous or nonexact locations.
|
| 36 |
-
|
| 37 |
-
pasted. If an opaque/RGB crop has lost alpha, a verified near-exact RGB
|
| 38 |
copy match can recover its location without punishing transparent padding.
|
| 39 |
2. Jointly optimize center X/Y and independent positive width/height using
|
| 40 |
scipy.optimize.least_squares(method='trf') with a weighted soft-L1 loss.
|
|
@@ -293,10 +297,9 @@ def resize_rgba_ewa(source: np.ndarray, width: int, height: int,
|
|
| 293 |
import logging
|
| 294 |
import time
|
| 295 |
from scipy.signal import correlate
|
| 296 |
-
__version__ = "2.
|
| 297 |
_LOG = logging.getLogger(__name__)
|
| 298 |
_MAX_DIMENSION = 32768
|
| 299 |
-
_MIN_CROP_SIMILARITY = 199.8
|
| 300 |
_RGB_COPY_ERROR_TOLERANCE = 1.0e-6
|
| 301 |
|
| 302 |
def _rgba_array(image, name="image"):
|
|
@@ -487,6 +490,10 @@ def _tensor_image(image, name, mask=None):
|
|
| 487 |
if not image.is_floating_point():
|
| 488 |
raise ValueError("%s must be a floating-point IMAGE." % name)
|
| 489 |
result = _rgba_array(image[0].detach().to(device="cpu", dtype=torch.float32).numpy(), name)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
if mask is not None:
|
| 491 |
if not isinstance(mask, torch.Tensor):
|
| 492 |
raise ValueError("%s_mask must be a ComfyUI MASK tensor." % name)
|
|
@@ -502,7 +509,7 @@ def _tensor_image(image, name, mask=None):
|
|
| 502 |
raise ValueError("%s_mask resolution must match %s. Masks are not resized." % (name, name))
|
| 503 |
if not np.isfinite(value).all():
|
| 504 |
raise ValueError("%s_mask contains NaN or infinity." % name)
|
| 505 |
-
#
|
| 506 |
result[..., 3] = 1.0 - np.clip(value, 0.0, 1.0)
|
| 507 |
# Preserve the fact that RGB had NO alpha. Promoting it here used to erase
|
| 508 |
# that information before crop-location diagnostics and recovery.
|
|
@@ -750,7 +757,7 @@ class _RegistrationLevel:
|
|
| 750 |
|
| 751 |
|
| 752 |
def _validate_registration_options(target_width, target_height, max_evaluations,
|
| 753 |
-
pyramid_levels, robust_threshold, scale_limit):
|
| 754 |
for name, value, lo, hi in (
|
| 755 |
("target_width", target_width, 0, _MAX_DIMENSION),
|
| 756 |
("target_height", target_height, 0, _MAX_DIMENSION),
|
|
@@ -760,7 +767,8 @@ def _validate_registration_options(target_width, target_height, max_evaluations,
|
|
| 760 |
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not lo <= value <= hi:
|
| 761 |
raise ValueError("%s must be an integer in [%d,%d]." % (name, lo, hi))
|
| 762 |
for name, value, lo, hi in (("robust_threshold", robust_threshold, 0.001, 1.0),
|
| 763 |
-
("scale_limit", scale_limit, 1.01, 8.0)
|
|
|
|
| 764 |
if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
|
| 765 |
raise ValueError("%s must be a finite number in [%g,%g]." % (name, lo, hi))
|
| 766 |
if not math.isfinite(float(value)) or not lo <= value <= hi:
|
|
@@ -777,7 +785,8 @@ def _input_alpha_description(name, rgba, input_channels):
|
|
| 777 |
|
| 778 |
def align_arrays(background, overlay, unedited_rect, target_width=0, target_height=0,
|
| 779 |
max_evaluations=100, pyramid_levels=3, robust_threshold=0.05,
|
| 780 |
-
scale_limit=2.0, interrupt=lambda: None, progress=lambda value: None
|
|
|
|
| 781 |
"""Locate the crop, jointly optimize four continuous values, then render.
|
| 782 |
|
| 783 |
No pixel-step grid, alternating move/scale phase, rotation, shear, or
|
|
@@ -786,7 +795,8 @@ def align_arrays(background, overlay, unedited_rect, target_width=0, target_heig
|
|
| 786 |
"""
|
| 787 |
started = time.monotonic()
|
| 788 |
_validate_registration_options(target_width, target_height, max_evaluations,
|
| 789 |
-
pyramid_levels, robust_threshold, scale_limit)
|
|
|
|
| 790 |
raw_inputs = (background, overlay, unedited_rect)
|
| 791 |
background = _rgba_array(background, "background")
|
| 792 |
overlay = _rgba_array(overlay, "overlay")
|
|
@@ -834,7 +844,9 @@ def align_arrays(background, overlay, unedited_rect, target_width=0, target_heig
|
|
| 834 |
"An RGB-only candidate had insufficient visible/texture evidence and was not accepted. "
|
| 835 |
"Hidden RGB in transparent pixels cannot establish a reliable visible match.")
|
| 836 |
crop_similarity = 200.0 * (1.0 - crop_error)
|
| 837 |
-
|
|
|
|
|
|
|
| 838 |
# Solver convergence is not evidence of correct crop localization.
|
| 839 |
# Return an explicit failure through the existing status socket and
|
| 840 |
# preserve background instead of pasting a wrong result somewhere.
|
|
@@ -842,8 +854,10 @@ def align_arrays(background, overlay, unedited_rect, target_width=0, target_heig
|
|
| 842 |
"LOCATION FAILED: original crop was not located reliably. No overlay was pasted.",
|
| 843 |
"Closest candidate: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200; required >= %.4f/200."
|
| 844 |
% (crop_x, crop_y, unedited_rect.shape[1], unedited_rect.shape[0], crop_similarity,
|
| 845 |
-
|
| 846 |
-
"The
|
|
|
|
|
|
|
| 847 |
"Check image wiring, crop resizing/flipping, and corresponding MASK/alpha inputs.",
|
| 848 |
"Output coordinates=-1 and dimensions=0 indicate no accepted placement.",
|
| 849 |
input_diagnostics, *crop_notes,
|
|
@@ -962,6 +976,8 @@ def align_arrays(background, overlay, unedited_rect, target_width=0, target_heig
|
|
| 962 |
"Crop: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200"
|
| 963 |
% (crop_x, crop_y, crop_width, crop_height, 200.0 * (1.0 - crop_error)),
|
| 964 |
"Crop match mode: " + crop_match_mode,
|
|
|
|
|
|
|
| 965 |
input_diagnostics,
|
| 966 |
"Overlay: top_left=(%.8f,%.8f), size=(%.8f,%.8f), center=(%.8f,%.8f)"
|
| 967 |
% (x, y, width, height, center_x, center_y),
|
|
@@ -1006,10 +1022,12 @@ class Salia_Auto_Align_Overlay:
|
|
| 1006 |
"tooltip": "Soft-L1 RGB threshold: smaller values reduce influence of large appearance edits."}),
|
| 1007 |
"scale_limit": ("FLOAT", {"default": 2.0, "min": 1.01, "max": 8.0, "step": 0.1,
|
| 1008 |
"tooltip": "Independent width/height ratio bounds: 2 permits 0.5x..2x initial dimensions. Not a pixel increment."}),
|
|
|
|
|
|
|
| 1009 |
}, "optional": {
|
| 1010 |
-
"background_mask": ("MASK", {"tooltip": "
|
| 1011 |
-
"overlay_mask": ("MASK", {"tooltip": "
|
| 1012 |
-
"Unedited_Rect_mask": ("MASK", {"tooltip": "
|
| 1013 |
}}
|
| 1014 |
|
| 1015 |
RETURN_TYPES = ("IMAGE", "IMAGE", "STRING", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT")
|
|
@@ -1026,7 +1044,7 @@ class Salia_Auto_Align_Overlay:
|
|
| 1026 |
|
| 1027 |
def align(self, background, overlay, Unedited_Rect, target_width=0, target_height=0,
|
| 1028 |
max_evaluations=100, pyramid_levels=3, robust_threshold=0.05, scale_limit=2.0,
|
| 1029 |
-
background_mask=None, overlay_mask=None, Unedited_Rect_mask=None):
|
| 1030 |
import torch
|
| 1031 |
try:
|
| 1032 |
from comfy.model_management import throw_exception_if_processing_interrupted as interrupt
|
|
@@ -1050,7 +1068,7 @@ class Salia_Auto_Align_Overlay:
|
|
| 1050 |
_tensor_image(overlay, "overlay", overlay_mask),
|
| 1051 |
_tensor_image(Unedited_Rect, "Unedited_Rect", Unedited_Rect_mask),
|
| 1052 |
target_width, target_height, max_evaluations, pyramid_levels,
|
| 1053 |
-
robust_threshold, scale_limit, interrupt, progress,
|
| 1054 |
)
|
| 1055 |
composite = torch.from_numpy(np.ascontiguousarray(result["composite"])).unsqueeze(0)
|
| 1056 |
canvas = torch.from_numpy(np.ascontiguousarray(result["overlay_canvas"])).unsqueeze(0)
|
|
|
|
| 1 |
"""
|
| 2 |
+
Salia Auto Align Overlay -- continuous registration, v2.2
|
| 3 |
=======================================================
|
| 4 |
Install this single file in ComfyUI/custom_nodes/, replacing the earlier
|
| 5 |
Salia_Auto_Align_Overlay.py. Restart ComfyUI and add a NEW copy of the node
|
|
|
|
| 20 |
robust_threshold: RGB-error scale for soft-L1 outlier suppression (0.05).
|
| 21 |
scale_limit: allowed scale ratio relative to each initial dimension (2.0
|
| 22 |
permits half to double independently). A bound is not a pixel search step.
|
| 23 |
+
min_tolerance: minimum original-crop similarity as a fraction of 200 (0.9
|
| 24 |
+
means 180/200). Always find the highest-scoring location first, then check
|
| 25 |
+
this acceptance threshold. It never stops at the first acceptable location.
|
| 26 |
Center can move by one initial width/height around the located crop center.
|
| 27 |
One image per input. Split batches upstream.
|
| 28 |
|
| 29 |
+
Native RGBA inputs always use their embedded alpha, even if an optional
|
| 30 |
+
*_mask is connected. For RGB inputs only, optional *_mask inputs accept
|
| 31 |
+
standard Load Image MASKs (1-alpha). RGB without a mask is opaque. Standard
|
| 32 |
+
Comfy Load Image separates alpha from RGB, so connect its MASK when loading
|
| 33 |
+
transparent PNGs with that loader.
|
| 34 |
|
| 35 |
Algorithm
|
| 36 |
---------
|
| 37 |
1. Locate the original crop with full-resolution masked template matching
|
| 38 |
(weighted color SSD accelerated by float64 FFT correlation). Directly
|
| 39 |
verify near-best matches; report ambiguous or nonexact locations.
|
| 40 |
+
The best crop location must score at least min_tolerance*200 or no overlay
|
| 41 |
+
is pasted. If an opaque/RGB crop has lost alpha, a verified near-exact RGB
|
| 42 |
copy match can recover its location without punishing transparent padding.
|
| 43 |
2. Jointly optimize center X/Y and independent positive width/height using
|
| 44 |
scipy.optimize.least_squares(method='trf') with a weighted soft-L1 loss.
|
|
|
|
| 297 |
import logging
|
| 298 |
import time
|
| 299 |
from scipy.signal import correlate
|
| 300 |
+
__version__ = "2.2.0"
|
| 301 |
_LOG = logging.getLogger(__name__)
|
| 302 |
_MAX_DIMENSION = 32768
|
|
|
|
| 303 |
_RGB_COPY_ERROR_TOLERANCE = 1.0e-6
|
| 304 |
|
| 305 |
def _rgba_array(image, name="image"):
|
|
|
|
| 490 |
if not image.is_floating_point():
|
| 491 |
raise ValueError("%s must be a floating-point IMAGE." % name)
|
| 492 |
result = _rgba_array(image[0].detach().to(device="cpu", dtype=torch.float32).numpy(), name)
|
| 493 |
+
# Embedded alpha is authoritative for RGBA. Do not replace, multiply or
|
| 494 |
+
# invert it through the external MASK, even if that mask is connected.
|
| 495 |
+
if int(image.shape[-1]) == 4:
|
| 496 |
+
return result
|
| 497 |
if mask is not None:
|
| 498 |
if not isinstance(mask, torch.Tensor):
|
| 499 |
raise ValueError("%s_mask must be a ComfyUI MASK tensor." % name)
|
|
|
|
| 509 |
raise ValueError("%s_mask resolution must match %s. Masks are not resized." % (name, name))
|
| 510 |
if not np.isfinite(value).all():
|
| 511 |
raise ValueError("%s_mask contains NaN or infinity." % name)
|
| 512 |
+
# RGB has no alpha: reconstruct it from the Comfy Load Image MASK.
|
| 513 |
result[..., 3] = 1.0 - np.clip(value, 0.0, 1.0)
|
| 514 |
# Preserve the fact that RGB had NO alpha. Promoting it here used to erase
|
| 515 |
# that information before crop-location diagnostics and recovery.
|
|
|
|
| 757 |
|
| 758 |
|
| 759 |
def _validate_registration_options(target_width, target_height, max_evaluations,
|
| 760 |
+
pyramid_levels, robust_threshold, scale_limit, min_tolerance=0.9):
|
| 761 |
for name, value, lo, hi in (
|
| 762 |
("target_width", target_width, 0, _MAX_DIMENSION),
|
| 763 |
("target_height", target_height, 0, _MAX_DIMENSION),
|
|
|
|
| 767 |
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or not lo <= value <= hi:
|
| 768 |
raise ValueError("%s must be an integer in [%d,%d]." % (name, lo, hi))
|
| 769 |
for name, value, lo, hi in (("robust_threshold", robust_threshold, 0.001, 1.0),
|
| 770 |
+
("scale_limit", scale_limit, 1.01, 8.0),
|
| 771 |
+
("min_tolerance", min_tolerance, 0.0, 1.0)):
|
| 772 |
if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
|
| 773 |
raise ValueError("%s must be a finite number in [%g,%g]." % (name, lo, hi))
|
| 774 |
if not math.isfinite(float(value)) or not lo <= value <= hi:
|
|
|
|
| 785 |
|
| 786 |
def align_arrays(background, overlay, unedited_rect, target_width=0, target_height=0,
|
| 787 |
max_evaluations=100, pyramid_levels=3, robust_threshold=0.05,
|
| 788 |
+
scale_limit=2.0, interrupt=lambda: None, progress=lambda value: None,
|
| 789 |
+
min_tolerance=0.9):
|
| 790 |
"""Locate the crop, jointly optimize four continuous values, then render.
|
| 791 |
|
| 792 |
No pixel-step grid, alternating move/scale phase, rotation, shear, or
|
|
|
|
| 795 |
"""
|
| 796 |
started = time.monotonic()
|
| 797 |
_validate_registration_options(target_width, target_height, max_evaluations,
|
| 798 |
+
pyramid_levels, robust_threshold, scale_limit, min_tolerance)
|
| 799 |
+
min_crop_similarity = float(min_tolerance) * 200.0
|
| 800 |
raw_inputs = (background, overlay, unedited_rect)
|
| 801 |
background = _rgba_array(background, "background")
|
| 802 |
overlay = _rgba_array(overlay, "overlay")
|
|
|
|
| 844 |
"An RGB-only candidate had insufficient visible/texture evidence and was not accepted. "
|
| 845 |
"Hidden RGB in transparent pixels cannot establish a reliable visible match.")
|
| 846 |
crop_similarity = 200.0 * (1.0 - crop_error)
|
| 847 |
+
# The search above evaluates all placements and selects the highest
|
| 848 |
+
# score. Tolerance is an acceptance check ONLY, never an early exit.
|
| 849 |
+
if crop_similarity < min_crop_similarity:
|
| 850 |
# Solver convergence is not evidence of correct crop localization.
|
| 851 |
# Return an explicit failure through the existing status socket and
|
| 852 |
# preserve background instead of pasting a wrong result somewhere.
|
|
|
|
| 854 |
"LOCATION FAILED: original crop was not located reliably. No overlay was pasted.",
|
| 855 |
"Closest candidate: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200; required >= %.4f/200."
|
| 856 |
% (crop_x, crop_y, unedited_rect.shape[1], unedited_rect.shape[0], crop_similarity,
|
| 857 |
+
min_crop_similarity),
|
| 858 |
+
"min_tolerance=%.6f. The highest-scoring location was selected before checking this minimum."
|
| 859 |
+
% float(min_tolerance),
|
| 860 |
+
"The best available crop match did not meet the configured minimum. "
|
| 861 |
"Check image wiring, crop resizing/flipping, and corresponding MASK/alpha inputs.",
|
| 862 |
"Output coordinates=-1 and dimensions=0 indicate no accepted placement.",
|
| 863 |
input_diagnostics, *crop_notes,
|
|
|
|
| 976 |
"Crop: top_left=(%d,%d), size=%dx%d, similarity=%.8f/200"
|
| 977 |
% (crop_x, crop_y, crop_width, crop_height, 200.0 * (1.0 - crop_error)),
|
| 978 |
"Crop match mode: " + crop_match_mode,
|
| 979 |
+
"Crop acceptance: min_tolerance=%.6f (%.6f/200); highest score selected before threshold check."
|
| 980 |
+
% (float(min_tolerance), min_crop_similarity),
|
| 981 |
input_diagnostics,
|
| 982 |
"Overlay: top_left=(%.8f,%.8f), size=(%.8f,%.8f), center=(%.8f,%.8f)"
|
| 983 |
% (x, y, width, height, center_x, center_y),
|
|
|
|
| 1022 |
"tooltip": "Soft-L1 RGB threshold: smaller values reduce influence of large appearance edits."}),
|
| 1023 |
"scale_limit": ("FLOAT", {"default": 2.0, "min": 1.01, "max": 8.0, "step": 0.1,
|
| 1024 |
"tooltip": "Independent width/height ratio bounds: 2 permits 0.5x..2x initial dimensions. Not a pixel increment."}),
|
| 1025 |
+
"min_tolerance": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01,
|
| 1026 |
+
"tooltip": "Minimum crop similarity / 200. 0.9 = 180/200. Always searches for the highest score first; never stops at the first passing location."}),
|
| 1027 |
}, "optional": {
|
| 1028 |
+
"background_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
|
| 1029 |
+
"overlay_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
|
| 1030 |
+
"Unedited_Rect_mask": ("MASK", {"tooltip": "RGB only: optional Load Image MASK (1-alpha). RGBA always uses embedded alpha and ignores this input."}),
|
| 1031 |
}}
|
| 1032 |
|
| 1033 |
RETURN_TYPES = ("IMAGE", "IMAGE", "STRING", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT", "FLOAT")
|
|
|
|
| 1044 |
|
| 1045 |
def align(self, background, overlay, Unedited_Rect, target_width=0, target_height=0,
|
| 1046 |
max_evaluations=100, pyramid_levels=3, robust_threshold=0.05, scale_limit=2.0,
|
| 1047 |
+
background_mask=None, overlay_mask=None, Unedited_Rect_mask=None, min_tolerance=0.9):
|
| 1048 |
import torch
|
| 1049 |
try:
|
| 1050 |
from comfy.model_management import throw_exception_if_processing_interrupted as interrupt
|
|
|
|
| 1068 |
_tensor_image(overlay, "overlay", overlay_mask),
|
| 1069 |
_tensor_image(Unedited_Rect, "Unedited_Rect", Unedited_Rect_mask),
|
| 1070 |
target_width, target_height, max_evaluations, pyramid_levels,
|
| 1071 |
+
robust_threshold, scale_limit, interrupt, progress, min_tolerance=min_tolerance,
|
| 1072 |
)
|
| 1073 |
composite = torch.from_numpy(np.ascontiguousarray(result["composite"])).unsqueeze(0)
|
| 1074 |
canvas = torch.from_numpy(np.ascontiguousarray(result["overlay_canvas"])).unsqueeze(0)
|