caffe 中 protobuffer

来源:互联网 发布:伊犁知乎 编辑:程序博客网 时间:2024/06/06 02:02



转自:http://blog.csdn.net/caoeryingzi/article/details/22755571


caffe 里面贯穿始终的文件格式就是protobuffer和glog了,不得不佩服,google确实很牛啊,恭维的话不说,熟悉一下protobuffer吧。其中官方文档什么的,网上搜吧,还有一系列别人在ubuntu和windows下的使用。把caffe中的代码粘贴下来如下:


//读取保存为text文档的proto文件,读进来,并通过Parse解析。

下面这些函数在 D:\Caffe_windows\Caffe For Windows VS2012 完整版,带第三方库\src\caffe\util\io.cpp文件夹下


D:\Caffe_windows\Caffe For Windows VS2012 完整版,带第三方库\include\caffe\solver.hpp文件夹下


void ReadProtoFromTextFile(const char* filename,  ::google::protobuf::Message* proto) {   int fd = open(filename, O_RDONLY);   CHECK_NE(fd, -1) << "File not found: " << filename;   FileInputStream* input = new FileInputStream(fd);   CHECK(google::protobuf::TextFormat::Parse(input, proto));   delete input;   close(fd); }


 //把proto写到文件,文件是text格式的。

void WriteProtoToTextFile(const Message& proto, const char* filename) {   int fd = open(filename, O_WRONLY);   FileOutputStream* output = new FileOutputStream(fd);   CHECK(google::protobuf::TextFormat::Print(proto, output));   delete output;   close(fd); }


 //读proto,其中proto的保存格式是binary格式文件。

void ReadProtoFromBinaryFile(const char* filename, Message* proto) {   int fd = open(filename, O_RDONLY);   CHECK_NE(fd, -1) << "File not found: " << filename;   ZeroCopyInputStream* raw_input = new FileInputStream(fd);   CodedInputStream* coded_input = new CodedInputStream(raw_input);   coded_input->SetTotalBytesLimit(536870912, 268435456);   CHECK(proto->ParseFromCodedStream(coded_input));   delete coded_input;   delete raw_input;   close(fd); }


 //将proto保存到文件,文件的序列化格式是binary的

void WriteProtoToBinaryFile(const Message& proto, const char* filename) {   fstream output(filename, ios::out | ios::trunc | ios::binary);   CHECK(proto.SerializeToOstream(&output)); }


从代码可以看到,提供了两种格式,一种是文档格式的,一种是二进制格式的。其中值得注意的是几个函数,


ZeroCopyInputStream ,相应的有ZeroCopyOutputStream //避免进行内存的拷贝 具体参考:

http://name5566.com/2633.html,

https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.io.zero_copy_stream
 

CodedInputStream  相应CodedOutputStream//,正如上面代码写的,用来定义不同长度的解析,理解的可能不太对,具体可参见:

https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.io.coded_stream?hl=zh-CN





0 0
原创粉丝点击