简体   繁体   English

如何使用 Java 在 android 中将图像提供给 TFLite 预训练的 model?

[英]how to feed an image to TFLite pre-trained model in android using Java?

I am new to android development, I need to get a pre-trained image classification model and run it with the image I choose, I managed to choose images from the gallery and retrieve the image from URI beside loading the TFLite model我是 android 开发的新手,我需要获得一个预训练的图像分类 model 并使用我选择的图像运行它,我设法从图库中选择图像并从加载 TFLite Z20F35E630DAF44D88FC3 的 URI 中检索图像

I also saw tutorials about TFLite model conversions and managed to run a simple model converting C degrees to F degrees我还看到了有关 TFLite model 转换的教程,并设法运行了一个简单的 model 将 C 度转换为 F 度

I can't do this with an image, any help?我不能用图像做到这一点,有什么帮助吗?

Android code for image selection and model loading: Android 代码用于图像选择和 model 加载:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.tensorflow.lite.Interpreter;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MainActivity extends AppCompatActivity {

    Button btnChoose;
    ImageView imageView;
    Interpreter tflite;
    TextView textView;

    String[] classes;

    private static int GALLERY_REQUEST_CODE = 35;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);

        btnChoose = findViewById(R.id.btnChoose);

        btnChoose.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("IntentReset")
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                String[] mimeTypes = {"image/jpeg", "image/png"};
                intent.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
                startActivityForResult(intent,GALLERY_REQUEST_CODE);
            }
        });

        try{
            tflite = new Interpreter(loadModelFile());
        } catch (Exception ex){
            ex.printStackTrace();
        }

        try{
            InputStream is = getAssets().open("labels_mobilenet_quant_v1_224.txt");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            classes = new String(buffer).split("\n");
            textView.setText(classes[1]);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            imageView.setImageURI(selectedImage);
        }
    }

    // TODO:
    /*
    doInf Function
     */

    private MappedByteBuffer loadModelFile() throws IOException {
        AssetFileDescriptor fileDescriptor = this.getAssets().openFd("mobilenet_v1_1.0_224_quant.tflite");
        FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
        FileChannel fileChannel = inputStream.getChannel();
        long startOffset = fileDescriptor.getStartOffset();
        long declaredLength = fileDescriptor.getDeclaredLength();
        return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
    }

}

TFLite Simple model code i done before我之前完成的 TFLite Simple model 代码

Button btn;
TextView tvOutput;
EditText etInput;
Interpreter tflite;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = findViewById(R.id.button);
    etInput = findViewById(R.id.etInput);
    tvOutput = findViewById(R.id.tvOutput);

    try{
        tflite = new Interpreter(loadModelFile());
    } catch (Exception ex){
        ex.printStackTrace();
    }

    btn.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View v) {
            float pred = doInf(etInput.getText().toString());
            tvOutput.setText(Float.toString(pred));
        }
    });
}

public float doInf(String inputString){
    float[] inputVal = new float[1];
    inputVal[0] = Float.parseFloat(inputString);

    float[][] outputVal = new float[1][1];

    tflite.run(inputVal, outputVal);

    return outputVal[0][0];
}

private MappedByteBuffer loadModelFile() throws IOException{
    AssetFileDescriptor fileDescriptor = this.getAssets().openFd("linear.tflite");
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}

Seems like you are trying to integrate an image classification model of mobilenet.似乎您正在尝试集成 mobilenet 的图像分类 model。 Try the TFLite Task library, which will take 5 lines of code to run and it encapsulate image processing and output processing automatically for you.试试 TFLite Task 库,它只需要 5 行代码即可运行,它自动为您封装了图像处理和 output 处理。 See the instruction and the Android app example .请参阅说明Android 应用示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将预训练的张量流模型加载并预测到Java代码中? - How to load and predict a pre-trained tensorflow model into Java code? 如何在Android Studio中使用预先训练的.model文件进​​行预测? - How to use pre-trained .model file for predictions in Android Studio? 如何使用TensorFlow Java API移除预训练模型的输出层? - How can I remove the output layer of pre-trained model with TensorFlow java api? 在Tensorflow for Java中加载预训练的模型 - Load pre-trained models in Tensorflow for Java 如何将训练有素的 tensorflow 2 model 导出到 tflite? - How to export trained tensorflow 2 model to tflite? 如何结合两个预先训练的Word2Vec模型? - How to combine two pre-trained Word2Vec models? 如何在Android Studio中集成tflite模型来识别声音(Java语言) - How to integrate tflite model in Android Studio to recognize sounds (Java language) 如何使用 AssetManager 和 Play Asset Delivery 在 Java 中加载 tflite model? - how to load a tflite model in Java using AssetManager and Play Asset Delivery? 如何使用java配置android studio来使用.tflite文件? - How to configure android studio using java to use .tflite file? 如何从 tflite model 中将 output 形状 [1,28,28,1] 数组作为 android 中的图像 - How to output array of shape [ 1, 28, 28,1] from a tflite model as image in android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM