1.配置 protobuf 的 include 目录
2.配置 protobuf的库目录
3.拷贝 caffe 源码生成的 caffe.pb.cc 和caffe.pb.h 文件到 当前工程目录。 (注意 protobuf 库 跟caffe 版本要匹配)
4.读取代码
#include "caffe.pb.h"
#include <fstream>
int getParameterFormCaffeModel(string &model_path, vector<float> & param)
{
caffe::NetParameter netparam;
ifstream caffemodel(model_path, ifstream::in | ifstream::binary);
if (&caffemodel == NULL) {
cout << "The ptr of caffemodel is NULL" << endl;
return -1;
}
if (!caffemodel.is_open()) {
cout << "Can not open model" << endl;
return -1;
}
bool flag = netparam.ParseFromIstream(&caffemodel);
//该方法有caffemodel 文件大小限制 64M ,可以使用以下方法代替
//caffe::NetParameter netparam;
//caffe::ReadNetParamsFromBinaryFileOrDie(model_path, &netparam);
int layer_size = netparam.layer_size();
cout << "layer_size = " << layer_size << endl;
caffe::LayerParameter* layerparam = nullptr;
for (size_t i = 0; i < layer_size; i++)
{
layerparam = netparam.mutable_layer(i);
cout << "layer type:" << layerparam->type() << endl;
int n = layerparam->mutable_blobs()->size();
if (n) //表示 该层 参数的多少 有 w 有偏置 n=2 有w 没有偏置 n=1, 没有参数 n= 0
{
const BlobProto& blob = layerparam->blobs(0);
printf("%s layer: %s weight(%d)", layerparam->type().c_str(), layerparam->name().c_str(), blob.data_size());
for (size_t j = 0; j < blob.data_size(); j++)
{
float weight = blob.data()[j];
cout << "weight is:" << weight << endl;
param.push_back(weight);
}
const BlobProto& blob_b = layerparam->blobs(1);
printf("%s layer: %s weight(%d)", layerparam->type().c_str(), layerparam->name().c_str(), blob_b.data_size());
for (size_t j = 0; j < blob_b.data_size(); j++)
{
float bias = blob_b.data()[j];
cout << "bias is:" << bias << endl;
param.push_back(bias);
}
}
}
caffemodel.close();
google::protobuf::ShutdownProtobufLibrary();
return 0;
}