OpenCV kmeans_1
The duplicate clustering node, strings and all
- data
- bestLabels
- centers
- float
- nparray_1
- nparray_2
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 fromnparray_1.criteria- STRING, aTermCriteriaas a Python literal, e.g.(3, 10, 1.0).attempts- INT, restarts with different initializations.flags- INT:0random centers,1use initial labels,2k-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.
Inputs (7)
| Name | Type | Default | Description |
|---|---|---|---|
| data | NPARRAY | — | |
| K | INT | — | |
| bestLabels | NPARRAY | — | |
| criteria | STRING | — | |
| attempts | INT | — | |
| flags | INT | — | |
| centersopt | NPARRAY | — |
Outputs (3)
| Name | Type | Description |
|---|---|---|
| float | FLOAT | — |
| nparray_1 | NPARRAY | — |
| nparray_2 | NPARRAY | — |