当前位置: 首页 > 知识库问答 >
问题:

创建填充了元数据的 Tflite 模型时出现的问题(用于对象检测)

温凯
2023-03-14

我正在尝试在Android上运行一个tflite模型用于对象检测。同样,

  1. 我已使用我的图像集成功训练了模型,如下所示:

(a) 培训:

!python3 object_detection/model_main.py \
--pipeline_config_path=/content/drive/My\ Drive/Detecto\ Tutorial/models/research/object_detection/samples/configs/ssd_mobilenet_v2_coco.config \
--model_dir=training/

修改配置文件以指向提到我的特定TF记录的位置)

(b) 导出推理图

!python /content/drive/'My Drive'/'Detecto Tutorial'/models/research/object_detection/export_inference_graph.py \
--input_type=image_tensor \
--pipeline_config_path=/content/drive/My\ Drive/Detecto\ Tutorial/models/research/object_detection/samples/configs/ssd_mobilenet_v2_coco.config \
--output_directory={output_directory} \
--trained_checkpoint_prefix={last_model_path}

(c) 创建tflite就绪图

!python /content/drive/'My Drive'/'Detecto Tutorial'/models/research/object_detection/export_tflite_ssd_graph.py \
  --pipeline_config_path=/content/drive/My\ Drive/Detecto\ Tutorial/models/research/object_detection/samples/configs/ssd_mobilenet_v2_coco.config \
  --output_directory={output_directory} \
  --trained_checkpoint_prefix={last_model_path} \
  --add_postprocessing_op=true

我使用图形文件中的tflite_convert创建了一个tflite模型,如下所示

!TF lite _ convert < br >-graph _ def _ file =/content/Drive/My \ Drive/detect o \ Tutorial/models/research/fine _ tuned _ model/TF lite _ graph . Pb < br >-output _ file =/content/Drive/My \ Drive/detect o \ Tutorial/models/research/fine _ tuned _ model/detect 3 . TF lite < br >-output _ format = TF lite < br >-input _ shapes = 1,300,300,3 < br >-input _ arrays = normalized _ input _ image _ tensor

上述tflite模型经过独立验证,工作正常(在Android之外)。

现在需要用元数据填充tflite模型,以便可以在下面链接提供的示例Android代码中处理(因为我收到了一个错误:不是有效的Zip文件,并且在Android Studio上运行时没有关联文件)。

https://github.com/tensorflow/examples/blob/master/lite/examples/object_detection/android/README.md

作为同一链接的一部分提供的sample.TFlite中填充了元数据,工作正常。

当我尝试使用以下链接:https://www.tensorflow.org/lite/convert/metadata#deep_dive_into_the_image_classification_example

populator = _metadata.MetadataPopulator.with_model_file('/content/drive/My Drive/Detecto Tutorial/models/research/fine_tuned_model/detect3.tflite')
populator.load_metadata_buffer(metadata_buf)
populator.load_associated_files(['/content/drive/My Drive/Detecto Tutorial/models/research/fine_tuned_model/labelmap.txt'])
populator.populate()

要添加元数据(代码的其余部分实际上与元描述的一些更改相同,而不是图像分类并指定标签映射的位置.txt),它给出了以下错误:

<ipython-input-6-173fc798ea6e> in <module>()
  1 populator = _metadata.MetadataPopulator.with_model_file('/content/drive/My Drive/Detecto Tutorial/models/research/fine_tuned_model/detect3.tflite')
  ----> 2 populator.load_metadata_buffer(metadata_buf)
        3 populator.load_associated_files(['/content/drive/My Drive/Detecto Tutorial/models/research/fine_tuned_model/labelmap.txt'])
        4 populator.populate()

1 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_lite_support/metadata/metadata.py in _validate_metadata(self, metadata_buf)
    540           "The number of output tensors ({0}) should match the number of "
    541           "output tensor metadata ({1})".format(num_output_tensors,
--> 542                                                 num_output_meta))
    543 
    544 

ValueError: The number of output tensors (4) should match the number of output tensor metadata (1)

4个输出张量是步骤2中output_arrays中提到的张量(有人可能会在那里纠正我)。我不确定如何相应地更新输出张量元数据。

