【TensorFlow爬坑记】部署TensorFlow Android Demo到Android Studio中需要修改的地方

额,说多了都是泪,调个demo调了三天才跑出来,下面放上代码(我把要修改的地方都加中文注释)

官方源码:https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android

AndroidManifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2016 The TensorFlow Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.tensorflow.demo">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO" />


#######下面三行注释掉#########
    <!--<uses-sdk-->
        <!--android:minSdkVersion="21"-->
        <!--android:targetSdkVersion="23" />-->

    <application android:allowBackup="true"
        android:debuggable="true"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/MaterialTheme">

        <activity android:name="org.tensorflow.demo.ClassifierActivity"
                  android:screenOrientation="portrait"
                  android:label="@string/activity_name_classification">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="org.tensorflow.demo.DetectorActivity"
                  android:screenOrientation="portrait"
                  android:label="@string/activity_name_detection">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="org.tensorflow.demo.StylizeActivity"
                  android:screenOrientation="portrait"
                  android:label="@string/activity_name_stylize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="org.tensorflow.demo.SpeechActivity"
            android:screenOrientation="portrait"
            android:label="@string/activity_name_speech">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

download-models.gradle

/*
 * download-models.gradle
 *     Downloads model files from ${MODEL_URL} into application's asset folder
 * Input:
 *     project.ext.TMP_DIR: absolute path to hold downloaded zip files
 *     project.ext.ASSET_DIR: absolute path to save unzipped model files
 * Output:
 *     3 model files will be downloaded into given folder of ext.ASSET_DIR
 */
// hard coded model files
// LINT.IfChange
def models = ['inception_v1.zip',
              'object_detection/ssd_mobilenet_v1_android_export.zip',
              'stylize_v1.zip',
              'speech_commands_conv_actions.zip']
// LINT.ThenChange(//tensorflow/examples/android/BUILD)

// Root URL for model archives
def MODEL_URL = 'https://storage.googleapis.com/download.tensorflow.org/models'

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'de.undercouch:gradle-download-task:3.2.0'
    }
}
###################下面八行代码注释掉###############
//import de.undercouch.gradle.tasks.download.Download
//task downloadFile(type: Download){
//    for (f in models) {
//        src "${MODEL_URL}/" + f
//    }
//    dest new File(project.ext.TMP_DIR)
//    overwrite true
//}

task extractModels(type: Copy) {
    for (f in models) {
        def localFile = f.split("/")[-1]
        from zipTree(project.ext.TMP_DIR + '/' + localFile)
    }

    into file(project.ext.ASSET_DIR)
    fileMode  0644
    exclude '**/LICENSE'

    def needDownload = false
    for (f in models) {
        def localFile = f.split("/")[-1]
        if (!(new File(project.ext.TMP_DIR + '/' + localFile)).exists()) {
            needDownload = true
        }
    }
###################下面三行代码注释掉###############
//    if (needDownload) {
//        dependsOn downloadFile
//    }
}

tasks.whenTaskAdded { task ->
    if (task.name == 'assembleDebug') {
        task.dependsOn 'extractModels'
    }
    if (task.name == 'assembleRelease') {
        task.dependsOn 'extractModels'
    }
}

 

build.gradle

// This file provides basic support for building the TensorFlow demo
// in Android Studio with Gradle.
//
// Note that Bazel is still used by default to compile the native libs,
// and should be installed at the location noted below. This build file
// automates the process of calling out to it and copying the compiled
// libraries back into the appropriate directory.
//
// Alternatively, experimental support for Makefile builds is provided by
// setting nativeBuildSystem below to 'makefile'. This will allow building the demo
// on Windows machines, but note that full equivalence with the Bazel
// build is not yet guaranteed. See comments below for caveats and tips
// for speeding up the build, such as enabling ccache.
// NOTE: Running a make build will cause subsequent Bazel builds to *fail*
// unless the contrib/makefile/downloads/ and gen/ dirs are deleted afterwards.

// The cmake build only creates libtensorflow_demo.so. In this situation,
// libtensorflow_inference.so will be acquired via the tensorflow.aar dependency.

// It is necessary to customize Gradle's build directory, as otherwise
// it will conflict with the BUILD file used by Bazel on case-insensitive OSs.
project.buildDir = 'gradleBuild'
getProject().setBuildDir('gradleBuild')

buildscript {
    repositories {
        jcenter()
#####################加上下面四行代码################
        maven{
            url'https://maven.google.com'
        }
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'
        classpath 'org.apache.httpcomponents:httpclient:4.5.4'
    }
}

allprojects {
    repositories {
        jcenter()
##########加上下面一行代码#############
        google()
    }
}

// set to 'bazel', 'cmake', 'makefile', 'none'
##################把bazel改成none##############
def nativeBuildSystem = 'none'

// Controls output directory in APK and CPU type for Bazel builds.
// NOTE: Does not affect the Makefile build target API (yet), which currently
// assumes armeabi-v7a. If building with make, changing this will require
// editing the Makefile as well.
// The CMake build has only been tested with armeabi-v7a; others may not work.
def cpuType = 'armeabi-v7a'

// Output directory in the local directory for packaging into the APK.
def nativeOutDir = 'libs/' + cpuType

