-215 opencv assertion_error ai_generated true

cv::error: (-215:断言失败) count >= 0 在函数 'cv::approxPolyDP' 中

cv::error: (-215:Assertion failed) count >= 0 in function 'cv::approxPolyDP'

ID: opencv/contour-approximation-empty

其他格式: JSON · Markdown 中文 · English
85%修复率
82%置信度
1证据数
2023-03-22首次发现

版本兼容性

版本状态引入弃用备注
4.5.5 active — — —
4.6.0 active — — —
4.7.0 active — — —
4.8.0 active — — —
4.9.0 active — — —

根因分析

approxPolyDP 接收到空或无效的轮廓(零个点),因为输入轮廓未被正确提取或被过滤掉。

English

approxPolyDP received an empty or invalid contour (zero points) because the input contour was not properly extracted or was filtered out.

generic

官方文档

https://docs.opencv.org/4.x/dd/d49/tutorial_py_contour_features.html

解决方案

  1. 在调用 approxPolyDP 前添加守卫检查:if len(contour) == 0: continue。示例:for cnt in contours: if cnt.shape[0] < 3: continue; approx = cv2.approxPolyDP(cnt, epsilon, True)
  2. 使用 cv2.contourArea 过滤面积为零的轮廓:if cv2.contourArea(cnt) > 0: approx = cv2.approxPolyDP(cnt, 0.02 * cv2.arcLength(cnt, True), True)
  3. 确保 findContours 使用正确的模式(如 RETR_TREE 或 RETR_LIST),并且层次结构未损坏;如果图像全黑,轮廓[0]可能为空

无效尝试

常见但无效的做法:

  1. 40% 失败

    Increasing the epsilon parameter to make the approximation less strict, which only masks the issue but doesn't fix empty contours

  2. 30% 失败

    Re-running findContours with different retrieval modes (e.g., RETR_EXTERNAL) without checking if contours exist

  3. 50% 失败

    Assuming the contour is always valid and skipping the empty check entirely