如何使用tensorflow for mobile,开发环境为android studio

目前要做一个基于图片识别的安卓app,撇开ui的部分,首先要做的就是在android上把tensorflow跑起来。

在android上使用tensorflow有两种方式:

  1. tensorflow for mobile,较为成熟,包含的功能方法多。
  2. tensorflow lite,是1的升级版,目前处于开发者预览阶段,优势是体积小性能有优化。是未来的趋势。

鉴于项目原因,用的第一种。

第一步,在android studio里添加tensorflow的library引用。
三种方式
鉴于网络没问题,所以我直接使用第一种方式(Include the jcenter AAR which contains it):
build.gradle里添加依赖compile 'org.tensorflow:tensorflow-android:+'即可

第二步,调用tensorflow接口进行使用。
官网的代码:

// Load the model from disk.
TensorFlowInferenceInterface inferenceInterface =
new TensorFlowInferenceInterface(assetManager, modelFilename);

// Copy the input data into TensorFlow.
inferenceInterface.feed(inputName, floatValues, 1, inputSize, inputSize, 3);

// Run the inference call.
inferenceInterface.run(outputNames, logStats);

// Copy the output Tensor back into the output array.
inferenceInterface.fetch(outputName, outputs);

根本看不懂这些参数要怎么设定,不过可以用官方的example,所以就直接copy了图片识别的code

拷贝这两个文件就可以了:Classifier.javaTensorFlowImageClassifier.java

第三步,进行识别。

// 用model创建一个分类器。
final Classifier classifier = TensorFlowImageClassifier.create(
       getAssets(),
       MODEL_FILE,
       LABEL_FILE,
       INPUT_SIZE,
       IMAGE_MEAN,
       IMAGE_STD,
       INPUT_NAME,
       OUTPUT_NAME);

// 加载图片
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.noodle);

// 识别图片
btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
       List<Classifier.Recognition> results = classifier.recognizeImage(bitmap);
       for(Classifier.Recognition result : results) {
           tv.setText(tv.getText().toString() + "\r\n" + result.getTitle());
       }
   }
});

至此,成功在android手机跑起了tensorflow的库,真的是很简单好用。

PS:图片的部分遇到arrayOutOfIndex问题就是这个原因了。

posted @ 2018-01-17 14:23  dfghjkloiuy  阅读(4509)  评论(0编辑  收藏  举报