-215 opencv assertion_error ai_generated true

cv::error: (-215:断言失败) hierarchy.checkVector(3, 4) >= 0 在函数 'drawContours' 中

cv::error: (-215:Assertion failed) hierarchy.checkVector(3, 4) >= 0 in function 'drawContours'

ID: opencv/contour-not-found-in-hierarchy

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

版本兼容性

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

根因分析

在调用 findContours 后使用 RETR_TREE 或 RETR_CCOMP 模式调用 drawContours 时,轮廓层次向量为空或格式错误。

English

Contour hierarchy vector is empty or malformed when calling drawContours with RETR_TREE or RETR_CCOMP mode after findContours.

generic

官方文档

https://docs.opencv.org/4.x/d3/dc0/group__imgproc__shape.html#ga17ed9f5d79ae97bd4c7cf18403e1689a

解决方案

  1. Check if hierarchy is not None and has at least 4 elements before calling drawContours. Example: `if hierarchy is not None and len(hierarchy) > 0: cv2.drawContours(img, contours, -1, (0,255,0), 2)`
  2. Use RETR_LIST mode which returns no hierarchy, then draw without hierarchy parameter.
  3. Ensure contours list is non-empty before drawing: `if len(contours) > 0: cv2.drawContours(img, contours, -1, (0,255,0), 2, hierarchy=hierarchy)`

无效尝试

常见但无效的做法:

  1. 60% 失败

    Setting RETR_EXTERNAL only retrieves outer contours, but hierarchy is still required for drawing with RETR_TREE. The error persists because hierarchy is empty.

  2. 50% 失败

    Changing CHAIN_APPROX_NONE to other approximations doesn't fix hierarchy emptiness; it only changes point storage.

  3. 40% 失败

    Increasing threshold values may reduce contour count but doesn't guarantee hierarchy is non-empty.