標籤:htm back mobile bitmap coder wim ring amp 手機
目前要做一個基於圖片識別的安卓app,撇開ui的部分,首先要做的就是在android上把tensorflow跑起來。
在android上使用tensorflow有兩種方式:
- tensorflow for mobile,較為成熟,包含的功能方法多。
- 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