如何使用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問題就是這個原因了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM