You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV中cv2.convexityDefects报(-215)断言错误的解决咨询

解决OpenCV convexityDefects的断言错误

错误信息

defects = cv2.convexityDefects(cnt, hull)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cv2.error: OpenCV(4.8.1) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\convhull.cpp:319: error: (-215:Assertion failed) npoints >= 0 in function 'cv::convexityDefects'

你尝试通过校验cnt和hull的有效性来解决问题,但代码里有个致命问题:你在判断分支后又直接执行了一次未加校验的cv2.convexityDefects(cnt, hull)调用,之前的校验逻辑完全没起到作用,这就是报错依然存在的原因。

另外还要注意,cv2.convexityDefects要求hull是凸包的索引数组,而非点坐标数组,也就是调用cv2.convexHull时必须传入returnPoints=False,否则也会触发断言错误。

正确处理代码

# 从轮廓列表中取目标轮廓(根据场景调整,比如取面积最大的轮廓)
cnt = None
if len(contours) > 0:
    cnt = max(contours, key=cv2.contourArea)

# 完整校验逻辑
if cnt is not None and len(cnt) >= 3:
    # 生成凸包索引数组,returnPoints=False是关键
    hull = cv2.convexHull(cnt, returnPoints=False)
    if hull is not None and len(hull) >= 3:
        defects = cv2.convexityDefects(cnt, hull)
        count_defects = 0
        # 此处可添加defects的后续处理逻辑
    else:
        print("凸包点数量不足,无法计算凸缺陷")
        defects = None
else:
    print("无效轮廓或轮廓点数量不足")
    defects = None

# 绘制轮廓前先确保轮廓列表非空
if len(contours) > 0:
    cv2.drawContours(thresh1, contours, -1, (0, 255, 0), 3)

关键注意点

  • 所有调用cv2.convexityDefects的地方必须前置校验,不能有遗漏
  • hull必须是凸包的索引数组,调用cv2.convexHull时一定要加returnPoints=False
  • 从cv2.findContours获取的contours是列表,要先判断列表非空,再选取单个轮廓传入后续函数

内容的提问来源于stack exchange,提问作者purva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:25:31