-215 opencv assertion_error ai_generated true

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

ID: opencv/contour-approximation-empty

Also available as: JSON · Markdown · 中文
85%Fix Rate
82%Confidence
1Evidence
2023-03-22First 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

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

generic

中文

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

Official Documentation

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

Workarounds

  1. 95% success Add a guard clause before calling approxPolyDP: if len(contour) == 0: continue. Example: for cnt in contours: if cnt.shape[0] < 3: continue; approx = cv2.approxPolyDP(cnt, epsilon, True)
    Add a guard clause before calling approxPolyDP: if len(contour) == 0: continue. Example: for cnt in contours: if cnt.shape[0] < 3: continue; approx = cv2.approxPolyDP(cnt, epsilon, True)
  2. 90% success Use cv2.contourArea to filter out contours with zero area before approximation: if cv2.contourArea(cnt) > 0: approx = cv2.approxPolyDP(cnt, 0.02 * cv2.arcLength(cnt, True), True)
    Use cv2.contourArea to filter out contours with zero area before approximation: if cv2.contourArea(cnt) > 0: approx = cv2.approxPolyDP(cnt, 0.02 * cv2.arcLength(cnt, True), True)
  3. 80% success Ensure findContours is called with the correct mode (e.g., RETR_TREE or RETR_LIST) and that the hierarchy is not corrupt; sometimes contour[0] can be empty if the image is all black
    Ensure findContours is called with the correct mode (e.g., RETR_TREE or RETR_LIST) and that the hierarchy is not corrupt; sometimes contour[0] can be empty if the image is all black

中文步骤

  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]可能为空

Dead Ends

Common approaches that don't work:

  1. 40% fail

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

  2. 30% fail

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

  3. 50% fail

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