# cv::error: (-215：断言失败) labels.size() == samples.rows 在函数 'cv::kmeans' 中

- **ID:** `opencv/kmeans-empty-labels`
- **领域:** opencv
- **类别:** assertion_error
- **错误码:** `-215`
- **验证级别:** ai_generated
- **修复率:** 87%

## 根因

传递给 kmeans 的 labels 数组大小与样本数量不一致，或者样本矩阵为空或行数为零。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 4.5.5 | active | — | — |
| 4.6.0 | active | — | — |
| 4.7.0 | active | — | — |
| 4.8.0 | active | — | — |
| 4.9.0 | active | — | — |

## 解决方案

1. ```
   让 OpenCV 自动分配 labels，传递 None：retval, labels, centers = cv2.kmeans(samples, K, None, criteria, attempts, flags)。避免手动尺寸问题。
   ```
2. ```
   如果需要手动提供 labels，确保形状：labels = np.zeros((samples.shape[0], 1), dtype=np.int32)。在调用 kmeans 前用 print(labels.shape) 验证。
   ```
3. ```
   将 samples 转换为 2D float32 矩阵：samples = np.float32(samples).reshape(-1, 2)（处理点集）。确保 samples.rows > 0。
   ```

## 无效尝试

- **** — Pre-allocating labels with np.zeros((1, N)) instead of np.zeros((N, 1), dtype=np.int32) — shape mismatch (30% 失败率)
- **** — Using np.random.randint to initialize labels without ensuring the dtype is np.int32 (25% 失败率)
- **** — Assuming the error is about K value being too large and reducing K, which doesn't fix the label size mismatch (20% 失败率)
