Fix overlap detection with base_mask: include base_mask in initial canvas for proper overlap checking

This commit is contained in:
TJ
2025-11-03 21:36:47 +09:00
parent 5c9a2b2d4f
commit 1b6905971a
2 changed files with 16 additions and 11 deletions
+6 -6
View File
@@ -367,15 +367,15 @@ class AdvancedShapePlacementNode(comfy_io.ComfyNode):
max_consecutive_fails=max_consecutive_fails,
progress_callback=progress_callback,
debug_mode=bool(debug_mode),
base_canvas=base_np,
)
# Store the added mask (before combining with base)
added_mask = composite_mask.copy()
# Combine with base mask if provided
# Calculate added mask (composite_mask includes base, so subtract it)
if base_np is not None:
# Use maximum to combine masks (union operation)
composite_mask = np.maximum(composite_mask, base_np)
# added_mask = newly placed shapes only (composite - base)
added_mask = np.maximum(composite_mask - base_np, 0)
else:
added_mask = composite_mask.copy()
# Convert results back to torch
result_composite = numpy_to_torch_mask(composite_mask)
+10 -5
View File
@@ -357,6 +357,7 @@ def place_shapes_in_region(
max_consecutive_fails: int = 100,
progress_callback = None, # Callback for ComfyUI progress updates
debug_mode: bool = False,
base_canvas: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, List[Dict]]:
"""
Place multiple shape masks within a region mask with overlap control.
@@ -405,7 +406,11 @@ def place_shapes_in_region(
region_height, region_width = region_mask.shape
# Initialize output canvas
canvas = np.zeros_like(region_mask, dtype=np.float32)
# If base_canvas provided, use it as starting point (includes existing shapes for overlap detection)
if base_canvas is not None:
canvas = base_canvas.copy()
else:
canvas = np.zeros_like(region_mask, dtype=np.float32)
# Store placement metadata
placements = []
@@ -554,9 +559,9 @@ def place_shapes_in_region(
time_checks += time.time() - t0
# Calculate overlap (only within canvas bounds)
# Optimize: skip if no existing shapes in this region
# Check overlap with existing shapes (including base_canvas if provided)
t0 = time.time()
if placed_count > 0 and np.any(placement_region > 0.5):
if np.any(placement_region > 0.5):
overlap_area = np.sum((clipped_mask > 0.5) & (placement_region > 0.5))
overlap_ratio_actual = overlap_area / new_mask_area
@@ -571,8 +576,8 @@ def place_shapes_in_region(
consecutive_fails += 1
time_overlap += time.time() - t0
continue
elif debug_mode and placed_count == 0:
print(f" Overlap: SKIP (first shape)")
elif debug_mode:
print(f" Overlap: SKIP (no existing shapes in region)")
time_overlap += time.time() - t0
# Check if mostly within valid region (using clipped mask)