android studio 中的 Opencv 不起作用?

Opencv in android studio does not work?

我正在尝试将本机代码添加到我的 Android 应用程序中。 NDK 可以很好地处理简单的 C++ 代码,例如 "Hello from C++",但我需要使用 openCV,但我被卡住了。

项目构建输出:

:app:generateArmDebugSources UP-TO-DATE
:app:compileArmDebugJava UP-TO-DATE
:app:compileArmDebugNdk
D:/android-ndk-r10c/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/objs-debug/jni_part/D_\AndroidStudioProjects\OpenCVFeatureDetection\app\src\main\jni\jni_part.o: in function cv::Mat::~Mat():jni_part.cpp(.text._ZN2cv3MatD2Ev+0x3c): error: undefined reference to 'cv::fastFree(void*)'
D:/android-ndk-r10c/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/objs-debug/jni_part/D_\AndroidStudioProjects\OpenCVFeatureDetection\app\src\main\jni\jni_part.o: in function cv::Mat::release():jni_part.cpp(.text._ZN2cv3Mat7releaseEv+0x6c): error: undefined reference to 'cv::Mat::deallocate()'
D:/android-ndk-r10c/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/objs-debug/jni_part/D_\AndroidStudioProjects\OpenCVFeatureDetection\app\src\main\jni\jni_part.o: in function cv::FastFeatureDetector::~FastFeatureDetector():jni_part.cpp(.text._ZN2cv19FastFeatureDetectorD1Ev+0xa0): error: undefined reference to 'cv::FeatureDetector::~FeatureDetector()'
...25+ similar lines...
collect2: ld returned 1 exit status
make.exe: *** [D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/libjni_part.so] Error 1

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileArmDebugNdk'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    D:\android-ndk-r10c\ndk-build.cmd NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\Android.mk APP_PLATFORM=android-21 NDK_OUT=D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj NDK_LIBS_OUT=D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\lib NDK_DEBUG=1 APP_STL=stlport_static APP_ABI=armeabi-v7a
Error Code:
    2
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileArmDebugNdk'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    D:\android-ndk-r10c\ndk-build.cmd NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\inter

mediates\ndk\arm\debug\Android.mk APP_PLATFORM=android-21 NDK_OUT=D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj NDK_LIBS_OUT=D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\lib NDK_DEBUG=1 APP_STL=stlport_static APP_ABI=armeabi-v7a
Error Code:
    2
Output:
    D:/android-ndk-r10c/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/objs-debug/jni_part/D_\AndroidStudioProjects\OpenCVFeatureDetection\app\src\main\jni\jni_part.o: in function cv::Mat::~Mat():jni_part.cpp(.text._ZN2cv3MatD2Ev+0x3c): error: undefined reference to 'cv::fastFree(void*)'
    D:/android-ndk-r10c/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/objs-debug/jni_part/D_\AndroidStudioProjects\OpenCVFeatureDetection\app\src\main\jni\jni_part.o: in function cv::Mat::release():jni_part.cpp(.text._ZN2cv3Mat7releaseEv+0x6c): error: undefined reference to 'cv::Mat::deallocate()'
    D:/android-ndk-r10c/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/objs-debug/jni_part/D_\AndroidStudioProjects\OpenCVFeatureDetection\app\src\main\jni\jni_part.o: in function cv::FastFeatureDetector::~FastFeatureDetector():jni_part.cpp(.text._ZN2cv19FastFeatureDetectorD1Ev+0xa0): error: undefined reference to 'cv::FeatureDetector::~FeatureDetector()'
    ...and 25+ similar lines again...
collect2: ld returned 1 exit status
    make.exe: *** [D:\AndroidStudioProjects\OpenCVFeatureDetection\app\build\intermediates\ndk\arm\debug\obj/local/armeabi-v7a/libjni_part.so] Error 1


* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.



 BUILD FAILED

Total time: 12.261 secs

我注意到了一个类似的问题,但我仍然没有找到解决方案。我做错了什么?

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.gogiant.opencvfeaturedetection"
        minSdkVersion 15
        targetSdkVersion 21
    versionCode 1
    versionName "1.0"

    ndk {
        moduleName "jni_part"
        cFlags "-DANDROID_NDK"
        ldLibs "log"
        stl "stlport_static"
    }
}

