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

OpenCV(4.5.4)调用forward函数报(-5:Bad argument)错误如何修复

报错原因
  • 核心为net.forward()参数类型不匹配:OpenCV 4.x版本中net.getUnconnectedOutLayers()返回的是numpy数组格式的层索引,而forward()方法要求传入输出层的字符串名称列表,直接传入索引数组就会触发类型错误。
  • 原代码还存在变量覆盖的逻辑错误:循环中直接把预先定义的class_ids、confidences列表变量赋值为单个数值,后续执行append操作时也会报错。
修复方案

只需修改两处代码即可解决问题:

  1. 输出层获取逻辑调整,适配OpenCV 4.x的API规则
# 原代码这两行替换为下方内容
# output_layers_names = net.getUnconnectedOutLayers() 
# layerOutputs = net.forward(output_layers_names) 

# 获取所有层名称
layer_names = net.getLayerNames()
# 根据输出层索引取对应的层名称(注意返回的索引是1起始,要减1匹配列表的0起始下标)
output_layers_names = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
layerOutputs = net.forward(output_layers_names)
  1. 修复循环内的变量重名问题,避免覆盖列表变量
for output in layerOutputs:
    for detection in output:
        scores = detection[5:] #从第6个元素开始为各类别置信度
        class_id = np.argmax(scores) #取置信度最高的类别id
        confidence = scores[class_id] 
        if confidence > 0.5: 
            center_x = int(detection[0]*width)
            center_y = int (detection[1]*height)
            w = int(detection[2]*width)
            h = int(detection[3]*height)

            x = int(center_x - w/2) 
            y = int(center_y - h/2)

            boxes.append([x,y,w,h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:04