1. 程式人生 > >Android Studio 導入OpenCV 並調試運行face-detection例子

Android Studio 導入OpenCV 並調試運行face-detection例子

pac oot tools property boolean adl cond dto rgb

Android Studio 導入OpenCV 並調試運行

face-detection例子


系統:Ubuntu 14.04

Studio版本:2.3.3

OpenCV版本:2.4.11

第一部分 將OpenCV導入到項目中

1.Google Android 開發中文網站上下載 Android Studio,下載完成後配置SDKNDK

下載地址:https://developer.android.google.cn/studio/index.html

2.下載OpenCV android開發SDK,並解壓

文件名:OpenCV-2.4.11-android-sdk.zip

下載地址:http://sourceforge.net/projects/opencvlibrary/files/opencv-android/2.4.11/OpenCV-2.4.11-android-sdk.zip/download


3.新創建一個的項目

Name :FaceDetection

Minimum SDK : API22

Empty Activity : MainActivity


4.OpenCV導入項目中

File->New->import Module

Source-directory:{unzip-dir}/adk/java

Module name:默認不用修改

技術分享

NEXT

這一頁全部默認,然後Finish

技術分享

可能會報如下錯誤

原因是OpenCVbuild.gradle裏指定的Android SDK 版本跟 本項目的build.gradle裏設置的版本不一致

技術分享

將兩個文件裏面下面這幾個配置改成一樣:

compileSDKVersion / buildToolsVersion / minSdkVersion / targetSdkVersion

然後在OpenCVbuild.gradleTry Again,錯誤解決。

技術分享

5.復制OpenCV Native lib到項目中

復制{unzip-dir}/sdk/native/libs到項目{project_name}/openCVLibrary2441/src/main/目錄下,重命名為jniLibs

技術分享

6.設置Module依賴

File->Project Structure->app->Dependencies

技術分享

+->3.Module dependency->選:openCVLibrary2411

技術分享

7.如果APP5.0以上的話,需要修改FaceDetection/openCVLibrary2411/src/main/java/org/opencv/android/AsyncServiceHelper.java中的initOpenCV方法.

新方法代碼如下:

public static boolean initOpenCV(String Version, final Context AppContext,
                                 final LoaderCallbackInterface Callback) {
    AsyncServiceHelper helper = new AsyncServiceHelper(Version, AppContext,
            Callback);
    Intent intent = new Intent("org.opencv.engine.BIND");
    intent.setPackage("org.opencv.engine");
    if (AppContext.bindService(intent, helper.mServiceConnection,
            Context.BIND_AUTO_CREATE)) {
        return true;
    } else {
        AppContext.unbindService(helper.mServiceConnection);
        InstallService(AppContext, Callback);
        return false;
    }
}

到此為止就把OpenCV SDK加載到項目中了,可以在項目使用OpenCV了。

第二部分 調試運行OpenCV SDK中的 face-detection例子

1.face-detectionjava代碼和res資源復制到項目 app下對應的目錄中

{unzip-dir}/OpenCV-android-sdk/samples/face-detection/src/org/opencv/samples/facedetect

{unzip-dir}/OpenCV-android-sdk/samples/face-detection/res

技術分享

2. 編譯C++代碼

face-detectionC++代碼目錄復制到app/main

{unzip-dir}/OpenCV-android-sdk/samples/face-detection/jni

技術分享

將編譯用的文件復制到項目根目錄

{unzip-dir}/OpenCV-android-sdk/sdk/native

技術分享

修改jni下的Android.mk文件,內容如下

註意OpenCV.mk的路徑(紅字部分)

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
OpenCV_INSTALL_MODULES := on
OpenCV_CAMERA_MODULES := off
OPENCV_LIB_TYPE :=STATIC
ifeq ("$(wildcard $(OPENCV_MK_PATH))","")
include ../../../../native/jni/OpenCV.mk
else
include $(OPENCV_MK_PATH)
endif
LOCAL_MODULE := detection_based_tracker
LOCAL_SRC_FILES :=DetectionBasedTracker_jni.cpp
LOCAL_LDLIBS +=  -lm -llog
include $(BUILD_SHARED_LIBRARY)

DetectionBasedTracker_jni.cpp DetectionBasedTracker_jni.h裏,對應的包信息根據項目的實際情況修改一下,內容如下紅色部分:(會有很多處,建議整體替換)

原:JNIEXPORT jlong JNICALL Java_org_opencv_samples_facedetect_DetectionBasedTracker_nativeCreateObject

現:JNIEXPORT jlong JNICALL Java_cn_com_grufield_facedetection_DetectionBasedTracker_nativeCreateObject

技術分享

app中的build.gradledeandroid標簽中加入如下內容:

sourceSets.main.jni.srcDirs = []
sourceSets.main.jniLibs.srcDirs = [‘src/main/libs‘,‘src/main/jniLibs‘]

task ndkBuild(type: Exec, description: ‘Compile JNI source with NDK‘) {
    Properties properties = new Properties()
    properties.load(project.rootProject.file(‘local.properties‘).newDataInputStream())
    def ndkDir = properties.getProperty(‘ndk.dir‘)
    if (org.apache.tools.ant.taskdefs.condition.Os.isFamily(org.apache.tools.ant.taskdefs.condition.Os.FAMILY_WINDOWS)) {
        commandLine "$ndkDir/ndk-build.cmd", ‘-C‘, file(‘src/main/jni‘).absolutePath
    } else {
        commandLine "$ndkDir/ndk-build", ‘-C‘, file(‘src/main/jni‘).absolutePath
    }
}
tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}
task ndkClean(type: Exec, description: ‘Clean NDK Binaries‘) {
    Properties properties = new Properties()
    properties.load(project.rootProject.file(‘local.properties‘).newDataInputStream())
    def ndkDir = properties.getProperty(‘ndk.dir‘)
    if (org.apache.tools.ant.taskdefs.condition.Os.isFamily(org.apache.tools.ant.taskdefs.condition.Os.FAMILY_WINDOWS)) {
        commandLine "$ndkDir/ndk-build.cmd",‘clean‘, ‘-C‘, file(‘src/main/jni‘).absolutePath
    } else {
        commandLine "$ndkDir/ndk-build",‘clean‘, ‘-C‘, file(‘src/main/jni‘).absolutePath
    }
}
clean.dependsOn ‘ndkClean‘

技術分享

在右面Gradle projects中找到ndkBuild,雙擊ndkBuild,編譯C++代碼

FaceDetection->:app->Taks->other->ndkBuild

技術分享

log如下則編譯成功

技術分享

3.修改AndroidManifest.xml文件

{unzip-dir}/OpenCV-android-sdk/samples/face-detection/AndroidManifest.xml中內容替換項目到項目的AndroidManifest.xml

內容如下:

    <application
        android:label="@string/app_name"
        android:icon="@drawable/icon"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

        <activity android:name="FdActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:configChanges="keyboardHidden|orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <supports-screens android:resizeable="true"
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:anyDensity="true" />

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.CAMERA"/>

    <uses-feature android:name="android.hardware.camera" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
    <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>

技術分享

到此為止導入完成

4.運行程序

技術分享

運行結果如下:

OK完成了

Android Studio 導入OpenCV 並調試運行face-detection例子