在Tensorflow-lite中输入具有动态尺寸的图像

五边形:

我有一个tensorflow模型,它接受不同大小的输入图像:

inputs = layers.Input(shape=(128,None,1), name='x_input')

<tf.Tensor 'x_input:0' shape=(?, 128, ?, 1) dtype=float32>

当我将此模型转换为tensorflow-lite时,它会抱怨:

converter = tf.lite.TFLiteConverter.from_frozen_graph(
  graph_def_file, input_arrays, output_arrays)
tflite_model = converter.convert() 

ValueError: None is only supported in the 1st dimension.
Tensor 'x_input_1' has invalid shape '[None, 128, None, 1]'.

我无法将图像缩放到固定大小。我看到的唯一解决方案是将图像填充到最大尺寸并在图形中使用该尺寸,但这似乎很浪费。还有其他方法可以使tensorflow-lite与动态图像尺寸一起使用吗?对此限制有任何理由吗?谢谢。

FalconUA:

是的,您可以在TF-Lite中使用动态张量之所以不能直接将形状设置为,[None, 128, None, 1]是因为通过这种方式,将来可以轻松支持更多语言。此外,它充分利用了静态内存分配方案。对于打算用于计算能力低的小型设备的框架来说,这是一个明智的设计选择。以下是有关如何动态设置张量大小的步骤:

0.冻结

似乎您正在从冻结的GraphDef(即*.pb文件)进行转换。假设冻结的模型具有输入形状[None, 128, None, 1]

1.转换步骤。

在此步骤中,将输入大小设置为模型可以接受的任何有效大小例如:

tflite_convert \
  --graph_def_file='model.pb' \
  --output_file='model.tflite' \
  --input_shapes=1,128,80,1 \     # <-- here, you set an
                                  #     arbitrary valid shape
  --input_arrays='input' \         
  --output_arrays='Softmax'

2.推论步骤

诀窍是interpreter::resize_tensor_input(...)在推理过程中实时使用TF-Lite API 的功能我将提供它的python实现。Java和C ++实现应相同(因为它们具有相似的API):

from tensorflow.contrib.lite.python import interpreter

# Load the *.tflite model and get input details
model = Interpreter(model_path='model.tflite')
input_details = model.get_input_details()

# Your network currently has an input shape (1, 128, 80 , 1),
# but suppose you need the input size to be (2, 128, 200, 1).
model.resize_tensor_input(
    input_details[0]['index'], (2, 128, 200, 1))
model.allocate_tensors()

而已。现在(2, 128, 200, 1),只要您的网络体系结构允许输入这样的形状就可以将该模型用于具有shape的图像请注意,model.allocate_tensors()每次进行此类重塑时都必须做,所以效率很低。这是强烈建议,以避免在程序中使用此功能太多。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章