在python中更改protobuf对象的元素的最优雅的方法是什么?

时间:2019-04-03 17:25:57

标签: python protocol-buffers protobuf-python

Here is a config file代表protobuf对象:

model {
  faster_rcnn {
    num_classes: 37
    image_resizer {
      keep_aspect_ratio_resizer {
        min_dimension: 600
        max_dimension: 1024
      }
    }
    ...

我希望使用python将其读入对象,对某些值进行一些更改,然后将其写回到配置文件中。

一个复杂的因素是,这是一个很大的对象,它是由许多.proto文件构造而成的。

我能够通过将protobuf转换为字典,进行编辑,然后再转换回protobuf来完成任务,就像这样:

import tensorflow as tf
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import ParseDict
from google.protobuf import text_format
from object_detection.protos import pipeline_pb2

def get_configs_from_pipeline_file(pipeline_config_path, config_override=None):

  '''
  read .config and convert it to proto_buffer_object
  '''

  pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  with tf.gfile.GFile(pipeline_config_path, "r") as f:
    proto_str = f.read()
    text_format.Merge(proto_str, pipeline_config)
  if config_override:
    text_format.Merge(config_override, pipeline_config)
  return pipeline_config

configs = get_configs_from_pipeline_file('faster_rcnn_resnet101_pets.config')

d = MessageToDict(configs)
d['model']['fasterRcnn']['numClasses']=999

config2 = pipeline_pb2.TrainEvalPipelineConfig()
c = ParseDict(d, config2)

s = text_format.MessageToString(c)

with open('/path/test.config', 'w+') as fh:
    fh.write(str(s))

我希望能够直接对protobuf对象进行编辑,而不必转换为字典。但是,问题在于,尚不清楚如何“遍历dom”以发现对要更改其值的变量的正确引用。当涉及多个.proto文件时,尤其如此。

我能够像这样进行编辑,但我希望有更好的方法:

configs.model.ListFields()[0][1].num_classes = 99

0 个答案:

没有答案