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

使用Python Flask实现目标检测时遇cv2.dnn_DetectionModel系统错误

Flask+OpenCV目标识别报错解决:SystemError: <class 'cv2.dnn_DetectionModel'> returned a result with an error set

我正在用Python Flask开发目标识别功能,实现代码如下:

c_Names = []
c_File = 'coco.names'
with open(c_File,'rt') as f:
    c_Names = f.read().rstrip('\n').split('\n')

confPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weiPath = 'frozen_inference_graph.pb'
net = cv2.dnn_DetectionModel(weiPath, confPath)
net.setInputSize(320,320)
net.setInputScale(1.0/ 127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)
packet,_ = self.client_socket.recvfrom(self.BUFF_SIZE)
data = base64.b64decode(packet,' /')
npdata = np.fromstring(data,dtype=np.uint8)
frame = cv2.imdecode(npdata,1)
# DO WHAT YOU WANT WITH TENSORFLOW / KERAS AND OPENCV
classIds, confs, bbox = net.detect(frame, confThreshold=0.5)
print(classIds, bbox)
if len(classIds) != 0:
    for classId, confidence,box in zip(classIds.flatten(),confs.flatten(),bbox):
        cv2.rectangle(frame,box,color=(0,255,0),thickness=2)
        cv2.putText(frame, c_Names[classId-1].upper(),(box[0]+10, box[1]+30),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0), 2)
        cv2.putText(frame, str(round(confidence*100,2)),(box[0]+200, box[1]+30),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0), 2)
        print("Name : " + c_Names[classId-1]+"\next : " + str(round(confidence*100,2) ))

ret, jpeg = cv2.imencode('.jpg', frame)
data = None #Data is information about classification in json form or dict
self.__send_frame(data if data != None else {"data": "data"})
return jpeg.tobytes()

运行时出现错误:SystemError: <class 'cv2.dnn_DetectionModel'> returned a result with an error set,即使重装frozen_inference_graph.pb文件问题仍未解决。报错栈如下:

Traceback (most recent call last):
  File "D:\Open_Cv\anaconda\Lib\site-packages\werkzeug\wsgi.py", line 462, in __next__
    return self._next()
  File "D:\Open_Cv\anaconda\Lib\site-packages\werkzeug\wrappers\response.py", line 50, in _iter_encoded    for item in iterable:
  File "C:\Opencv_Object_detect_platform-main\OBJweb\app_stable.py", line 16, in gen
    frame = camera.get_frame()
  File "C:\Opencv_Object_detect_platform-main\OBJweb\camera\camera.py", line 41, in get_frame
    net = cv2.dnn_DetectionModel(weiPath, confPath)
SystemError: <class 'cv2.dnn_DetectionModel'> returned a result with an error set
127.0.0.1 - - [08/Nov/2022 23:13:00] "GET /video_feed HTTP/1.1" 200 -

解决步骤

  • 检查模型文件路径
    相对路径可能导致文件找不到,先打印绝对路径确认:

    import os
    print("配置文件路径:", os.path.abspath(confPath))
    print("权重文件路径:", os.path.abspath(weiPath))
    

    如果路径错误,改为绝对路径,或者将模型文件放到脚本执行的目录下。

  • 验证模型文件完整性
    单独下载单个模型文件可能损坏或版本不匹配,重新下载完整的SSD MobileNet V3 Large模型包,确保pbtxt和pb文件是配套的。

  • 升级OpenCV版本
    cv2.dnn_DetectionModel在OpenCV 4.2及以上版本才稳定,执行以下命令查看版本:

    print(cv2.__version__)
    

    版本低于4.2的话,升级OpenCV:

    pip install --upgrade opencv-python opencv-contrib-python
    
  • 避免重复加载模型
    当前代码每次调用get_frame都重新初始化模型,不仅效率低还可能引发资源错误。将模型初始化移到类的__init__方法中:

    class Camera:
        def __init__(self):
            self.c_Names = []
            c_File = 'coco.names'
            with open(c_File,'rt') as f:
                self.c_Names = f.read().rstrip('\n').split('\n')
    
            confPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
            weiPath = 'frozen_inference_graph.pb'
            self.net = cv2.dnn_DetectionModel(weiPath, confPath)
            self.net.setInputSize(320,320)
            self.net.setInputScale(1.0/ 127.5)
            self.net.setInputMean((127.5, 127.5, 127.5))
            self.net.setInputSwapRB(True)
            # 其他初始化代码
    
        def get_frame(self):
            # 仅处理帧接收和检测逻辑
            packet,_ = self.client_socket.recvfrom(self.BUFF_SIZE)
            data = base64.b64decode(packet,' /')
            npdata = np.frombuffer(data,dtype=np.uint8)  # 替换弃用的fromstring
            frame = cv2.imdecode(npdata,1)
            classIds, confs, bbox = self.net.detect(frame, confThreshold=0.5)
            # 后续绘制框的代码...
    
  • 替换弃用的numpy方法
    np.fromstring已被弃用,改用np.frombuffer(data,dtype=np.uint8),避免数据解析异常。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:35:19