buildTypes {
    release {

        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }

    // make per-variant version code
    applicationVariants.all { variant ->
        // get the single flavor
        def flavorVersion = variant.productFlavors.get(0).versionCode

        // set the composite code
        variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig.versionCode
    }

    productFlavors {
        x86 {
            ndk {
                abiFilter "x86"
            }

            // this is the flavor part of the version code.
            // It must be higher than the arm one for devices supporting
            // both, as x86 is preferred.
            versionCode = 3
        }
        arm {
            ndk {
                abiFilter "armeabi-v7a"
            }
            versionCode = 2
        }
        mips {
            ndk {
                abiFilter "mips"
            }
            versionCode = 1
        }
        fat {
            // fat binary, lowest version code to be
            // the last option
            versionCode = 0
        }
    }

        debug.jniDebuggable true
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.android.support:support-v4:21.0.3'
    compile project(':libraries:opencv')
}

Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
OPENCV_LIB_TYPE:=STATIC
OPENCV_INSTALL_MODULES:=on
OPENCV_CAMERA_MODULES:=off


include D:\OpenCV-2.4.9-android-sdk\sdk\native\jni\OpenCV.mk

LOCAL_C_INCLUDES += D:\AndroidStudioProjects\OpenCVFeatureDetection\libraries\opencv\include


LOCAL_MODULE    := jni_part
LOCAL_SRC_FILES := jni_part.cpp

LOCAL_STATIC_LIBRARIES += libopencv_contrib libopencv_legacy libopencv_ml libopencv_stitching libopencv_nonfree libopencv_objdetect libopencv_videostab libopencv_calib3d libopencv_photo libopencv_video libopencv_features2d libopencv_highgui libopencv_androidcamera libopencv_flann libopencv_imgproc libopencv_ts libopencv_core

LOCAL_LDLIBS +=  -llog -ldl
include $(BUILD_SHARED_LIBRARY)

Application.mk

APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -fexceptions
APP_ABI := all
APP_PLATFORM := android-8

项目结构:http://i.stack.imgur.com/Yg5Jl.png 完成项目:https://yadi.sk/d/brR5GUjber2Qo

感谢您的帮助。

您是否尝试过使用 Eclipse 构建您的项目?我在 Intellij 上用 OpenCV 做了一些工作,但遇到了一些麻烦,这也是 NDK 的问题。

我测试了你的项目。为了成功构建,我必须删除文件夹 app/src/main/jni 和文件夹 app/src/main/3rdparty 以及文件夹 app/libs/ 中的文件 opencvlibrary-2.4.9.jar。看起来你的项目中有几个 opencv 库(因此相互冲突)。

希望对您有所帮助。

Android Studio 和 Android gradle 插件 1.1.0 中当前的 NDK 支持受到限制且已弃用。即时使用自动生成的 Makefile,不支持开箱即用地从您的 NDK 源链接外部 NDK 库(如 OpenCV)。

您应该删除 build.gradle 中的 ndk{} 块并停用当前的 NDK 集成,以便直接依赖 ndk-build 和您的 Makefile。您还可以使用 splits 而不是 flavors 来生成 per-ABI APK,就像这个要点:https://gist.github.com/ph0b/9e59058ac59cac104398

你的 build.gradle 会是这样的:

import org.apache.tools.ant.taskdefs.condition.Os

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.gogiant.opencvfeaturedetection"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }

    sourceSets.main {
        jniLibs.srcDir 'src/main/libs'
        jni.srcDirs = [] //disable automatic ndk-build call
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    splits {
        abi {
            enable true
            reset()
            include 'x86', 'armeabi-v7a', 'mips' //select ABIs to build APKs for
            universalApk true //generate an additional APK that contains all the ABIs
        }
    }

    project.ext.versionCodes = ['armeabi':1, 'armeabi-v7a':2, 'arm64-v8a':3, 'mips':5, 'mips64':6, 'x86':8, 'x86_64':9] //versionCode digit for each supported ABI, with 64bit>32bit and x86>armeabi-*

    android.applicationVariants.all { variant ->
    // assign different version code for each output
        variant.outputs.each { output ->
            output.versionCodeOverride =
 project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 1000000 + defaultConfig.versionCode
        }
    }

    // call regular ndk-build(.cmd) script from app directory
    task ndkBuild(type: Exec) {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
        } else {
            commandLine 'ndk-build', '-C', file('src/main').absolutePath
        }
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.android.support:support-v4:21.0.3'
    compile project(':libraries:opencv')
}