无法在具有 307200 字节的 TensorFlowLite 缓冲区和具有 270000 字节的 Java 缓冲区之间进行转换

Cannot convert between a TensorFlowLite buffer with 307200 bytes and a Java Buffer with 270000 bytes

我正在尝试 运行 来自 Tensorflow detection model zoo. I used the ssd_mobilenet_v3_small_coco model from this site under the Mobile Models heading. According to the instructions 的预训练对象检测 TensorFlowLite 模型 运行 我们在 Android[=23 上的模型=],为了避免资源被覆盖,我注释掉了模型下载脚本: build.gradle 文件中的 // apply from:'download_model.gradle' 并替换了 assets 目录中的 detect.tflitelabelmap.txt 文件。构建成功,没有任何错误,该应用程序已安装在我的 android 设备中,但它一启动就崩溃了,logcat 显示:

E/AndroidRuntime: FATAL EXCEPTION: inference
Process: org.tensorflow.lite.examples.detection, PID: 16960
java.lang.IllegalArgumentException: Cannot convert between a TensorFlowLite buffer with 307200 bytes and a Java Buffer with 270000 bytes.
    at org.tensorflow.lite.Tensor.throwIfShapeIsIncompatible(Tensor.java:425)
    at org.tensorflow.lite.Tensor.throwIfDataIsIncompatible(Tensor.java:392)
    at org.tensorflow.lite.Tensor.setTo(Tensor.java:188)
    at org.tensorflow.lite.NativeInterpreterWrapper.run(NativeInterpreterWrapper.java:150)
    at org.tensorflow.lite.Interpreter.runForMultipleInputsOutputs(Interpreter.java:314)
    at org.tensorflow.lite.examples.detection.tflite.TFLiteObjectDetectionAPIModel.recognizeImage(TFLiteObjectDetectionAPIModel.java:196)
    at org.tensorflow.lite.examples.detection.DetectorActivity.run(DetectorActivity.java:185)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:201)
    at android.os.HandlerThread.run(HandlerThread.java:65)

我搜索了许多 TensorFlowLite 文档,但没有找到与此错误相关的任何内容,而且我在 Whosebug 上发现了一些具有相同错误消息但针对自定义训练模型的问题,因此没有帮助。即使在自定义训练的模型上,同样的错误也会不断出现。我应该怎么做才能消除这个错误?

您应该调整输入张量的大小,以便您的模型可以获取任何大小、像素或批次的数据。

以下代码用于图像分类,您的代码用于对象检测: TFLiteObjectDetectionAPIModel 负责获取大小。尝试在 TFLiteObjectDetectionAPIModel 的某些地方操纵大小。

The labels length needs to be match the output tensor length for your trained model.

  int[] dimensions = new int[4];
  dimensions[0] = 1; // Batch_size // No of frames at a time
  dimensions[1] = 224; // Image Width required by model
  dimensions[2] = 224; // Image Height required by model
  dimensions[3] = 3; // No of Pixels
  Tensor tensor = c.tfLite.getInputTensor(0);
  c.tfLite.resizeInput(0, dimensions);
  Tensor tensor1 = c.tfLite.getInputTensor(0);

Change input size