Nodes/ComfyUI-YCNodes/Mask Top-N Filter
ComfyUI Node

Mask Top-N Filter

Keep the N biggest blobs in a mask, delete the rest

By yichengup·Created 2 years ago·Updated 4 months ago· 48
Mask Top-N Filter
  • mask
  • filtered_mask
keep_top_n2

A mask comes back with the thing you want plus a bunch of noise blobs you don't. Mask Top-N Filter keeps the keep_top_n largest connected regions by area and wipes everything else. Default is 2, which is a good prompt-free way to say "the two subjects, nothing else."

This is the blunt instrument of the mask-filter family, and blunt is fine - it's the tool you reach for when you don't care about shape or solidity, only size. Combined with a min_area-style floor (which this node doesn't have, see below), it's the standard "clean up my mask" pass.

How it works

It binarizes the mask (anything above 0.5 becomes 1, everything below becomes 0 - the soft edges are gone after this), runs cv2.connectedComponents, sorts the components by pixel count descending, and redraws only the top N onto a blank mask. If the mask already has N or fewer components, it returns the binarized mask as-is.

The input that matters

mask (MASK) and keep_top_n (1–100, default 2). The output is filtered_mask, a hard-edged mask of the same dimensions.

The practical gotcha is that there's no area floor. If your noise consists of large fragments - a big stray region that isn't connected to anything - it can outrank a legitimately smaller object and claim a top-N slot. For that case you want the sibling Filter Mask By Solidity, which ranks by how "whole" a blob is, or MaskContourFill_YC, whose min_area drops small speckles before you even get to ranking.

Install

Part of ComfyUI-YCNodes. ComfyUI Manager → search "ComfyUI-YCNodes", or:

cd ComfyUI/custom_nodes
git clone https://github.com/yichengup/ComfyUI-YCNodes

Restart ComfyUI. Standard deps, no downloads. Under "YCNode/Mask".

Gotchas

Two things, both in the code and both easy to miss. The threshold at 0.5 means a feathered mask loses its softness - if you were planning to feed the result into a conditioning node that wanted a soft boundary, blur afterward or this will surprise you with hard edges. And it takes the first frame if you feed a batch; process one mask at a time or per-frame. None of this is fatal, but it's the difference between "this node works" and "this node works the way I assumed."

CategoryYCNode/Mask

Inputs (2)

NameTypeDefaultDescription
maskMASK
keep_top_nINT21–100

Outputs (1)

NameTypeDescription
filtered_maskMASK