github给出的官方demo:
Tensorflow Android Camera Demo
官方给出的环境需要:Linux,Android Studio, SDK,NDK,Bazel.
为了避免使用Linux,找了好久找到一篇不用bazel的: )
windows 下Android Studio中运行tensorflow
本来想要使用eclipse开发Android的,但是虽然eclipse支持Android SDK、ADT插件,但是没有Android Studio全面。
- Android Studio-2.2.0
- 使用Android SDK包管理器,install的是Android API 26
- Android SDK(E:\java\android-sdk-windows),
- JDK (E:\java\jdk1.8.0_181)
- Android NDK(E:\major\Android_NDK\android-ndk-r16b-windows-x86_64\android-ndk-r16b)
思路:
- 把tensorflow模型保存为pb文件,并将此pb文件添加到APP项目中:其中的asset文件夹是自己建的。
- 在app项目中的build.gradle文件中添加该语句
compile 'org.tensorflow:tensorflow-android:1.12.0'
加了这句就之后,编译的时候会自动下载tensorflow-android:1.12.0包,然后我们的Android项目就可以使用tensorflow接口。不需要使用bazel等。
下出现:
但是编译过程中出现错误:
Error:Error converting bytecode to dex:
Cause: Dex cannot parse version 52 byte code.
This is caused by library dependencies that have been compiled using Java 8 or above.
If you are using the 'java' gradle plugin in a library submodule add
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
to that submodule's build.gradle file.
version 52 是java8编译后生成的字节码版本号
按照这篇:cause:Dex cannot parse version 52 byte code解决方法
中的方法,上述error不见了。
下边贴出改动后的build.gradle文件中的内容:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "com.example.fxy.myapplication01"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
jackOptions{ //这是自己添加的start
enabled = true
} ///这是自己添加的end
}
compileOptions { //这是自己添加的start
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
//这是自己添加的end
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
testCompile 'junit:junit:4.12'
//下边这句是自己添加的,这句话的作用是,编译之后我们的Android项目就可以使用
// tensorflow接口。不需要使用bazel等
compile 'org.tensorflow:tensorflow-android:1.12.0'
}
run APP—>AS左下角的“run”框中的部分信息提示,如下
03/30 20:24:24: Launching app
$ adb push E:\PROJECT\_Android\workspace\MyApplication01\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.fxy.myapplication01
$ adb shell pm install -r "/data/local/tmp/com.example.fxy.myapplication01"
Success
$ adb shell am start -n "com.example.fxy.myapplication01/com.example.fxy.myapplication01.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 20378 on device huawei-mar_al00-5GK4C19A18010184
手机上提示安装该APP。
题外话
- cause :Dex cannot parse version 52 byte code._APICloud论坛这个上面说到大多数的第三方库自定义的兼容版本都是java7(即jdk 1.7),建议进行java开发使用jdk 1.7
- dex文件 && class文件
两者的异同点可以看下面的笔记 : )