-215 opencv assertion_error ai_generated true

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

ID: opencv/kmeans-empty-labels

Also available as: JSON · Markdown · 中文
87%Fix Rate
80%Confidence
1Evidence
2024-01-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.5.5 active
4.6.0 active
4.7.0 active
4.8.0 active
4.9.0 active

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.

generic

中文

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

Official Documentation

https://docs.opencv.org/4.x/d5/d38/group__core__cluster.html#ga9a34e1b8c9c3f5a0b8b0c0a0c0a0c0a0

Workarounds

  1. 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.
    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. 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.
    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. 85% success Convert samples to a 2D float32 matrix: samples = np.float32(samples).reshape(-1, 2) if working with points. Ensure samples.rows > 0.
    Convert samples to a 2D float32 matrix: samples = np.float32(samples).reshape(-1, 2) if working with points. Ensure samples.rows > 0.

中文步骤

  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。

Dead Ends

Common approaches that don't work:

  1. 30% fail

    Pre-allocating labels with np.zeros((1, N)) instead of np.zeros((N, 1), dtype=np.int32) — shape mismatch

  2. 25% fail

    Using np.random.randint to initialize labels without ensuring the dtype is np.int32

  3. 20% fail

    Assuming the error is about K value being too large and reducing K, which doesn't fix the label size mismatch