# cv::error: (-215:Assertion failed) labels.size() == samples.rows in function 'cv::kmeans'

- **ID:** `opencv/kmeans-empty-labels`
- **Domain:** opencv
- **Category:** assertion_error
- **Error Code:** `-215`
- **Verification:** ai_generated
- **Fix Rate:** 87%

## Root Cause

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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 4.5.5 | active | — | — |
| 4.6.0 | active | — | — |
| 4.7.0 | active | — | — |
| 4.8.0 | active | — | — |
| 4.9.0 | active | — | — |

## Workarounds

1. **Let OpenCV allocate labels automatically by passing None: retval, labels, centers = cv2.kmeans(samples, K, None, criteria, attempts, flags). This avoids manual size issues.** (95% success)
   ```
   Let OpenCV allocate labels automatically by passing None: retval, labels, centers = cv2.kmeans(samples, K, None, criteria, attempts, flags). This avoids manual size issues.
   ```
2. **If manually providing labels, ensure shape: labels = np.zeros((samples.shape[0], 1), dtype=np.int32). Verify with print(labels.shape) before calling kmeans.** (90% success)
   ```
   If manually providing labels, ensure shape: labels = np.zeros((samples.shape[0], 1), dtype=np.int32). Verify with print(labels.shape) before calling kmeans.
   ```
3. **Convert samples to a 2D float32 matrix: samples = np.float32(samples).reshape(-1, 2) if working with points. Ensure samples.rows > 0.** (85% success)
   ```
   Convert samples to a 2D float32 matrix: samples = np.float32(samples).reshape(-1, 2) if working with points. Ensure samples.rows > 0.
   ```

## Dead Ends

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