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

ROS Melodic搭配Python3运行时出现OpenCV getConstBlob错误求助

解决OpenCV dnn的"Const input blob for weights not found"错误

我刚梳理了你的问题和代码,这个错误大概率和模型加载的方式或文件匹配性有关,以下是针对性的修复方案:

1. 把模型初始化移出回调函数(核心修复)

你现在每次收到图像回调时都会重新加载模型、配置和类别列表,这不仅会造成极高的资源浪费,还很容易引发加载异常——这很可能就是触发错误的主要原因。模型只需要初始化一次,而非每次回调都重复操作。

修改后的完整代码如下:

#! /usr/bin/env python3
import cv2 
import numpy as np
import rospy
import sensor_msgs.msg as sensor
import cv_bridge

rostopic = "/iris/camera/rgb/image_raw"
rosmsg = sensor.Image
configPath = "/home/irene/catkin_ws/src/beginner_tutorials/scripts/model/ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt"
modelPath = "/home/irene/catkin_ws/src/beginner_tutorials/scripts/model/frozen_inference_graph.pb"
classesPath = "/home/irene/catkin_ws/src/beginner_tutorials/scripts/model/coco.names"
bridge = cv_bridge.CvBridge()

# 全局变量存储模型和类别列表,仅初始化一次
net = None
classesList = []

def init_model():
    global net, classesList
    # 初始化检测模型
    net = cv2.dnn_DetectionModel(modelPath, configPath)
    net.setInputSize(320,320)
    net.setInputScale(1/127.5)
    net.setInputMean((127.5, 127.5, 127.5))
    net.setInputSwapRB(True)

    # 加载类别列表
    with open(classesPath, "r") as file:
        classesList = file.read().splitlines()

def im_callback(rosmsg):
    global net, classesList, bridge
    img = bridge.imgmsg_to_cv2(rosmsg, "bgr8")

    # 直接使用预初始化的模型进行检测
    classesLabelIDs, confidences, body_rects = net.detect(img, confThreshold = 0.6)

    body_rects = list(body_rects)
    confidences = list(np.array(confidences).reshape(1,-1)[0])
    confidences = list(map(float, confidences))

    bboxsIDx = cv2.dnn.NMSBoxes(body_rects, confidences, score_threshold=0.5, nms_threshold = 0.2) 

    if len(bboxsIDx) != 0:
        for _, bID in enumerate(bboxsIDx):
            classLabelID = np.squeeze(classesLabelIDs[np.squeeze(bID)])
            # 避免类别ID超出列表范围导致索引错误
            if classLabelID >= len(classesList):
                continue
            classLabel = classesList[classLabelID]

            if classLabel == "person":
                body_rect = body_rects[np.squeeze(bID)]
                classConfidence = confidences[np.squeeze(bID)]

                # 修复置信度格式化语法,确保正确显示小数
                display_text = "{} - {:.1f}".format(classLabel, classConfidence)

                x,y,w,h = body_rect
                        
                cv2.rectangle(img, (x,y), (x+w, y+h), (0,0,255), 1)
                cv2.line(img, (x,y), (x+ int(w*.3), y), (0,0,255), 3)
                cv2.line(img, (x,y), (x, y + int(h*.3)), (0,0,255), 3)
                cv2.line(img, (x+w,y), (x + w - int(w*.3), y), (0,0,255), 3)
                cv2.line(img, (x+w,y), (x+w, y + int(h*.3)), (0,0,255), 3)
                cv2.line(img, (x+w,y+h), (x + w - int(w*.3), y + h), (0,0,255), 3)
                cv2.line(img, (x+w,y+h), (x+w, y + h - int(h*.3)), (0,0,255), 3)
                cv2.line(img, (x,y+h), (x + int(w*.3), y+h), (0,0,255), 3)
                cv2.line(img, (x,y+h), (x, y + h -int(h*.3)), (0,0,255), 3)
                cv2.putText(img, display_text, (x, y-8), cv2.FONT_HERSHEY_COMPLEX, .4, (255,255,255), 1)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

def main():
    global rosmsg, rostopic
    
    rospy.init_node("webcam_node", anonymous=True)
    
    # 提前初始化模型
    init_model()

    rospy.Subscriber(rostopic, rosmsg, im_callback)
    rospy.spin()
    
    # 节点退出时清理窗口资源
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

2. 验证模型与配置文件的匹配性

如果修改后仍报错,需要确认:

  • ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt与frozen_inference_graph.pb属于同一版本的模型,两者必须严格匹配,否则会出现权重找不到的错误。
  • 检查模型文件是否完整未损坏,可以尝试重新下载对应版本的SSD MobileNet V3模型。

3. 检查OpenCV版本兼容性

你使用的OpenCV 4.4.0对SSD MobileNet V3的支持是没问题的,但如果问题依然存在,可以尝试升级OpenCV到4.5+版本,或者确认pip安装的OpenCV是否包含了TensorFlow相关的编译支持(通常默认是包含的)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:25:26