1.依赖工具及环境
下载tensorflow-models源码
git clone https://github.com/tensorflow/models
按照提示配置环境
注意在~/.bashrc添加上1
2# From tensorflow/models/research/
export PYTHONPATH=$PYTHONPATH:xxxxxx/tensorflow-models/research:xxxx/tensorflow-models/research/slim
下载tensorflow源码和android ndk r16b
1
2
3https://github.com/tensorflow/tensorflow
cd tensorflow
git checkout r1.10设置编译android demo需要的ndk
进入tensorflow源码根目录,修改WORKSPACE增加如下行1
2
3
4
5
6
7
8
9
10
11
12
13android_sdk_repository(
name = "androidsdk",
api_level = 27,
build_tools_version = "27.0.2",
path = "/Users/xxxx/Library/Android/sdk",
)
# Android NDK r12b is recommended (higher may cause issues with Bazel)
android_ndk_repository(
name="androidndk",
path="/Users/xxxx/Library/Android/sdk/android-ndk-r16b",
api_level=21
)
2.生成tflite兼容的pb graph
2.1) 设置变量
1 | ROOT_PATH=xxxxx/tensorflow/pretrained_models |
2.2) 根据pb、checkpoint、pipeline.config等生成frozen graph
1 | python object_detection/export_tflite_ssd_graph.py --pipeline_config_path $CONFIG_FILE --trained_checkpoint_prefix $CHECKPOINT_PATH --output_directory /tmp/tflite/ --add_postprocessing_op=true |
3.通过TOCO获取优化后的模型
TOCO: TensorFlow Lite Optimizing Converter
3.1)如果想要整型[这块暂时没调通]
1 | bazel run --config=opt tensorflow/contrib/lite/toco:toco -- \ |
3.2)如果想要浮点类型
1 | bazel run --config=opt tensorflow/contrib/lite/toco:toco -- \ |
4. 集成到Android Studio工程中
4.1)更新模型和配置文件
cp /tmp/tflite/detect.tflite tensorflow/contrib/lite/examples/android/app/src/main/assets
编辑tensorflow/contrib/lite/examples/android/BUILD,增加新的detect.tflite和color_pen_label.txt
1 | @@ -37,9 +37,10 @@ android_binary( |
新建color_pen_label.txt内容为
1 | ??? |
拷贝到demo/asset目录:
cp color_pen_label.txt tensorflow/contrib/lite/examples/android/app/src/main/assets
如果是float的话,按如下修改源码
tensorflow/contrib/lite/examples/android/app/src/main/java/org/tensorflow/demo/DetectorActivity.java
1 | @@ -50,9 +50,9 @@ public class DetectorActivity extends CameraActivity implements OnImageAvailable |
如果是量化模型的话,按如下修改源码
1 | @@ -50,9 +50,9 @@ public class DetectorActivity extends CameraActivity implements OnImageAvailable |
4.2)编译tflite_demo app
1 | bazel build --cxxopt=--std=c++11 //tensorflow/contrib/lite/examples/android:tflite_demo |
4.3)安装到Android设备
1 | adb install -r bazel-bin/tensorflow/contrib/lite/examples/android/tflite_demo.apk |