Nodes/opencv-comfyui/OpenCV kmeans_1
ComfyUI Node

OpenCV kmeans_1

The duplicate clustering node, strings and all

By geroldmeisinger·Created about a year ago·Updated about a year ago· 35
OpenCV kmeans_1
  • data
  • bestLabels
  • centers
  • float
  • nparray_1
  • nparray_2
K
criteria
attempts
flags

OpenCV kmeans_1 is the overload twin of kmeans_0 - same cv2.kmeans call, same six required inputs, same three outputs. cv2.kmeans is listed twice in OpenCV's type stubs (MatLike/UMat), the auto-generator numbered them, and they behave identically. Everything mechanical is in the kmeans_0 article; this page hits the parts people actually stumble on.

What it does

Runs k-means clustering: given (N, dims) float32 samples, it groups them into K clusters and returns cluster labels, cluster centers, and a compactness score. The use case most ComfyUI users care about is color quantization - K cluster centers in RGB space are a K-color palette, which is exactly the palette-reduction step the KB's post-processing essay describes for pixel-art and limited-palette looks.

Inputs and outputs

  • data - NPARRAY, (N, dims) float32. For images: pixels reshaped to (N, 3).
  • K - INT, number of clusters.
  • bestLabels - NPARRAY, required input though it's really an output (generator quirk - the stub types it non-optional). Connect a placeholder; read the real result from nparray_1.
  • criteria - STRING, a TermCriteria as a Python literal, e.g. (3, 10, 1.0).
  • attempts - INT, restarts with different initializations.
  • flags - INT: 0 random centers, 1 use initial labels, 2 k-means++.
  • centers - optional out-parameter.
  • Outputs: float (compactness), nparray_1 (labels), nparray_2 (centers).

Installing

cd ComfyUI/custom_nodes
git clone https://github.com/geroldmeisinger/opencv-comfyui
cd opencv-comfyui
pip install -r requirements.txt

or ComfyUI Manager → "opencv-comfyui". No model downloads; deps are opencv-contrib-python, numpy, torch.

Gotchas

The criteria string is the classic invalid syntax (<unknown>, line 0) trap - it's parsed with ast.literal_eval, so it must be a valid Python literal like (3, 10, 1.0). data must be 2D float32; an image-shaped array throws an assertion. And bestLabels being a required input is the weirdest quirk in this whole pack - you have to supply an array that the function overwrites, because the generator only makes out-parameters optional when the stub types them | None. kmeans_1 adds nothing over kmeans_0; use whichever a workflow references.

Categoryimage/OpenCV

Inputs (7)

NameTypeDefaultDescription
dataNPARRAY
KINT
bestLabelsNPARRAY
criteriaSTRING
attemptsINT
flagsINT
centersoptNPARRAY

Outputs (3)

NameTypeDescription
floatFLOAT
nparray_1NPARRAY
nparray_2NPARRAY