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

运行OpenCV YOLO检测代码触发数组真值歧义ValueError报错如何解决

报错原因
  • 核心错误是嵌套循环逻辑写反:你第一层循环遍历了outputs里的每个output,但第二层循环仍然遍历了整个outputs而非当前的output,导致你拿到的det不是单条检测结果,而是一整个批次的二维数组。后续推导出来的confidence也是多维数组,Python没办法直接判断多维数组的布尔值,就触发了该报错。
  • 如果循环逻辑修改后仍出现该报错,才需要考虑用numpy的any()/all()方法明确判断逻辑:只要有一个元素满足条件用.any(),所有元素都满足条件才用.all()。
修复后的代码
def findGun(outputs,img):
    ht , wt , ct = img.shape
    bbox = []
    classIDs = []
    confs = []
    for output in outputs:
        # 这里修改为遍历当前output里的det,而非整个outputs
        for det in output:
            scores = det[5:]
            classID = np.argmax(scores)
            confidence = scores[classID]
            if confidence > confThreshold:
                w,h = int(det[2]*wt),int(det[3]*ht)
                x , y = int((det[0]*wt) - w/2),int((det[1]*ht) - h/2)
                bbox.append([x,y,w,h])
                classIDs.append(classID)
                confs.append(float(confidence))
验证方法

修改后可以在confidence = scores[classID]后面加一行打印代码print(confidence.ndim),如果输出是0,说明是单值,判断语句可以正常运行,不会再触发报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:18:01