模型在 jupyter 笔记本上运行,但在 android 上导入时失败

时间:2021-04-30 08:23:36

标签: java android tensorflow

btPredict.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        img= Bitmap.createScaledBitmap(img,200,200,true);
        try {
            Model model = Model.newInstance(getApplicationContext());
            TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 200, 200, 3},
                                                                      DataType.FLOAT32);
            TensorImage tensorImage = new TensorImage(DataType.FLOAT32);
            tensorImage.load(img);
            ByteBuffer byteBuffer = tensorImage.getBuffer();
            inputFeature0.loadBuffer(byteBuffer);

            Model.Outputs outputs = model.process(inputFeature0);
            TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
            textView.setText(outputFeature0.getFloatArray()[0] + " \n"+ outputFeature0.getFloatArray()[1]);
            model.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我收到以下错误

021-04-30 11:55:07.70329735-29735/com.example.catsdogmodel E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.example.catsdogmodel, PID: 29735
     java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
         at com.example.catsdogmodel.MainActivity$3.onClick(MainActivity.java:94)
         at android.view.View.performClick(View.java:7869)
         at android.widget.TextView.performClick(TextView.java:14958)
         at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
         at android.view.View.performClickInternal(View.java:7838)
         at android.view.View.access$3600(View.java:886)
         at android.view.View$PerformClick.run(View.java:29362)
         at android.os.Handler.handleCallback(Handler.java:883)
         at android.os.Handler.dispatchMessage(Handler.java:100)
         at android.os.Looper.loop(Looper.java:237)
         at android.app.ActivityThread.main(ActivityThread.java:8019)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)][1]

IDE

1 个答案:

答案 0 :(得分:0)

在不知道您的型号的情况下,我很确定是这条线textView.setText(outputFeature0.getFloatArray()[0] + " \n"+ outputFeature0.getFloatArray()[1]); 也许你的输出比你想象的多包装一次,所以你必须写 textView.setText(outputFeature0.getFloatArray()[0][0] + " \n"+ outputFeature0.getFloatArray()[0][1]); 但是,如果不了解您的模型结构,就很难说。除此之外,我不会在 onClick 方法中而是在单独的类中创建您的所有输入数据和模型。