OpenCV年龄检测脚本报错:ConvolutionLayerImpl::getMemoryShapes断言失败
问题描述
运行OpenCV年龄检测脚本时出现dnn模块报错,相关信息如下:
核心代码片段
# load the input image and construct an input blob for the image image = cv2.imread(args["image"]) (h, w) = image.shape[:2] blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0)) # pass the blob through the network and obtain the face detections print("[INFO] computing face detections...") print("First Blob: {}".format(blob.shape)) faceNet.setInput(blob) detections = faceNet.forward()
执行命令
python detect_age.py --image images/samuel_l_jackson.png --face face_detector --age age_detector
报错信息
[ERROR:0@0.157] global net_impl.cpp:1169 cv::dnn::dnn4_v20231225::Net::Impl::getLayerShapesRecursively OPENCV/DNN: [Convolution]:(conv1): getMemoryShapes() throws exception. inputs=1 outputs=0/1 blobs=0 [ERROR:0@0.163] global net_impl.cpp:1172 cv::dnn::dnn4_v20231225::Net::Impl::getLayerShapesRecursively input[0] = [ 1 3 224 224 ] [ERROR:0@0.168] global net_impl.cpp:1182 cv::dnn::dnn4_v20231225::Net::Impl::getLayerShapesRecursively Exception message: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\layers\convolution_layer.cpp:368: error: (-215:Assertion failed) !blobs.empty() || inputs.size() > 1 in function 'cv::dnn::ConvolutionLayerImpl::getMemoryShapes'
已确认输入图片、人脸/年龄检测模型的路径正确且可访问。
错误分析与解决方案
错误原因
报错指向卷积层缺少必要的权重blob,本质是年龄检测模型未正确加载——要么权重文件缺失,要么加载代码路径错误,导致OpenCV无法读取模型的卷积层权重数据。
解决步骤
- 检查模型文件完整性:确认
age_detector目录下同时存在deploy.prototxt(模型结构文件)和age_net.caffemodel(权重文件),两个文件缺一不可,且文件未损坏。 - 修正模型加载代码:确保加载年龄模型时同时指定结构文件和权重文件,推荐用
os.path.join避免路径拼接错误:import os # 构造完整模型路径 age_prototxt_path = os.path.join(args["age"], "deploy.prototxt") age_model_path = os.path.join(args["age"], "age_net.caffemodel") # 加载模型 ageNet = cv2.dnn.readNet(age_prototxt_path, age_model_path) - 重新下载模型:如果文件存在但仍报错,大概率是模型文件下载不完整,重新下载完整的年龄检测模型包。
- 适配OpenCV版本:OpenCV 4.x对模型加载的路径解析更严格,避免使用相对路径的模糊写法,确保路径指向准确的文件位置。
内容的提问来源于stack exchange,提问作者Pablo Palacios
相关产品推荐
相关产品推荐

