使用protobuf可以分为以下几步:
1 .proto文件的定义,在这个文件中定义了最终生成的prototxt格式
举个例子如下所示:
syntax = "proto2";
package label_proto;
message DetectLabel {
optional string name = 1;
optional int32 label = 2;
optional string display_name = 3;
optional string group = 4;
}
message DetectLabels {
repeated DetectLabel item = 1;
}
2 将上述proto文件转换成python的py文件
执行命令:
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/addressbook.proto
3 将message转换成prototxt定义的string格式
import label_pb2
from google.protobuf.text_format import MessageToString
categories = [{"group":"gender", "name":"male", "full_name":"gender_male", "value":0 },{"group":"gender", "name":"famale", "full_name":"gender_famale", "value":1 }]
label = label_pb2.DetectLabels()
with open("labelmap_attributes.prototxt", "w") as f:
for idx, category in enumerate(categories):
each_item = label.item.add()
each_item.name = category.get("name")
each_item.label = category.get("value")
each_item.display_name = category.get("full_name")
each_item.group = category.get("group")
f.write(MessageToString(label))
f.close()