OpenCV报错cv2.error: Unknown C++ exception from OpenCV code求助
问题
在VSCode中使用Python 3.10、Windows 10 Education系统编写目标检测代码时,执行classIds, confs, bbox = net.detect(img,confThreshold=thres)一行触发错误:cv2.error: Unknown C++ exception from OpenCV code,每次调用detect模型都会出现这个错误,疑问是否与操作系统有关?
完整代码如下:
import cv2 import numpy as np thres = 0.45 # Threshold to detect object nms_threshold = 0.2 cap = cv2.VideoCapture(0) # cap.set(3,1280) # cap.set(4,720) # cap.set(10,150) classNames = [] classFile = "ModelosDNN/classes.txt" with open(classFile,"rt") as f: classNames = f.read().rstrip("n").split("n") #print(classNames) configPath = "ModelosDNN/yolov4-tiny.cfg" weightsPath = "ModelosDNN/yolov4-tiny.weights" net = cv2.dnn_DetectionModel(weightsPath,configPath) net.setInputSize(320,320) net.setInputScale(1.0/ 127.5) net.setInputMean((127.5, 127.5, 127.5)) net.setInputSwapRB(True) while True: success,img = cap.read() classIds, confs, bbox = net.detect(img,confThreshold=thres) bbox = list(bbox) confs = list(np.array(confs).reshape(1,-1)[0]) confs = list(map(float,confs)) #print(type(confs[0])) #print(confs) indices = cv2.dnn.NMSBoxes(bbox,confs,thres,nms_threshold) #print(indices) for i in indices: i = i[0] box = bbox[i] x,y,w,h = box[0],box[1],box[2],box[3] cv2.rectangle(img, (x,y),(x+w,h+y), color=(0, 255, 0), thickness=2) cv2.putText(img,classNames[classIds[i][0]-1].upper(),(box[0]+10,box[1]+30), cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2) cv2.imshow("Output",img) cv2.waitKey(1)
分析与解决
操作系统并非直接诱因:Windows 10 Education本身不会导致OpenCV的dnn模块抛出未知C++异常,问题大概率出在代码细节、模型文件、OpenCV版本或环境配置上。
修复代码中的明显错误:
- 类名读取逻辑错误:代码里的
rstrip("n")和split("n")中的"n"应为"\n",否则无法正确按行分割类名文件,可能触发底层异常。修正后:classNames = f.read().rstrip("\n").split("\n") - 添加摄像头帧读取校验:当前代码未判断
success是否为True,若摄像头初始化失败或无法读取帧,无效的img传入net.detect()会引发异常。添加判断:success, img = cap.read() if not success: break # 或打印错误信息后退出循环
- 类名读取逻辑错误:代码里的
检查模型文件与兼容性:
- 确认
yolov4-tiny.cfg和yolov4-tiny.weights文件完整无损坏,且与当前OpenCV版本兼容(部分旧版本OpenCV对YOLOv4-tiny的支持存在bug)。 - 尝试替换为官方下载的YOLOv4-tiny模型文件。
- 确认
调整OpenCV环境:
- 卸载当前opencv-python,重新安装稳定版本,如
pip install opencv-python==4.5.5.62。 - 避免同时安装opencv-python和opencv-contrib-python,防止环境冲突。
- 卸载当前opencv-python,重新安装稳定版本,如
其他排查方向:
- 确认VSCode有Windows 10摄像头访问权限,可在系统隐私设置中开启。
- 用本地图片替换摄像头输入测试,如
img = cv2.imread("test.jpg"),若仍报错,说明问题出在模型或OpenCV配置,而非摄像头。
内容的提问来源于stack exchange,提问作者Gabriel Krummenauer de Morais
相关产品推荐
相关产品推荐

