756 lines
28 KiB
Python
756 lines
28 KiB
Python
"""FeiHou Toolbox custom nodes.
|
|
|
|
Copyright (C) 2026 FeiHou Toolbox contributors.
|
|
|
|
SPDX-License-Identifier: GPL-3.0
|
|
|
|
Create SCAIL-2 Colored Mask V2 is a non-conflicting copy of ComfyUI's
|
|
built-in Create SCAIL-2 Colored Mask node with an extra prefix image mask
|
|
output.
|
|
|
|
Modified from ComfyUI's built-in SCAIL2ColoredMask node.
|
|
Modifications:
|
|
- Added prefix_image_mask output for prefix image batches.
|
|
- Added configurable torch render device handling.
|
|
- Fixed replacement_mode background handling for generated masks.
|
|
- Added warnings when prefix track data contains no usable mask.
|
|
|
|
AutoRefCollage is original code for this toolbox. It uses ComfyUI's SAM3
|
|
model interfaces to extract people from multiple reference images and compose
|
|
them into portrait, square, or landscape collages.
|
|
"""
|
|
|
|
import logging
|
|
|
|
from typing_extensions import override
|
|
|
|
import torch
|
|
import torch.nn.functional as F
|
|
|
|
import comfy.model_management
|
|
import comfy.utils
|
|
from comfy_api.latest import ComfyExtension, io
|
|
from comfy.ldm.sam3.tracker import unpack_masks
|
|
|
|
|
|
SAM3TrackData = io.Custom("SAM3_TRACK_DATA")
|
|
|
|
LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
# Model was trained on these exact colors; deviating degrades multi-identity quality.
|
|
DEFAULT_PALETTE = [
|
|
(0.0, 0.0, 1.0), # Blue
|
|
(1.0, 0.0, 0.0), # Red
|
|
(0.0, 1.0, 0.0), # Green
|
|
(1.0, 0.0, 1.0), # Magenta
|
|
(0.0, 1.0, 1.0), # Cyan
|
|
(1.0, 1.0, 0.0), # Yellow
|
|
]
|
|
|
|
|
|
def _first_batch_frame(image):
|
|
if image is None:
|
|
return None
|
|
if image.ndim != 4 or image.shape[0] < 1:
|
|
raise ValueError("AutoRefCollage: image inputs must be ComfyUI IMAGE tensors shaped [B, H, W, C].")
|
|
return image[:1, ..., :3]
|
|
|
|
|
|
def _mask_bbox(mask, pad=0):
|
|
coords = torch.nonzero(mask > 0.5, as_tuple=False)
|
|
if coords.numel() == 0:
|
|
return None
|
|
y1 = int(coords[:, 0].min().item())
|
|
y2 = int(coords[:, 0].max().item()) + 1
|
|
x1 = int(coords[:, 1].min().item())
|
|
x2 = int(coords[:, 1].max().item()) + 1
|
|
height, width = mask.shape[-2], mask.shape[-1]
|
|
return (
|
|
max(0, x1 - pad),
|
|
max(0, y1 - pad),
|
|
min(width, x2 + pad),
|
|
min(height, y2 + pad),
|
|
)
|
|
|
|
|
|
def _soften_alpha(mask, blur_radius=2):
|
|
alpha = mask.float().unsqueeze(0).unsqueeze(0)
|
|
if blur_radius <= 0:
|
|
return alpha[0, 0].clamp(0, 1)
|
|
kernel = blur_radius * 2 + 1
|
|
alpha = F.avg_pool2d(alpha, kernel_size=kernel, stride=1, padding=blur_radius)
|
|
return alpha[0, 0].clamp(0, 1)
|
|
|
|
|
|
def _encode_sam3_prompt(clip, prompt):
|
|
if clip is None:
|
|
raise ValueError("AutoRefCollage / 多参图像自动拼接: CLIP input is required for SAM3 text detection.")
|
|
if not prompt or not prompt.strip():
|
|
prompt = "person"
|
|
tokens = clip.tokenize(prompt)
|
|
return clip.encode_from_tokens_scheduled(tokens)
|
|
|
|
|
|
def _extract_sam3_prompt(conditioning, device, dtype):
|
|
cond_meta = conditioning[0][1]
|
|
emb = conditioning[0][0].to(device=device, dtype=dtype)
|
|
mask = cond_meta.get("attention_mask")
|
|
if mask is not None:
|
|
mask = mask.to(device)
|
|
else:
|
|
mask = torch.ones(emb.shape[0], emb.shape[1], dtype=torch.int64, device=device)
|
|
return emb, mask
|
|
|
|
|
|
def _refine_detector_mask(sam3_model, orig_image_hwc, coarse_mask, box_xyxy, height, width, device, dtype):
|
|
pad_frac = 0.1
|
|
x1, y1, x2, y2 = box_xyxy.tolist()
|
|
bw, bh = x2 - x1, y2 - y1
|
|
cx1 = max(0, int(x1 - bw * pad_frac))
|
|
cy1 = max(0, int(y1 - bh * pad_frac))
|
|
cx2 = min(width, int(x2 + bw * pad_frac))
|
|
cy2 = min(height, int(y2 + bh * pad_frac))
|
|
if cx2 <= cx1 or cy2 <= cy1:
|
|
return F.interpolate(
|
|
coarse_mask.unsqueeze(0).unsqueeze(0),
|
|
size=(height, width),
|
|
mode="bilinear",
|
|
align_corners=False,
|
|
)[0, 0]
|
|
|
|
crop = orig_image_hwc[cy1:cy2, cx1:cx2, :3]
|
|
crop_1008 = comfy.utils.common_upscale(
|
|
crop.unsqueeze(0).movedim(-1, 1),
|
|
1008,
|
|
1008,
|
|
"bilinear",
|
|
crop="disabled",
|
|
)
|
|
crop_frame = crop_1008.to(device=device, dtype=dtype)
|
|
crop_h, crop_w = cy2 - cy1, cx2 - cx1
|
|
|
|
mask_h, mask_w = coarse_mask.shape[-2:]
|
|
mx1, my1 = int(cx1 / width * mask_w), int(cy1 / height * mask_h)
|
|
mx2, my2 = int(cx2 / width * mask_w), int(cy2 / height * mask_h)
|
|
if mx2 <= mx1 or my2 <= my1:
|
|
return F.interpolate(
|
|
coarse_mask.unsqueeze(0).unsqueeze(0),
|
|
size=(height, width),
|
|
mode="bilinear",
|
|
align_corners=False,
|
|
)[0, 0]
|
|
|
|
mask_logit = coarse_mask[..., my1:my2, mx1:mx2].unsqueeze(0).unsqueeze(0)
|
|
for _ in range(2):
|
|
coarse_input = F.interpolate(mask_logit, size=(1008, 1008), mode="bilinear", align_corners=False)
|
|
mask_logit = sam3_model.forward_segment(crop_frame, mask_inputs=coarse_input)
|
|
|
|
refined_crop = F.interpolate(mask_logit, size=(crop_h, crop_w), mode="bilinear", align_corners=False)
|
|
full_mask = torch.zeros(1, 1, height, width, device=device, dtype=dtype)
|
|
full_mask[:, :, cy1:cy2, cx1:cx2] = refined_crop
|
|
coarse_full = F.interpolate(
|
|
coarse_mask.unsqueeze(0).unsqueeze(0),
|
|
size=(height, width),
|
|
mode="bilinear",
|
|
align_corners=False,
|
|
)
|
|
return torch.maximum(full_mask[0, 0], coarse_full[0, 0])
|
|
|
|
|
|
def _segment_person_with_sam3(model, image, prompt, conditioning, threshold):
|
|
_, height, width, _ = image.shape
|
|
comfy.model_management.load_model_gpu(model)
|
|
device = comfy.model_management.get_torch_device()
|
|
dtype = model.model.get_dtype()
|
|
sam3_model = model.model.diffusion_model
|
|
text_embeddings, text_mask = _extract_sam3_prompt(conditioning, device, dtype)
|
|
|
|
image_in = comfy.utils.common_upscale(
|
|
image[..., :3].movedim(-1, 1),
|
|
1008,
|
|
1008,
|
|
"bilinear",
|
|
crop="disabled",
|
|
)
|
|
frame = image_in.to(device=device, dtype=dtype)
|
|
results = sam3_model(
|
|
frame,
|
|
text_embeddings=text_embeddings,
|
|
text_mask=text_mask,
|
|
threshold=threshold,
|
|
orig_size=(height, width),
|
|
)
|
|
scores = results["scores"][0].sigmoid()
|
|
masks = results["masks"][0]
|
|
boxes = results["boxes"][0]
|
|
keep = scores > threshold
|
|
if not keep.any():
|
|
LOGGER.warning(
|
|
"AutoRefCollage: SAM3 found no object for prompt %r at threshold %.2f; using background fallback.",
|
|
prompt,
|
|
threshold,
|
|
)
|
|
return _fallback_person_alpha(image).to(image.device)
|
|
|
|
keep_scores = scores[keep]
|
|
best_local = int(keep_scores.argmax().item())
|
|
keep_indices = torch.nonzero(keep, as_tuple=False).flatten()
|
|
best = int(keep_indices[best_local].item())
|
|
mask = _refine_detector_mask(
|
|
sam3_model,
|
|
image[0].to(device=device, dtype=dtype),
|
|
masks[best],
|
|
boxes[best],
|
|
height,
|
|
width,
|
|
device,
|
|
dtype,
|
|
)
|
|
mask = (mask > 0).float()
|
|
return _soften_alpha(mask, blur_radius=2)
|
|
|
|
|
|
def _fallback_person_alpha(image):
|
|
frame = image[0, ..., :3]
|
|
height, width, _ = frame.shape
|
|
border = max(2, min(height, width) // 80)
|
|
samples = torch.cat(
|
|
[
|
|
frame[:border].reshape(-1, 3),
|
|
frame[-border:].reshape(-1, 3),
|
|
frame[:, :border].reshape(-1, 3),
|
|
frame[:, -border:].reshape(-1, 3),
|
|
],
|
|
dim=0,
|
|
)
|
|
bg = samples.median(dim=0).values
|
|
dist = (frame - bg).abs().mean(dim=-1)
|
|
alpha = (dist > 0.055).float()
|
|
alpha = F.max_pool2d(alpha.unsqueeze(0).unsqueeze(0), kernel_size=7, stride=1, padding=3)[0, 0]
|
|
return _soften_alpha(alpha, blur_radius=2)
|
|
|
|
|
|
def _prepare_cutout(image, alpha):
|
|
frame = image[0, ..., :3]
|
|
height, width = alpha.shape
|
|
bbox = _mask_bbox(alpha, pad=max(8, min(height, width) // 80))
|
|
if bbox is None:
|
|
alpha = _fallback_person_alpha(image).to(frame.device)
|
|
bbox = _mask_bbox(alpha, pad=max(8, min(height, width) // 80))
|
|
if bbox is None:
|
|
bbox = (0, 0, width, height)
|
|
alpha = torch.ones((height, width), device=frame.device, dtype=frame.dtype)
|
|
x1, y1, x2, y2 = bbox
|
|
return {
|
|
"rgb": frame[y1:y2, x1:x2].contiguous(),
|
|
"alpha": alpha[y1:y2, x1:x2].contiguous(),
|
|
"width": x2 - x1,
|
|
"height": y2 - y1,
|
|
}
|
|
|
|
|
|
def _aspect_mode(width, height):
|
|
ratio = width / max(1, height)
|
|
if ratio < 0.85:
|
|
return "portrait"
|
|
if ratio > 1.15:
|
|
return "landscape"
|
|
return "square"
|
|
|
|
|
|
def _layout_specs(count, width, height):
|
|
mode = _aspect_mode(width, height)
|
|
if mode == "portrait":
|
|
if count == 2:
|
|
return mode, [
|
|
{"x": 0.33, "base": 0.99, "max_h": 0.80, "max_w": 0.50},
|
|
{"x": 0.67, "base": 0.92, "max_h": 0.76, "max_w": 0.50},
|
|
]
|
|
if count == 3:
|
|
return mode, [
|
|
{"x": 0.33, "base": 0.98, "max_h": 0.74, "max_w": 0.48},
|
|
{"x": 0.67, "base": 0.84, "max_h": 0.70, "max_w": 0.48},
|
|
{"x": 0.50, "base": 1.02, "max_h": 0.82, "max_w": 0.56},
|
|
]
|
|
return mode, [
|
|
{"x": 0.20, "base": 0.74, "max_h": 0.72, "max_w": 0.54},
|
|
{"x": 0.67, "base": 0.73, "max_h": 0.72, "max_w": 0.54},
|
|
{"x": 0.36, "base": 1.02, "max_h": 0.76, "max_w": 0.54},
|
|
{"x": 0.86, "base": 1.02, "max_h": 0.74, "max_w": 0.50},
|
|
][:count]
|
|
if mode == "square":
|
|
left = 0.11 if count == 4 else 0.16
|
|
right = 1.0 - left
|
|
xs = [0.5] if count == 1 else [left + (right - left) * i / (count - 1) for i in range(count)]
|
|
max_w = min(0.35, 1.08 / count)
|
|
return mode, [{"x": x, "base": 0.985, "max_h": 0.98, "max_w": max_w} for x in xs]
|
|
left = 0.13 if count == 4 else 0.17
|
|
right = 1.0 - left
|
|
xs = [0.5] if count == 1 else [left + (right - left) * i / (count - 1) for i in range(count)]
|
|
max_w = min(0.25, 0.92 / count)
|
|
return mode, [{"x": x, "base": 0.995, "max_h": 0.99, "max_w": max_w} for x in xs]
|
|
|
|
|
|
def _paste_cutout(canvas, canvas_alpha, cutout, spec, out_width, out_height):
|
|
rgb = cutout["rgb"].movedim(-1, 0).unsqueeze(0)
|
|
alpha = cutout["alpha"].unsqueeze(0).unsqueeze(0)
|
|
target_h = max(1, int(out_height * spec["max_h"]))
|
|
target_w = max(1, int(out_width * spec["max_w"]))
|
|
scale = min(target_w / max(1, cutout["width"]), target_h / max(1, cutout["height"]))
|
|
new_w = max(1, int(round(cutout["width"] * scale)))
|
|
new_h = max(1, int(round(cutout["height"] * scale)))
|
|
|
|
rgb = F.interpolate(rgb, size=(new_h, new_w), mode="bilinear", align_corners=False)[0].movedim(0, -1)
|
|
alpha = F.interpolate(alpha, size=(new_h, new_w), mode="bilinear", align_corners=False)[0, 0].clamp(0, 1)
|
|
|
|
cx = int(round(out_width * spec["x"]))
|
|
baseline = int(round(out_height * spec["base"]))
|
|
x0 = cx - new_w // 2
|
|
y0 = baseline - new_h
|
|
x1 = x0 + new_w
|
|
y1 = y0 + new_h
|
|
src_x0 = max(0, -x0)
|
|
src_y0 = max(0, -y0)
|
|
dst_x0 = max(0, x0)
|
|
dst_y0 = max(0, y0)
|
|
dst_x1 = min(out_width, x1)
|
|
dst_y1 = min(out_height, y1)
|
|
if dst_x1 <= dst_x0 or dst_y1 <= dst_y0:
|
|
return
|
|
src_x1 = src_x0 + (dst_x1 - dst_x0)
|
|
src_y1 = src_y0 + (dst_y1 - dst_y0)
|
|
src_rgb = rgb[src_y0:src_y1, src_x0:src_x1]
|
|
src_alpha = alpha[src_y0:src_y1, src_x0:src_x1].unsqueeze(-1)
|
|
dst = canvas[dst_y0:dst_y1, dst_x0:dst_x1]
|
|
canvas[dst_y0:dst_y1, dst_x0:dst_x1] = src_rgb * src_alpha + dst * (1.0 - src_alpha)
|
|
old_alpha = canvas_alpha[dst_y0:dst_y1, dst_x0:dst_x1]
|
|
canvas_alpha[dst_y0:dst_y1, dst_x0:dst_x1] = torch.maximum(old_alpha, src_alpha[..., 0])
|
|
|
|
|
|
def _compose_collage(cutouts, width, height, background):
|
|
device = comfy.model_management.intermediate_device()
|
|
dtype = torch.float32
|
|
bg = torch.tensor(_background_rgb(background), device=device, dtype=dtype)
|
|
canvas = bg.view(1, 1, 3).expand(height, width, 3).clone()
|
|
canvas_alpha = torch.zeros((height, width), device=device, dtype=dtype)
|
|
_, specs = _layout_specs(len(cutouts), width, height)
|
|
for cutout, spec in zip(cutouts, specs):
|
|
local = {
|
|
"rgb": cutout["rgb"].to(device=device, dtype=dtype),
|
|
"alpha": cutout["alpha"].to(device=device, dtype=dtype),
|
|
"width": cutout["width"],
|
|
"height": cutout["height"],
|
|
}
|
|
_paste_cutout(canvas, canvas_alpha, local, spec, width, height)
|
|
return canvas.unsqueeze(0).clamp(0, 1), canvas_alpha.unsqueeze(0).clamp(0, 1)
|
|
|
|
def _unpack(track_data):
|
|
packed = track_data["packed_masks"]
|
|
if packed is None or packed.shape[1] == 0:
|
|
return None
|
|
return unpack_masks(packed)
|
|
|
|
|
|
def _first_frame_cx_area(masks_bool):
|
|
first = masks_bool[0].float()
|
|
height, width = first.shape[-2], first.shape[-1]
|
|
n_pixels = height * width
|
|
grid_x = torch.arange(width, device=first.device, dtype=first.dtype).view(1, width)
|
|
area = first.sum(dim=(-1, -2)).clamp_(min=1)
|
|
cx = (first * grid_x).sum(dim=(-1, -2)) / area
|
|
return (cx / width).tolist(), (area / n_pixels).tolist()
|
|
|
|
|
|
def _subset_track_data(track_data, obj_indices):
|
|
out = dict(track_data)
|
|
packed = track_data["packed_masks"]
|
|
if packed is None or not obj_indices:
|
|
out["packed_masks"] = None
|
|
if "scores" in out:
|
|
out["scores"] = []
|
|
return out
|
|
out["packed_masks"] = packed[:, obj_indices].contiguous()
|
|
scores = track_data.get("scores")
|
|
if scores is not None:
|
|
out["scores"] = [scores[i] for i in obj_indices if i < len(scores)]
|
|
return out
|
|
|
|
|
|
def _background_rgb(background):
|
|
return (1.0, 1.0, 1.0) if background.startswith("white") else (0.0, 0.0, 0.0)
|
|
|
|
|
|
def _render_device(render_device="auto"):
|
|
if render_device == "cpu":
|
|
return torch.device("cpu")
|
|
if render_device in ("auto", "gpu"):
|
|
return comfy.model_management.get_torch_device()
|
|
return comfy.model_management.intermediate_device()
|
|
|
|
|
|
def _render_dtype(device):
|
|
dtype = comfy.model_management.intermediate_dtype()
|
|
if device.type == "cpu" and dtype == torch.float16:
|
|
return torch.float32
|
|
return dtype
|
|
|
|
|
|
def _has_any_mask(packed, device):
|
|
if packed is None or packed.shape[1] == 0:
|
|
return False
|
|
return bool(unpack_masks(packed.to(device)).any().item())
|
|
|
|
|
|
def _blank_images(frame_count, height, width, background, render_device="auto"):
|
|
device = _render_device(render_device)
|
|
dtype = _render_dtype(device)
|
|
bg_rgb = _background_rgb(background)
|
|
out = torch.empty(frame_count, height, width, 3, device=device, dtype=dtype)
|
|
out[..., 0], out[..., 1], out[..., 2] = bg_rgb[0], bg_rgb[1], bg_rgb[2]
|
|
return out
|
|
|
|
|
|
def _render_colored_masks(track_data, background="black", render_device="auto"):
|
|
packed = track_data["packed_masks"]
|
|
height, width = track_data["orig_size"]
|
|
device = _render_device(render_device)
|
|
dtype = _render_dtype(device)
|
|
bg_rgb = _background_rgb(background)
|
|
if packed is None or packed.shape[1] == 0:
|
|
frame_count = track_data.get("n_frames", 1) if packed is None else packed.shape[0]
|
|
return _blank_images(max(1, frame_count), height, width, background, render_device)
|
|
|
|
frame_count, n_obj = packed.shape[0], packed.shape[1]
|
|
colors = torch.tensor(
|
|
[DEFAULT_PALETTE[i % len(DEFAULT_PALETTE)] for i in range(n_obj)],
|
|
device=device,
|
|
dtype=dtype,
|
|
)
|
|
masks_full = unpack_masks(packed.to(device)).float()
|
|
mask_height, mask_width = masks_full.shape[-2], masks_full.shape[-1]
|
|
masks_full = F.interpolate(
|
|
masks_full.view(frame_count * n_obj, 1, mask_height, mask_width),
|
|
size=(height, width),
|
|
mode="nearest",
|
|
).view(frame_count, n_obj, height, width) > 0.5
|
|
any_mask = masks_full.any(dim=1)
|
|
obj_idx_map = masks_full.to(torch.uint8).argmax(dim=1)
|
|
color_overlay = colors[obj_idx_map]
|
|
bg_tensor = torch.tensor(bg_rgb, device=device, dtype=color_overlay.dtype).view(1, 1, 1, 3)
|
|
return torch.where(any_mask.unsqueeze(-1), color_overlay, bg_tensor.expand_as(color_overlay))
|
|
|
|
|
|
def _render_prefix_image_masks(
|
|
track_data,
|
|
background="white",
|
|
prefix_mask_mode="Single Image Multi Color",
|
|
max_images=5,
|
|
render_device="auto",
|
|
):
|
|
packed = track_data["packed_masks"]
|
|
height, width = track_data["orig_size"]
|
|
|
|
if packed is None or packed.shape[1] == 0:
|
|
frame_count = track_data.get("n_frames", 1) if packed is None else packed.shape[0]
|
|
LOGGER.warning("SCAIL2ColoredMaskV2: prefix_track_data has no objects; prefix_image_mask is blank.")
|
|
return _blank_images(max(1, min(frame_count, max_images)), height, width, background, render_device)
|
|
|
|
frame_count = max(1, min(packed.shape[0], max_images))
|
|
packed = packed[:frame_count]
|
|
n_obj = packed.shape[1]
|
|
if n_obj == 0:
|
|
LOGGER.warning("SCAIL2ColoredMaskV2: prefix_track_data has zero objects; prefix_image_mask is blank.")
|
|
return _blank_images(frame_count, height, width, background, render_device)
|
|
|
|
device = _render_device(render_device)
|
|
dtype = _render_dtype(device)
|
|
masks_full = unpack_masks(packed.to(device)).float()
|
|
if not masks_full.any():
|
|
LOGGER.warning("SCAIL2ColoredMaskV2: prefix_track_data masks are empty; prefix_image_mask is blank.")
|
|
mask_height, mask_width = masks_full.shape[-2], masks_full.shape[-1]
|
|
masks_full = F.interpolate(
|
|
masks_full.view(frame_count * n_obj, 1, mask_height, mask_width),
|
|
size=(height, width),
|
|
mode="nearest",
|
|
).view(frame_count, n_obj, height, width) > 0.5
|
|
|
|
bg = torch.tensor(_background_rgb(background), device=device, dtype=dtype).view(1, 1, 1, 3)
|
|
blank = bg.expand(frame_count, height, width, 3)
|
|
|
|
if prefix_mask_mode == "Multi Image Single Color":
|
|
any_mask = masks_full.any(dim=1)
|
|
blue = torch.tensor(DEFAULT_PALETTE[0], device=device, dtype=dtype).view(1, 1, 1, 3)
|
|
color_overlay = blue.expand(frame_count, height, width, 3)
|
|
return torch.where(any_mask.unsqueeze(-1), color_overlay, blank)
|
|
|
|
any_mask = masks_full.any(dim=1)
|
|
colors = torch.tensor(
|
|
[DEFAULT_PALETTE[i % len(DEFAULT_PALETTE)] for i in range(n_obj)],
|
|
device=device,
|
|
dtype=dtype,
|
|
)
|
|
obj_idx_map = masks_full.to(torch.uint8).argmax(dim=1)
|
|
color_overlay = colors[obj_idx_map]
|
|
return torch.where(any_mask.unsqueeze(-1), color_overlay, blank)
|
|
|
|
|
|
class SCAIL2ColoredMaskV2(io.ComfyNode):
|
|
"""Render SCAIL-2 colored masks plus a prefix-image colored batch mask."""
|
|
|
|
@classmethod
|
|
def define_schema(cls):
|
|
return io.Schema(
|
|
node_id="SCAIL2ColoredMaskV2",
|
|
display_name="Create SCAIL-2 Colored Mask V2",
|
|
category="conditioning/video_models/scail",
|
|
inputs=[
|
|
SAM3TrackData.Input(
|
|
"driving_track_data",
|
|
tooltip="SAM3 track of the driving pose video. Will be rendered into the pose_video_mask output.",
|
|
),
|
|
SAM3TrackData.Input(
|
|
"ref_track_data",
|
|
optional=True,
|
|
tooltip="SAM3 track of the reference image.",
|
|
),
|
|
SAM3TrackData.Input(
|
|
"prefix_track_data",
|
|
optional=True,
|
|
tooltip="SAM3 track of a prefix image batch. The first 5 frames are rendered into prefix_image_mask.",
|
|
),
|
|
io.String.Input(
|
|
"object_indices",
|
|
default="",
|
|
tooltip="Comma-separated list of person indices to include (e.g. '0,2,3'). Applied to driving, reference, and prefix masks. Empty = all.",
|
|
),
|
|
io.Combo.Input(
|
|
"sort_by",
|
|
options=["none", "left_to_right", "area"],
|
|
default="left_to_right",
|
|
tooltip="Order in which palette colors are assigned to tracked objects. left_to_right = leftmost object gets the first color; area = biggest object gets the first color; none = keep SAM3's order.",
|
|
),
|
|
io.Combo.Input(
|
|
"prefix_mask_mode",
|
|
options=["Single Image Multi Color", "Multi Image Single Color"],
|
|
default="Single Image Multi Color",
|
|
tooltip="Single Image Multi Color = each prefix image can show multiple object colors using the 6-color palette loop. Multi Image Single Color = every prefix image mask is blue.",
|
|
),
|
|
io.Boolean.Input(
|
|
"replacement_mode",
|
|
default=False,
|
|
tooltip="False = Animation Mode (pose_video_mask black background, reference_image_mask and prefix_image_mask white background). True = Replacement Mode (pose_video_mask white background, reference_image_mask and prefix_image_mask black background).",
|
|
),
|
|
io.Combo.Input(
|
|
"render_device",
|
|
options=["auto", "gpu", "cpu"],
|
|
default="auto",
|
|
tooltip="Device used to render the RGB mask tensors. auto/gpu uses ComfyUI's current torch device; cpu uses system memory.",
|
|
),
|
|
],
|
|
outputs=[
|
|
io.Image.Output("pose_video_mask"),
|
|
io.Image.Output("reference_image_mask"),
|
|
io.Image.Output("prefix_image_mask"),
|
|
],
|
|
is_experimental=True,
|
|
)
|
|
|
|
@classmethod
|
|
def execute(
|
|
cls,
|
|
driving_track_data,
|
|
object_indices,
|
|
sort_by,
|
|
prefix_mask_mode,
|
|
replacement_mode,
|
|
render_device="auto",
|
|
ref_track_data=None,
|
|
prefix_track_data=None,
|
|
) -> io.NodeOutput:
|
|
def _prep(td):
|
|
masks_bool = _unpack(td)
|
|
if sort_by != "none" and masks_bool is not None:
|
|
cx, area = _first_frame_cx_area(masks_bool)
|
|
if sort_by == "left_to_right":
|
|
order = sorted(range(len(cx)), key=lambda i: cx[i])
|
|
else:
|
|
order = sorted(range(len(area)), key=lambda i: -area[i])
|
|
td = _subset_track_data(td, order)
|
|
if object_indices.strip():
|
|
indices = [int(i.strip()) for i in object_indices.split(",") if i.strip().isdigit()]
|
|
packed = td.get("packed_masks")
|
|
n_obj = packed.shape[1] if packed is not None else 0
|
|
indices = [i for i in indices if 0 <= i < n_obj]
|
|
td = _subset_track_data(td, indices)
|
|
return td
|
|
|
|
drv = _prep(driving_track_data)
|
|
|
|
# Animation: driving=black, ref/prefix=white. Replacement: driving=white, ref/prefix=black.
|
|
mask_video = _render_colored_masks(drv, "white" if replacement_mode else "black", render_device)
|
|
ref_bg = "black" if replacement_mode else "white"
|
|
prefix_bg = "black" if replacement_mode else "white"
|
|
|
|
if ref_track_data is not None:
|
|
ref = _prep(ref_track_data)
|
|
reference_image_mask = _render_colored_masks(ref, ref_bg, render_device)
|
|
else:
|
|
height, width = drv["orig_size"]
|
|
reference_image_mask = _blank_images(1, height, width, ref_bg, render_device)
|
|
|
|
if prefix_track_data is not None:
|
|
prefix = _prep(prefix_track_data)
|
|
prefix_image_mask = _render_prefix_image_masks(
|
|
prefix,
|
|
prefix_bg,
|
|
prefix_mask_mode,
|
|
render_device=render_device,
|
|
)
|
|
if not _has_any_mask(prefix.get("packed_masks"), _render_device(render_device)):
|
|
LOGGER.warning(
|
|
"SCAIL2ColoredMaskV2: prefix_image_mask contains only the %s background. "
|
|
"Check the prefix SAM3 track input, prompt, threshold, or initial mask.",
|
|
prefix_bg,
|
|
)
|
|
else:
|
|
height, width = drv["orig_size"]
|
|
LOGGER.warning("SCAIL2ColoredMaskV2: prefix_track_data is not connected; prefix_image_mask is blank.")
|
|
prefix_image_mask = _blank_images(1, height, width, prefix_bg, render_device)
|
|
|
|
return io.NodeOutput(mask_video, reference_image_mask, prefix_image_mask)
|
|
|
|
|
|
class AutoRefCollage(io.ComfyNode):
|
|
"""Extract 2-4 reference people with SAM3 and compose an automatic collage."""
|
|
|
|
@classmethod
|
|
def define_schema(cls):
|
|
return io.Schema(
|
|
node_id="AutoRefCollage",
|
|
display_name="多参图像自动拼接",
|
|
category="image/compositing",
|
|
search_aliases=["auto reference collage", "person collage", "sam3 collage", "multi reference"],
|
|
inputs=[
|
|
io.Model.Input(
|
|
"model",
|
|
display_name="model",
|
|
tooltip="SAM3/SAM3.1 model from CheckpointLoaderSimple.",
|
|
),
|
|
io.Clip.Input(
|
|
"clip",
|
|
display_name="clip",
|
|
tooltip="SAM3/SAM3.1 CLIP from CheckpointLoaderSimple. The node encodes its internal prompt with this input.",
|
|
),
|
|
io.Image.Input("image_1", display_name="image_1"),
|
|
io.Image.Input("image_2", display_name="image_2"),
|
|
io.Image.Input("image_3", display_name="image_3", optional=True),
|
|
io.Image.Input("image_4", display_name="image_4", optional=True),
|
|
io.String.Input(
|
|
"prompt",
|
|
display_name="prompt",
|
|
default="person",
|
|
multiline=True,
|
|
tooltip="Text prompt used internally for SAM3 detection. Use a short object phrase, e.g. person or woman.",
|
|
),
|
|
io.Int.Input(
|
|
"width",
|
|
display_name="width",
|
|
default=1280,
|
|
min=64,
|
|
max=8192,
|
|
step=8,
|
|
tooltip="Output collage width.",
|
|
),
|
|
io.Int.Input(
|
|
"height",
|
|
display_name="height",
|
|
default=1280,
|
|
min=64,
|
|
max=8192,
|
|
step=8,
|
|
tooltip="Output collage height.",
|
|
),
|
|
io.Float.Input(
|
|
"detection_threshold",
|
|
display_name="detection_threshold",
|
|
default=0.5,
|
|
min=0.0,
|
|
max=1.0,
|
|
step=0.01,
|
|
tooltip="SAM3 mask threshold after segmentation. Lower values keep more edge/detail; higher values remove weak regions.",
|
|
),
|
|
io.Combo.Input(
|
|
"background",
|
|
display_name="background",
|
|
options=["white", "black"],
|
|
default="white",
|
|
tooltip="Background color for the RGB collage image output.",
|
|
),
|
|
],
|
|
outputs=[
|
|
io.Image.Output("collage"),
|
|
io.Mask.Output("alpha_mask"),
|
|
],
|
|
is_experimental=True,
|
|
)
|
|
|
|
@classmethod
|
|
def execute(
|
|
cls,
|
|
model,
|
|
clip,
|
|
image_1,
|
|
image_2,
|
|
prompt,
|
|
width,
|
|
height,
|
|
detection_threshold,
|
|
background,
|
|
image_3=None,
|
|
image_4=None,
|
|
) -> io.NodeOutput:
|
|
images = [
|
|
img
|
|
for img in (
|
|
_first_batch_frame(image_1),
|
|
_first_batch_frame(image_2),
|
|
_first_batch_frame(image_3),
|
|
_first_batch_frame(image_4),
|
|
)
|
|
if img is not None
|
|
]
|
|
if len(images) < 2:
|
|
raise ValueError("AutoRefCollage / 多参图像自动拼接: at least 2 image inputs are required.")
|
|
|
|
threshold = max(0.0, min(float(detection_threshold), 1.0))
|
|
conditioning = _encode_sam3_prompt(clip, prompt)
|
|
cutouts = []
|
|
pbar = comfy.utils.ProgressBar(len(images))
|
|
for image in images:
|
|
alpha = _segment_person_with_sam3(
|
|
model,
|
|
image,
|
|
prompt,
|
|
conditioning,
|
|
threshold,
|
|
)
|
|
cutouts.append(_prepare_cutout(image, alpha.to(image.device)))
|
|
pbar.update(1)
|
|
|
|
collage, alpha_mask = _compose_collage(cutouts, int(width), int(height), background)
|
|
return io.NodeOutput(collage, alpha_mask)
|
|
|
|
|
|
class FeiHouToolboxExtension(ComfyExtension):
|
|
@override
|
|
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
|
return [
|
|
SCAIL2ColoredMaskV2,
|
|
AutoRefCollage,
|
|
]
|
|
|
|
|
|
async def comfy_entrypoint() -> FeiHouToolboxExtension:
|
|
return FeiHouToolboxExtension()
|