如何使用tensorflow for mobile,開發環境為android studio

來源:互聯網
上載者:User

標籤:htm   back   mobile   bitmap   coder   wim   ring   amp   手機   

目前要做一個基於圖片識別的安卓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.java和TensorFlowImageClassifier.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問題就是這個原因了。

如何使用tensorflow for mobile,開發環境為android studio

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.