// Default to building with Bazel and override with make if requested.
def nativeBuildRule = 'buildNativeBazel'
def demoLibPath = '../../../bazel-bin/tensorflow/examples/android/libtensorflow_demo.so'
def inferenceLibPath = '../../../bazel-bin/tensorflow/contrib/android/libtensorflow_inference.so'

// Override for Makefile builds.
if (nativeBuildSystem == 'makefile') {
    nativeBuildRule = 'buildNativeMake'
    demoLibPath = '../../../tensorflow/contrib/makefile/gen/lib/android_' + cpuType + '/libtensorflow_demo.so'
    inferenceLibPath = '../../../tensorflow/contrib/makefile/gen/lib/android_' + cpuType + '/libtensorflow_inference.so'
}

// If building with Bazel, this is the location of the bazel binary.
// NOTE: Bazel does not yet support building for Android on Windows,
// so in this case the Makefile build must be used as described above.
def bazelLocation = '/usr/local/bin/bazel'

// import DownloadModels task
project.ext.ASSET_DIR = projectDir.toString() + '/assets'
project.ext.TMP_DIR   = project.buildDir.toString() + '/downloads'

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
##################此处将26.0.1改为28.0.3##############
    buildToolsVersion '28.0.3'
####################加上下面四行代码#################
    defaultConfig {
        applicationId = 'org.tensorflow.demo'
        minSdkVersion 21
        targetSdkVersion 23
    }
    if (nativeBuildSystem == 'cmake') {
        defaultConfig {
            applicationId = 'org.tensorflow.demo'
            minSdkVersion 21
            targetSdkVersion 23
            ndk {
                abiFilters "${cpuType}"
            }
            externalNativeBuild {
                cmake {
                    arguments '-DANDROID_TOOLCHAIN=gcc', '-DANDROID_STL=gnustl_static'
                }
            }
        }
        externalNativeBuild {
            cmake {
                path './jni/CMakeLists.txt'
            }
        }
    }

    lintOptions {
        abortOnError false
    }

    sourceSets {
        main {
            if (nativeBuildSystem == 'bazel' || nativeBuildSystem == 'makefile') {
                // TensorFlow Java API sources.
                java {
                    srcDir '../../java/src/main/java'
                    exclude '**/examples/**'
                }

                // Android TensorFlow wrappers, etc.
                java {
                    srcDir '../../contrib/android/java'
                }
            }
            // Android demo app sources.
            java {
                srcDir 'src'
            }

            manifest.srcFile 'AndroidManifest.xml'
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = [project.ext.ASSET_DIR]
            jniLibs.srcDirs = ['libs']
        }

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

task buildNativeBazel(type: Exec) {
    workingDir '../../..'
    commandLine bazelLocation, 'build', '-c', 'opt',  \
         'tensorflow/examples/android:tensorflow_native_libs',  \
         '--crosstool_top=//external:android/crosstool',  \
         '--cpu=' + cpuType,  \
         '--host_crosstool_top=@bazel_tools//tools/cpp:toolchain'
}

task buildNativeMake(type: Exec) {
    environment "NDK_ROOT", android.ndkDirectory
    // Tip: install ccache and uncomment the following to speed up
    // builds significantly.
    // environment "CC_PREFIX", 'ccache'
    workingDir '../../..'
    commandLine 'tensorflow/contrib/makefile/build_all_android.sh',  \
         '-s',  \
         'tensorflow/contrib/makefile/sub_makefiles/android/Makefile.in',  \
         '-t',  \
         'libtensorflow_inference.so libtensorflow_demo.so all'  \
         , '-a', cpuType  \
         //, '-T'  // Uncomment to skip protobuf and speed up subsequent builds.
}


task copyNativeLibs(type: Copy) {
    from demoLibPath
    from inferenceLibPath
    into nativeOutDir
    duplicatesStrategy = 'include'
    dependsOn nativeBuildRule
    fileMode 0644
}

tasks.whenTaskAdded { task ->
    if (nativeBuildSystem == 'bazel' || nativeBuildSystem == 'makefile') {
        if (task.name == 'assembleDebug') {
            task.dependsOn 'copyNativeLibs'
        }
        if (task.name == 'assembleRelease') {
            task.dependsOn 'copyNativeLibs'
        }
    }
}

// Download default models; if you wish to use your own models then
// place them in the "assets" directory and comment out this line.
apply from: "download-models.gradle"


dependencies {
    if (nativeBuildSystem == 'cmake' || nativeBuildSystem == 'none') {
##################此处将compile改为implementation###################
        implementation 'org.tensorflow:tensorflow-android:+'
    }
}

第四步:

因为android不会自动下载模型(因为你把上面的那个值设置为none了),所以需要先下载好模型,并放在指定文件夹中。

下载模型:https://download.csdn.net/download/qq_24800377/10689177

解压后如图:

将这四个压缩包放在gradleBuild/downloads下。

第五步:再次编译运行,ok

在第五步的时候,我第一次编译运行成功了,但是电脑突然蓝屏了吓我一跳,重启后,重新编译运行一次,问题解决。

参考来源:

https://blog.csdn.net/qq_24800377/article/details/82856708

https://blog.csdn.net/weixin_43325818/article/details/86529004

最后感谢各位大佬

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值