运行YOLOv3代码遇cv2.error: Unknown C++ exception报错求助
问题描述
运行基于OpenCV的YOLOv3目标检测代码时,执行layerOutputs = net.forward(output_layers_names)语句触发错误:cv2.error: Unknown C++ exception from OpenCV code,更换多个OpenCV版本后问题依旧。
代码如下:
import cv2 import numpy as np net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg') classes = [] with open("coco.txt", "r") as f: classes = f.read().splitlines() cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_PLAIN colors = np.random.uniform(0, 255, size=(100, 3)) while True: _, img = cap.read() height, width, _ = img.shape blob = cv2.dnn.blobFromImage(img, 1/255, (416, 416), (0,0,0), swapRB=True, crop=False) net.setInput(blob) output_layers_names = net.getUnconnectedOutLayersNames() layerOutputs = net.forward(output_layers_names) boxes = [] confidences = [] class_ids = [] for output in layerOutputs: for detection in output: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.3: 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) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.2, 0.4) if len(indexes)>0: for i in indexes.flatten(): x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) confidence = str(round(confidences[i],2)) color = colors[i] cv2.rectangle(img, (x,y), (x+w, y+h), color, 2) cv2.putText(img, label + " " + confidence, (x, y+20), font, 2, (255,255,255), 2) cv2.imshow('Image', img) key = cv2.waitKey(1) if key==27: break cap.release() cv2.destroyAllWindows()
问题截图:
解决方向
- 检查模型文件完整性:确认
yolov3.weights、yolov3.cfg、coco.txt路径正确且未损坏。weights文件约240MB,若下载中断会导致文件残缺,可重新下载官方版本并验证MD5值。 - 验证摄像头输入:
cv2.VideoCapture(0)调用默认摄像头,若设备不存在或被占用,img可能为空,引发后续blob处理异常。可添加判断逻辑:_, img = cap.read() if img is None: print("无法读取摄像头画面") continue - 指定DNN后端与目标设备:OpenCV的dnn模块支持多后端,强制指定可解决兼容性问题:
net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg') # 有GPU时优先用CUDA加速 net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) # 无GPU则用CPU后端 # net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) # net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) - 核对输入尺寸配置:YOLOv3输入尺寸需为32的倍数(如416、608),确保
blobFromImage的(416,416)与cfg文件中width、height参数完全一致。 - 排查OpenCV编译问题:若用源码编译OpenCV,需确认编译时开启了DNN模块及对应后端支持;用pip安装时,优先选择官方预编译包,避免第三方编译版本的兼容性bug。
内容的提问来源于stack exchange,提问作者Bagas30h
相关产品推荐
相关产品推荐

