-215
opencv
assertion_error
ai_generated
true
cv::error: (-215:断言失败) labels.size() == samples.rows 在函数 'cv::kmeans' 中
cv::error: (-215:Assertion failed) labels.size() == samples.rows in function 'cv::kmeans'
ID: opencv/kmeans-empty-labels
87%修复率
80%置信度
1证据数
2024-01-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 4.5.5 | active | — | — | — |
| 4.6.0 | active | — | — | — |
| 4.7.0 | active | — | — | — |
| 4.8.0 | active | — | — | — |
| 4.9.0 | active | — | — | — |
根因分析
传递给 kmeans 的 labels 数组大小与样本数量不一致,或者样本矩阵为空或行数为零。
English
The labels array provided to kmeans has a different size than the number of samples, or the samples matrix is empty or has zero rows.
官方文档
https://docs.opencv.org/4.x/d5/d38/group__core__cluster.html#ga9a34e1b8c9c3f5a0b8b0c0a0c0a0c0a0解决方案
-
让 OpenCV 自动分配 labels,传递 None:retval, labels, centers = cv2.kmeans(samples, K, None, criteria, attempts, flags)。避免手动尺寸问题。
-
如果需要手动提供 labels,确保形状:labels = np.zeros((samples.shape[0], 1), dtype=np.int32)。在调用 kmeans 前用 print(labels.shape) 验证。
-
将 samples 转换为 2D float32 矩阵:samples = np.float32(samples).reshape(-1, 2)(处理点集)。确保 samples.rows > 0。
无效尝试
常见但无效的做法:
-
30% 失败
Pre-allocating labels with np.zeros((1, N)) instead of np.zeros((N, 1), dtype=np.int32) — shape mismatch
-
25% 失败
Using np.random.randint to initialize labels without ensuring the dtype is np.int32
-
20% 失败
Assuming the error is about K value being too large and reducing K, which doesn't fix the label size mismatch