天天看點

TensorFlow2學習十八、安卓進行圖像分類示例

一、說明

  • 本示例來源于tensorflow官網。
  • 項目連續使用安卓兵團攝像頭對所看到的物體進行分類。
  • 項目使用TF Lite Java API來執行推理。該示範應用程式實時地對圖像幀分類,顯示最可能的分類結果。它允許使用者選擇浮點或量化模型,選擇線程數,并決定運作在CPU、GPU上,或是通過NNAPI運作。

二、代碼來源

​​https://github.com/tensorflow/examples/tree/master/lite/examples/image_classification/android​​

1. 編譯環境

Android Studio3.2+

2. 建構說明

直接編譯有可能會報異常,在項目的build.gralde->dependencies裡添加:

implementation group: 'org.tensorflow', name: 'tensorflow-lite', version: '2.0.0'      

我同時把其它幾個庫版本改了一下,供參考:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'

    implementation 'org.tensorflow:tensorflow-lite:2.0.0'
    implementation 'org.tensorflow:tensorflow-lite-gpu:2.0.0'
    implementation 'org.tensorflow:tensorflow-lite-support:0.0.0-nightly'
    implementation group: 'org.tensorflow', name: 'tensorflow-lite', version: '2.0.0'
}      

3. 連接配接手機,打開USB調試模式,編譯安裝後即可運作。

運作效果:

風扇識别成功:

TensorFlow2學習十八、安卓進行圖像分類示例

滑鼠

TensorFlow2學習十八、安卓進行圖像分類示例

2個滑鼠:

TensorFlow2學習十八、安卓進行圖像分類示例

識别成眼鏡了 😦

三、demo項目結構

[外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-6RkXhtcs-1575613381150)(/uploads/20191206/850c999b5dec24281e42ce41c4a6468c.png)]

  • 關鍵代碼在org.tensorflow.lite.examples.classification.tflite裡
  • 模型檔案放在assets下

類說明:

1. 入口Activity

ClassifierActivity,調用模型:

private Classifier classifier;
# 執行個體化,傳回 ClassifierQuantizedMobileNet 或 ClassifierFloatMobileNet
classifier = Classifier.create(this, model, device, numThreads); 

final List<Classifier.Recognition> results =
                  classifier.recognizeImage(rgbFrameBitmap, sensorOrientation);      

2. Classifier類

虛類,封裝TF模型的調用,其中識别的主要程式代碼段:

inputImageBuffer = loadImage(bitmap, sensorOrientation);
tflite.run(inputImageBuffer.getBuffer(), outputProbabilityBuffer.getBuffer().rewind());
Map<String, Float> labeledProbability =
        new TensorLabel(labels, probabilityProcessor.process(outputProbabilityBuffer))
            .getMapWithFloatValue();
return getTopKProbability(labeledProbability);      

getTopKProbability用來傳回最有可能分類值。

3. ClassifierFloatMobileNet和ClassifierQuantizedMobileNet

用來定義模型位置、标簽位置等

四、自己的項目裡使用TF2.0講解

1. dependencies 引用

2. ABIs設定

android {
    defaultConfig {
        ndk {
            abiFilters 'armeabi-v7a', 'arm64-v8a'
        }
    }
}