OpenCV(4.5.4)调用forward函数报(-5:Bad argument)错误如何修复
报错原因
- 核心为
net.forward()参数类型不匹配:OpenCV 4.x版本中net.getUnconnectedOutLayers()返回的是numpy数组格式的层索引,而forward()方法要求传入输出层的字符串名称列表,直接传入索引数组就会触发类型错误。 - 原代码还存在变量覆盖的逻辑错误:循环中直接把预先定义的
class_ids、confidences列表变量赋值为单个数值,后续执行append操作时也会报错。
修复方案
只需修改两处代码即可解决问题:
- 输出层获取逻辑调整,适配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)
- 修复循环内的变量重名问题,避免覆盖列表变量
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
相关产品推荐
相关产品推荐

