运行TensorFlow模型的java.nio.BufferOverflowException

时间:2018-07-21 17:22:16

标签: android tensorflow

在我的android应用中运行tensorflow模型时出现此致命错误:

Caused by: java.nio.BufferOverflowException
                                                                 at java.nio.HeapFloatBuffer.put(HeapFloatBuffer.java:179)
                                                                 at org.tensorflow.Tensor.writeTo(Tensor.java:488)
                                                                 at org.tensorflow.contrib.android.TensorFlowInferenceInterface.fetch(TensorFlowInferenceInterface.java:488)
                                                                 at org.tensorflow.contrib.android.TensorFlowInferenceInterface.fetch(TensorFlowInferenceInterface.java:442)

代码如下:

    //sample values: WANTED_WIDTH = 714, WANTED_HEIGHT = 438
    int[] intValues = new int[WANTED_WIDTH * WANTED_HEIGHT];
    float[] floatValues = new float[WANTED_WIDTH * WANTED_HEIGHT * 3];
    float[] outputValues = new float[WANTED_WIDTH * WANTED_HEIGHT * 3];

    Bitmap bitmap = activity.mainBitmap;

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, WANTED_WIDTH, WANTED_HEIGHT, true);
    scaledBitmap.getPixels(intValues, 0, scaledBitmap.getWidth(), 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight());

    for (int i = 0; i < intValues.length; i++) {
        final int val = intValues[i];
        floatValues[i*3] = ((val >> 16) & 0xFF);
        floatValues[i*3+1] = ((val >> 8) & 0xFF);
        floatValues[i*3+2] = (val & 0xFF);
    }

    AssetManager assetManager = getResources().getAssets();
    mInferenceInterface = new TensorFlowInferenceInterface(assetManager, MODEL_FILE);


    final float[] styleVals = new float[NUM_STYLES];
    for (int i = 0; i < NUM_STYLES; ++i) {
        styleVals[i] = 0.0f / NUM_STYLES;
    }
    styleVals[params[0]] = 1.5f;

    mInferenceInterface.feed(INPUT_NODE, floatValues, 1, WANTED_HEIGHT, WANTED_WIDTH, 3);
    mInferenceInterface.feed("style_num", styleVals, NUM_STYLES);
    mInferenceInterface.run(new String[] {OUTPUT_NODE}, false);
    mInferenceInterface.fetch(OUTPUT_NODE, outputValues);

错误显示在我上面提供的代码的最后一行,即       “ mInferenceInterface.fetch(OUTPUT_NODE,outputValues);”

关于如何解决此问题的任何想法,我已经经历过Google搜索,但是在此特定问题上没有任何涉及。

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要验证OUTPUT_NODE的尺寸等于outputValues的尺寸吗?

此外,您可以参考我的项目代码url:https://github.com/tz28/Chinese-number-gestures-recognition/blob/master/DigitalGestureRecognition/app/src/main/java/com/example/hc/digitalgesturerecognition/Classifier.java