最近使用过自定义模型(然后在Android上应用)使用过对象检测的任何人都可以提供帮助吗?或者帮助了解如何将张量元数据更新为 4 而不是 1。

共有1个答案

王建华
2023-03-14

2021年6月10日更新:

请参阅tensorflow.org上关于元数据编写器库的最新教程。

更新:

Metadata Writer库已经发布。它目前支持图像分类器和对象检测器,更多支持的任务正在进行中。

下面是为对象检测器模型写入元数据的示例:

  1. 安装TFLite支持夜间Pypi包:
pip install tflite_support_nightly
from tflite_support.metadata_writers import object_detector
from tflite_support.metadata_writers import writer_utils
from tflite_support import metadata

ObjectDetectorWriter = object_detector.MetadataWriter
_MODEL_PATH = "ssd_mobilenet_v1_1_default_1.tflite"
_LABEL_FILE = "labelmap.txt"
_SAVE_TO_PATH = "ssd_mobilenet_v1_1_default_1_metadata.tflite"

writer = ObjectDetectorWriter.create_for_inference(
    writer_utils.load_file(_MODEL_PATH), [127.5], [127.5], [_LABEL_FILE])
writer_utils.save_file(writer.populate(), _SAVE_TO_PATH)

# Verify the populated metadata and associated files.
displayer = metadata.MetadataDisplayer.with_model_file(_SAVE_TO_PATH)
print("Metadata populated:")
print(displayer.get_metadata_json())
print("Associated file(s) populated:")
print(displayer.get_packed_associated_file_list())

-之前手动写入元数据的答案-

这里是一个代码片段,您可以使用它来填充对象检测模型的元数据,它与TFLite Android应用程序兼容。

model_meta = _metadata_fb.ModelMetadataT()
model_meta.name = "SSD_Detector"
model_meta.description = (
    "Identify which of a known set of objects might be present and provide "
    "information about their positions within the given image or a video "
    "stream.")

# Creates input info.
input_meta = _metadata_fb.TensorMetadataT()
input_meta.name = "image"
input_meta.content = _metadata_fb.ContentT()
input_meta.content.contentProperties = _metadata_fb.ImagePropertiesT()
input_meta.content.contentProperties.colorSpace = (
    _metadata_fb.ColorSpaceType.RGB)
input_meta.content.contentPropertiesType = (
    _metadata_fb.ContentProperties.ImageProperties)
input_normalization = _metadata_fb.ProcessUnitT()
input_normalization.optionsType = (
    _metadata_fb.ProcessUnitOptions.NormalizationOptions)
input_normalization.options = _metadata_fb.NormalizationOptionsT()
input_normalization.options.mean = [127.5]
input_normalization.options.std = [127.5]
input_meta.processUnits = [input_normalization]
input_stats = _metadata_fb.StatsT()
input_stats.max = [255]
input_stats.min = [0]
input_meta.stats = input_stats

# Creates outputs info.
output_location_meta = _metadata_fb.TensorMetadataT()
output_location_meta.name = "location"
output_location_meta.description = "The locations of the detected boxes."
output_location_meta.content = _metadata_fb.ContentT()
output_location_meta.content.contentPropertiesType = (
    _metadata_fb.ContentProperties.BoundingBoxProperties)
output_location_meta.content.contentProperties = (
    _metadata_fb.BoundingBoxPropertiesT())
output_location_meta.content.contentProperties.index = [1, 0, 3, 2]
output_location_meta.content.contentProperties.type = (
    _metadata_fb.BoundingBoxType.BOUNDARIES)
output_location_meta.content.contentProperties.coordinateType = (
    _metadata_fb.CoordinateType.RATIO)
output_location_meta.content.range = _metadata_fb.ValueRangeT()
output_location_meta.content.range.min = 2
output_location_meta.content.range.max = 2

output_class_meta = _metadata_fb.TensorMetadataT()
output_class_meta.name = "category"
output_class_meta.description = "The categories of the detected boxes."
output_class_meta.content = _metadata_fb.ContentT()
output_class_meta.content.contentPropertiesType = (
    _metadata_fb.ContentProperties.FeatureProperties)
