Comfy-Org / Comfy-Org/ComfyUI

negative x,y in ImageCompositeMasked produces a tensor error

Open
#5,477 0 comments 1 reaction 0 assignees View on GitHub
Potential Bug
Dominant language
Python
Stars
133k
Forks
15.7k
Avg merge
1d 10h
Merged PRs (30d)
153

Description

### Expected Behavior

negative x&y values should place the source rectangle off the left and top of the image, the same as the source rectangle can go off the right and bottom of the image already

### Actual Behavior

gets an error with mismatched tensor sizes, because the code uses `[left:right]` to slice destination, but if x is negative, left is negative, so `left` in slice notation is treated as an offset from the end rather than a negative position, so the length of the resulting tensor is nonsense.

### Steps to Reproduce

The code seems to be intended to support negative x & y, given the appearance of `min(0, x)` etc. in various places. That's why this is a bug report not a feature request.

A complete fix is as follows:
```
# calculate the bounds of the source that will be overlapping the destination
# this prevents the source trying to overwrite latent pixels that are out of bounds
# of the destination
> visible_width, visible_height = (destination.shape[3] - left, destination.shape[2] - top,)

> offset_x, offset_y = max(0,-x//multiplier),max(0,-y//multiplier)
> mask = mask[:, :, offset_y:visible_height, offset_x:visible_width]
inverse_mask = torch.ones_like(mask) - mask

> source_portion = mask * source[:, :, offset_y:visible_height, offset_x:visible_width]

> left,top = max(left,0),max(top,0)
destination_portion = inverse_mask * destination[:, :, top:bottom, left:right]

destination[:, :, top:bottom, left:right] = source_portion + destination_portion
return destination
```

In addition, the node description needs to be updated to allow negative x & y, for which there is an existing but closed pull request #2574 (although you can already use negative values if you make them inputs).

### Debug Logs

```powershell
.
```

### Other

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.