有关使用cv2加载caffe模型的问题:
caffe模型的prototxt文件的第一个层为imagedata层,它的具体结构如下:
name: "AlexNet"
layers {
name: "data"
type: IMAGE_DATA
top: "data"
top: "label"
transform_param {
mirror: false
crop_size: 227
}
image_data_param {
source: "BS/databases06/pipa_features/ffaceregion_feat/train_shuffle.txt"
batch_size: 1
new_height: 227
new_width: 227
}
}
我想使用cv2加载该模型进行推理,已经有这个模型的prototx文件对应的caffemodel文件,可以成功加载。但根据imagedata层预处理图片,输入之后进行推理时仍然报错,请问应该怎么解决呢?代码为:
import cv2
import numpy as np
prototxt = 'model/alexnet_extraction.prototxt'
caffemodel = 'model/face.caffemodel'
imagelist = '1.jpg'
label_file = 'BS/databases06/pipa_features/ffaceregion_feat/train_shuffle.txt'
# 加载模型
net = cv2.dnn.readNetFromCaffe(prototxt, caffemodel)
# 读取图像和标签数据
with open(label_file, 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip().split(' ')
image_path = line[0]
label = int(line[1])
# 读取图像
image = cv2.imread('1.jpg')
# 将图像像素值归一化到 [0, 1] 范围并减去均值
image = image.astype(np.float32) / 255.0
mean = np.array([104, 117, 123], dtype=np.float32)
image -= mean
# 构建 blob 对象
blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size=(227, 227), mean=(104, 117, 123), swapRB=True, crop=False)
# 设置输入 blob 到网络中
net.setInput(blob)
# 运行模型进行推理
output = net.forward()
# 处理输出结果
# TODO: 根据实际需要进行后续处理
报错:
[ERROR:0@1.218] global net_impl.cpp:1164 cv::dnn::dnn4_v20221220::Net::Impl::getLayerShapesRecursively OPENCV/DNN: []:(_input): getMemoryShapes() throws exception. inputs=1 outputs=0/0 blobs=0
[ERROR:0@1.221] global net_impl.cpp:1167 cv::dnn::dnn4_v20221220::Net::Impl::getLayerShapesRecursively input[0] = [ 1 3 227 227 ]
[ERROR:0@1.221] global net_impl.cpp:1177 cv::dnn::dnn4_v20221220::Net::Impl::getLayerShapesRecursively Exception message: OpenCV(4.7.0) d:\a\opencv-python\opencv-python\opencv\modules\dnn\src\layer_internals.hpp:309: error: (-215:Assertion failed) inputs.size() == requiredOutputs in function 'cv::dnn::dnn4_v20221220::detail::DataLayer::getMemoryShapes'
Traceback (most recent call last):
File "E:/person_recognition/person_recogintion_personal_photo/main.py", line 36, in <module>
output = net.forward()
cv2.error: OpenCV(4.7.0) d:\a\opencv-python\opencv-python\opencv\modules\dnn\src\layer_internals.hpp:309: error: (-215:Assertion failed) inputs.size() == requiredOutputs in function 'cv::dnn::dnn4_v20221220::detail::DataLayer::getMemoryShapes'