如何解码caffemodel中的权重并转发图像?

How to decode the weights in caffemodel and forward an image?

大家。

我有一个 prototxt 文件、caffemodel 文件和一张图片。 我想提取caffemodel文件中的权重并转发图像 获取关于 prototxt 文件的输出向量(例如用于分类的 1000 维向量)。

我知道$(CAFFE_ROOT)/src/caffe/proto/caffe.proto中的文件定义 protobuf消息结构,caffemodel文件根据序列化 这些结构。

我也研究过如何对消息结构进行编码。 例如,如果我有一个消息结构:

message Test2 {
    required string b = 2;
}

并将b的值设置为"testing",然后编码后, 我会得到“12 07 74 65 73 74 69 6e 67”

但我仍然不知道如何使用caffemodel 文件中的权重转发图像,仅使用C 和C++ 编程。 我想解码 caffemodel 文件并通过我的 C 和转发图像 C++ 代码,而不是使用 Caffe 或 Protobuf 提供的 API。

下一步我有什么想法吗? 例如,研究其他材料或其他。 非常感谢。

Caffe的代码非常清晰易读。开始研究$CAFFE_DIR/tools/caffe.cpp文件,具体是int test()函数。

重要行:

Net<float> caffe_net(FLAGS_model, caffe::TEST);
caffe_net.CopyTrainedLayersFrom(FLAGS_weights);
const vector<Blob<float>*>& result = caffe_net.Forward(&iter_loss);

$CAFFE_DIR/examples/cpp_classification/classification.cpp也有有用的代码。

vector<float> Classifier::Predict(const cv::Mat& img) {
    Blob<float>* input_layer = net_->input_blobs()[0];
    input_layer->Reshape(1, num_channels_,
            input_geometry_.height, input_geometry_.width);
    /* Forward dimension change to all layers. */
    net_->Reshape();

    vector<cv::Mat> input_channels;
    WrapInputLayer(&input_channels);

    Preprocess(img, &input_channels);

    net_->Forward();

    /* Copy the output layer to a vector */
    Blob<float>* output_layer = net_->output_blobs()[0];
    const float* begin = output_layer->cpu_data();
    const float* end = begin + output_layer->channels();
    return vector<float>(begin, end);
}