Crop by Margins (Mask)
Trim a mask by pixels without losing alignment with the image
- mask
- MASK
Masks are the silent partner in every inpainting and compositing workflow, and they have a bad habit of going out of sync with the image they describe. You crop the image to remove a border, the mask still spans the old dimensions, and suddenly your inpaint region is offset by exactly the pixels you removed. CropMaskByMargins is the mask half of the pack's margin-crop pair, built so that image and mask can be trimmed identically and stay glued together.
It takes a MASK and the same four margin inputs as its image sibling - left_px, top_px, right_px, bottom_px - plus snap_multiple, and returns the cropped MASK. The defaults are all zero, so it's a no-op until you tell it otherwise. Set the same four values you used on CropImageByMargins, wire both nodes in parallel, and every pixel you cut from the image is cut from the mask too, leaving the subject region's coordinates intact relative to the new canvas.
snap_multiple works exactly like the image version: after cropping it rounds the mask dimensions down to a multiple of the value (default 1, i.e. off). If you snapped your image crop to multiples of 8 or 16, snap the mask the same way or the two can disagree by a pixel or two at the edges - the whole point of this node is that they agree.
There's no magic here, and that's the selling point. Mask cropping is the kind of fiddly coordinate bookkeeping that people do by hand with ImageCrop + arithmetic once per workflow, then get wrong on the next batch. This makes it a repeating, wired step instead of a one-off manual calc.
Install
Same as every node in PortraitUtils - Manager → search "PortraitUtils", or:
cd ComfyUI/custom_nodes
git clone https://github.com/heyburns/PortraitUtils
Restart after. No extra dependencies.
Common issues
- Mask and image drift apart - you changed margins on one node and not the other. Give both the same inputs, or drive them from a shared config source so there's only one place to edit.
- Feathered or soft-edged masks look wrong after cropping - a margin crop is a hard slice; if your mask has a soft falloff near the edge you're cutting, you're removing part of the falloff. Trim generously or feather before you crop.
- Cropping a mask to zero area - if the margins exceed the mask dimensions you'll end up with nothing. The range goes to 16384, so it's on you to keep the numbers sane relative to your actual image size.
Use it right after any smart-crop or bbox-derived crop that shaves pixels, and your inpaint region will stay exactly where you drew it.
Inputs (6)
| Name | Type | Default | Description |
|---|---|---|---|
| mask | MASK | — | |
| left_px | INT | 00–16384 | — |
| top_px | INT | 00–16384 | — |
| right_px | INT | 00–16384 | — |
| bottom_px | INT | 00–16384 | — |
| snap_multiple | INT | 11–512 | — |
Outputs (1)
| Name | Type | Description |
|---|---|---|
| MASK | MASK | — |