简体   繁体   中英

How to write a caffe network to prototxt in C++ using google protobuf

I am using protobuf and caffe. I want to create a network using the caffe API in C++ and then write this to a protobuf file.

name: "AlexNet" input: "data" input_shape { dim: 1 dim: 3 dim: 227 dim: 227 }

I have a C++ program that is creating a NetParameter object param . My question is which function should I call to write this to a prototxt file.

I think I should be using WriteProtoToTextFile(const Message& proto, const char* filename) located here in src/caffe/util/io.cpp:

#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include <string>
#include "caffe.pb.h"
#include <iostream>
#include <caffe/caffe.hpp>

using namespace std;
using google::protobuf::Message;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::ZeroCopyOutputStream;

int main()
{
    caffe::NetParameter param;

    const char *filename = "/test.prototxt";

    int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        cout << "File not found: " << filename;

    FileOutputStream *output = new FileOutputStream(fd);

    param.set_name("AlexNet");

    //How to convert param to a proto message 

    // Call WriteProtoToTextFile(const Message& proto, const char* filename) ??

    delete outputput;

    close(fd);
    return 0;
}

Is this correct? This function take a proto message as the first argument. How do I convert the param object to a proto message?

After you've created the NetParameter, you can write it to a prototxt by using:

caffe::NetParameter param;

// ... param initialization ...

std::ofstream ofs; 
ofs.open ("test.prototxt", std::ofstream::out | std::ofstream::app);
ofs << param.Utf8DebugString(); 
ofs.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM