OpenCV Python YOLOv3目标识别代码报IndexError错误求助
问题:YOLOv3 + OpenCV 目标识别代码报错 IndexError: invalid index to scalar variable.
我正在用Python结合OpenCV做目标识别开发,基于YOLOv3模型写了如下代码:
import cv2 as cv import numpy as np img = cv.imread("photo1.jpg") print(img) img_width = img.shape[1] img_height = img.shape[0] img_blob = cv.dnn.blobFromImage(img,1/255,(416,416),swapRB = True) lables = ["person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "trafficlight", "firehydrant", "stopsign", "parkingmeter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sportsball", "kite", "baseballbat", "baseballglove", "skateboard", "surfboard", "tennisracket", "bottle", "wineglass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hotdog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed", "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cellphone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddybear", "hairdrier", "toothbrush"] colors = ["255,255,0","0,255,0","255,0,255","0,255,255","0,0,255"] colors = [np.array(color.split(",")).astype("int") for color in colors] colors = np.array(colors) colors = np.tile(colors,(20,1)) model = cv.dnn.readNetFromDarknet ("Model/yolov3.cfg","Model/yolov3.weights") layers = model.getLayerNames() output_layer = [layers[layer[0]-1] for layer in model.getUnconnectedOutLayers()] model.setInput(img_blob) detection_layers = model.forward(output_layer) ids_list = [] boxes_list = [] confidences_list = [] for detection_layer in detection_layers: for object_detection in detection_layer: scores = object_detection[5:] predicted_id = np.argmax(scores) confidence = scores[predicted_id] if confidence > 0.80: label = lables[predicted_id] bounding_box = object_detection[0:4] * np.array(img_width,img_height,img_width,img_height) (box_center_x, box_center_y,box_width,box_height) = bounding_box.astype("int") start_x = int(box_center_x - (box_width/2)) start_y = int(box_center_y - (box_height/2)) ids_list.append(predicted_id) confidences_list.append(float(confidence)) boxes_list.append([start_x,start_y,int(box_width),int(box_height)]) max_ids = cv.dnn.NMSBoxes(boxes_list,confidences_list,0.5,0.4) for max_id in max_ids: max_class_id = max_id[0] box = boxes_list[max_class_id] start_x = box[0] start_y = box[1] box_width = box[2] box_height = box[3] predicted_id = ids_list[max_class_id] label = lables[predicted_id] confidence = confidences_list[max_class_id] end_x = start_x + box_width end_y = start_y + box_height box_color = colors[predicted_id] box_color = [int(each)for each in box_color] cv.rectangle(img,(start_x,start_y),(end_x,end_y),box_color,2) cv.putText(img,label,(start_x,start_y-20),cv.FONT_HERSHEY_SIMPLEX,0.5,box_color,1) cv.imshow("Detection Screen", img)
运行代码时出现如下错误:
Traceback (most recent call last): File "C:\Users\bahac\OneDrive\Desktop\OpenCV\main.py", line 29, in <module> output_layer = [layers[layer[0]-1] for layer in model.getUnconnectedOutLayers()] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\bahac\OneDrive\Desktop\OpenCV\main.py", line 29, in <listcomp> output_layer = [layers[layer[0]-1] for layer in model.getUnconnectedOutLayers()] ~~~~~^^^ IndexError: invalid index to scalar variable.
解决方案
1. 核心错误原因
报错源于OpenCV版本差异导致的返回格式变化:
- 旧版OpenCV中,
model.getUnconnectedOutLayers()返回嵌套数组(如[[200], [227], [254]]) - 新版OpenCV中,该方法返回一维数组(如
[200, 227, 254])
原代码中layer[0]的写法只适配旧版,新版中layer是标量值,无法使用索引,因此触发IndexError。
2. 代码修复
将获取输出层的代码替换为兼容新旧版本的写法:
layers = model.getLayerNames() unconnected_layers = model.getUnconnectedOutLayers() # 统一处理为一维数组,再遍历取值 output_layer = [layers[i - 1] for i in unconnected_layers.flatten()]
3. 额外潜在问题修复
代码中计算bounding_box的行存在语法错误,缺少数组方括号,会触发TypeError,需修改:
# 原代码: bounding_box = object_detection[0:4] * np.array(img_width,img_height,img_width,img_height) # 修改为: bounding_box = object_detection[0:4] * np.array([img_width, img_height, img_width, img_height])
4. 验证
修改后重新运行代码,即可正常加载模型、获取输出层并执行目标检测。
内容的提问来源于stack exchange,提问作者İbrahim Ethem BAHACAN
相关产品推荐
相关产品推荐

