OpenCV countNonZero_0
CountNonZero_0 — the tiny node that answers 'how much mask is there?'
- src
- int
countNonZero_0 is the smallest, most boring-looking node in this pack and one of the most genuinely useful: it counts the number of non-zero pixels in an array and hands you the integer. That's it. cv2.countNonZero has one input (src) and one int output. No knobs, no tuning, no drama.
But boring is a feature. In an AI workflow, this is the node that answers the question you keep needing answered in automation: is there actually anything here? Specifically:
- Mask sanity checks. Feed it a mask (like the
MASKfrom a segmentation or detailer stage, once it's an nparray). Zero → the detector found nothing, and you can branch the graph instead of silently inpainting nothing. - Coverage metrics. Divide the count by total pixels and you've got "what fraction of the frame is foreground" - useful for batch QA over a hundred frames of a video, or deciding whether a generated image has enough detail region.
- Denoise checks. Count non-zero in a difference image (before/after) to see if a filter actually changed anything.
That's the through-line from the KB's masking-detection essay: automation is only as trustworthy as its signals, and a single integer saying "your mask is empty" is a very cheap signal. It's the difference between a batch run that quietly does nothing useful and one that tells you it did.
How it works
It walks the array and tallies pixels where the value isn't zero. Note the constraints baked into OpenCV: src must be single-channel. A grayscale image or a mask works; a 3-channel color array throws. If your mask comes out of ComfyUI as a MASK (float tensor), you'll route it through the pack's Image2Nparray-style conversion first, and remember the value range question - a mask normalized to 0..1 still counts every pixel above zero, so "non-zero" and "non-transparent" line up.
Inputs and output
src- one nparray, single channel.- Output:
int- the count. Wire it into a text/primitive display or use it to drive a switch that gates the rest of your workflow.
Install
Ships with opencv-comfyui. ComfyUI Manager → search opencv-comfyui → install, or:
cd ComfyUI/custom_nodes
git clone https://github.com/geroldmeisinger/opencv-comfyui
Restart. Dependencies: opencv-contrib-python, numpy, torch. No model downloads.
Common issues
CV_8UC1/ channel assertion → you fed it color or a multi-channel array. Extract a single channel first (extractChannel_0exists in this pack).- Batch > 1 →
Image2Nparrayonly takesbatch_size==1; useImageFromBatch. _0vs_1→ identical overloads; either works.
The pack is auto-generated and the author's "expect dragons" warning is fair - but this particular dragon is a friendly one. One input, one integer, and a genuinely useful answer.
Inputs (1)
| Name | Type | Default | Description |
|---|---|---|---|
| src | NPARRAY | — |
Outputs (1)
| Name | Type | Description |
|---|---|---|
| int | INT | — |