# cv::error: (-215:断言失败) centers.cols == data.cols 在函数 'cv::kmeans' 中

- **ID:** `opencv/kmeans-initial-centers-mismatch`
- **领域:** opencv
- **类别:** assertion_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

当向 kmeans 提供初始聚类中心时，中心矩阵的列数（特征数）与数据矩阵的列数不匹配。

## 版本兼容性

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

## 解决方案

1. ```
   Ensure the centers matrix has the same number of columns as the data matrix. For example, if data is a 100x3 matrix (100 samples, 3 features), centers should be Kx3. Initialize centers as: cv::Mat centers(K, data.cols, CV_32FC1); for (int i = 0; i < K; i++) { data.row(rand() % data.rows).copyTo(centers.row(i)); } Then call kmeans(data, K, labels, criteria, attempts, KMEANS_USE_INITIAL_LABELS, centers);
   ```
2. ```
   Convert data to CV_32F type if it is CV_64F: data.convertTo(data, CV_32F); and ensure centers is also CV_32F.
   ```
3. ```
   Use KMEANS_RANDOM_CENTERS flag instead of providing initial centers: kmeans(data, K, labels, criteria, attempts, KMEANS_RANDOM_CENTERS);
   ```

## 无效尝试

- **Transpose the data matrix using data.t()** — kmeans expects data as rows of samples (each row is a sample). Transposing changes the shape incorrectly, leading to centers.cols != data.cols in a different way. (85% 失败率)
- **Set the number of clusters K to a smaller value** — The error is about feature dimension mismatch, not the number of clusters. Changing K doesn't affect the column count. (95% 失败率)
- **Use cv::Mat::reshape to flatten the data to 1 column** — Flattening to 1 column changes the feature space entirely, causing centers.cols (still original features) to mismatch. (90% 失败率)