output_class_meta.content.contentProperties = (
    _metadata_fb.FeaturePropertiesT())
output_class_meta.content.range = _metadata_fb.ValueRangeT()
output_class_meta.content.range.min = 2
output_class_meta.content.range.max = 2
label_file = _metadata_fb.AssociatedFileT()
label_file.name = os.path.basename("label.txt")
label_file.description = "Label of objects that this model can recognize."
label_file.type = _metadata_fb.AssociatedFileType.TENSOR_VALUE_LABELS
output_class_meta.associatedFiles = [label_file]

output_score_meta = _metadata_fb.TensorMetadataT()
output_score_meta.name = "score"
output_score_meta.description = "The scores of the detected boxes."
output_score_meta.content = _metadata_fb.ContentT()
output_score_meta.content.contentPropertiesType = (
    _metadata_fb.ContentProperties.FeatureProperties)
output_score_meta.content.contentProperties = (
    _metadata_fb.FeaturePropertiesT())
output_score_meta.content.range = _metadata_fb.ValueRangeT()
output_score_meta.content.range.min = 2
output_score_meta.content.range.max = 2

output_number_meta = _metadata_fb.TensorMetadataT()
output_number_meta.name = "number of detections"
output_number_meta.description = "The number of the detected boxes."
output_number_meta.content = _metadata_fb.ContentT()
output_number_meta.content.contentPropertiesType = (
    _metadata_fb.ContentProperties.FeatureProperties)
output_number_meta.content.contentProperties = (
    _metadata_fb.FeaturePropertiesT())

# Creates subgraph info.
group = _metadata_fb.TensorGroupT()
group.name = "detection result"
group.tensorNames = [
    output_location_meta.name, output_class_meta.name,
    output_score_meta.name
]
subgraph = _metadata_fb.SubGraphMetadataT()
subgraph.inputTensorMetadata = [input_meta]
subgraph.outputTensorMetadata = [
    output_location_meta, output_class_meta, output_score_meta,
    output_number_meta
]
subgraph.outputTensorGroups = [group]
model_meta.subgraphMetadata = [subgraph]

b = flatbuffers.Builder(0)
b.Finish(
    model_meta.Pack(b),
    _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER)
self.metadata_buf = b.Output()
 类似资料:
  • 我使用BS4从https://www.worldometers.info/coronavirus/中获取了全国统计数据。但我想用这些数据填充我的django模型,这些数据与我不知道如何填充的刮取数据相同。在使用其他库(如scrapy(celery))刮取表格数据时,我也遇到了麻烦。这是我试图报废“//*[@id=”Main_Table_Countries_Today“]”表的xpath。如果有人能

  • 问题内容: 创建给定大小的零填充熊猫数据框的最佳方法是什么? 我用过了: 有更好的方法吗? 问题答案: 您可以尝试以下方法:

  • 在jaxb上下文转换技术的帮助下,我将java对象转换为xml字符串。当我试着以主类的形式运行程序时。它将其转换为xml字符串,但当我从project中的不同类调用该方法时。它抛出参数不匹配异常。我正在使用tomcat 7和jdk 6,并在eclipse中运行代码。请查找下面的马歇尔片段。 请指导为什么它失败时,我运行它到一个项目。

  • 我正试图更好地理解Python以及为什么我会收到错误。 我有一个带有国家名称的数据框,我想过滤数据集,只显示那些没有重复项的数据。我进入: 然而,我得到一个错误 似乎创建了一个列表,该列表还显示了国家名称和布尔值,而不仅仅是我所期望的布尔值。 此外,我尝试只对一个国家进行过滤,即,,效果非常好。 我只是想理解为什么在一个场景中它起作用,而在另一个场景中它不起作用。我确实注意到后者有一个从0开始的索

  • 问题内容: 我一直试图创建一个包含两个值的类的数组,但是当我尝试将值应用于该数组时,我得到了。 为什么会出现此异常,我该如何解决? 问题答案: 你创建了数组,但未在其中放置任何内容,因此你有一个包含5个元素的数组,所有元素均为null。你可以添加 在设置的行之前。