Nodes/opencv-comfyui/OpenCV countNonZero_1
ComfyUI Node

OpenCV countNonZero_1

CountNonZero_1 — the twin, and the mask-coverage trick worth stealing

By geroldmeisinger·Created about a year ago·Updated about a year ago· 35
OpenCV countNonZero_1
  • src
  • int

countNonZero_1 is the auto-generated twin of countNonZero_0 - identical call to cv2.countNonZero, identical single input and single int output. As with every _0/_1 pair in this pack, the split is just the two overloads from OpenCV's type definitions. Pick one. The interesting stuff is what you do with a bare pixel count, so let's spend this article there.

The coverage trick

A raw non-zero count is context-free - 40,000 non-zero pixels could be a huge region in a tiny image or a tiny region in a huge image. Normalize it and it becomes a real signal. Since you know the image dimensions (or can get them from another node), the coverage ratio is:

coverage = countNonZero(src) / (width × height)

That ratio turns this node into a decision input. In practice, the pattern that pays for itself across a batch:

  1. Run detection (SAM, a YOLO-based detailer, whatever) and get a mask.
  2. Feed the mask (single-channel nparray) into countNonZero_1.
  3. Branch on the result: 0 means the detector found nothing - skip the inpaint pass, log it, don't waste a diffusion call on an empty region. Small means the mask is a speck - maybe your threshold is wrong. Huge means the detector locked onto the whole frame - different failure, same signal.

That's the automation loop from the KB's detailing essay made explicit: the difference between a batch that quietly does nothing and one that tells you why. This node is a cheap, deterministic tripwire.

The two constraints that will bite you

  • Single channel only. countNonZero asserts on a multi-channel array. Grayscale or a proper mask is fine; RGB is not. Extract a channel first if you must count something in color.
  • Value semantics. "Non-zero" is not "opaque." A float mask normalized to 0..1 counts everything above zero, including 0.01s that look black. If you want "substantially opaque," threshold the mask first, then count.

Input / output / install

  • src - single-channel nparray. Output: int.
  • Install via ComfyUI Manager (search opencv-comfyui) or:
cd ComfyUI/custom_nodes
git clone https://github.com/geroldmeisinger/opencv-comfyui

Restart. Needs opencv-contrib-python, numpy, torch. No models.

Gotchas

The _1 suffix is meaningless here, same as everywhere. Batch-size-1 limit on the image bridge, channel assertion on color input, and - the fun one - the pack README warns that some nparray outputs aren't images at all. This node, refreshingly, returns an int, which is exactly the kind of output you can trust to be what it says.

Categoryimage/OpenCV

Inputs (1)

NameTypeDefaultDescription
srcNPARRAY

Outputs (1)

NameTypeDescription
intINT