四时宝库

程序员的知识宝库

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调试模式,编译安装后即可运行。

运行效果:

风扇识别成功:

鼠标

2个鼠标:

三、demo项目结构

  • 关键代码在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设置

谷歌建议大部分开发者删减x86,x86_64,arm32的ABIs:

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

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接