AndroidはOpenCV構成メソッドを呼び出します

1.環境

Windows10
Android Studio 3.0
Android NDK:android-ndk-r16b
Opencv3.2.0

2.準備

Android studio3.0、android-ndk-r16bをダウンロードし、リンクをダウンロードします:http://www.androiddevtools.cn/index.html

opencv-3.2.0-android-sdk.zipパッケージをダウンロードし、ダウンロードリンクを解凍します:https://opencv.org/releases.html

3.サンプルプロジェクトの構築を開始します

新しいAndroidプロジェクトを作成し、[C ++サポートを含める]をオンにして、最後まで次へ進みます。

最初にエラーがある可能性があります。おそらくndkが見つかりません。解決策は、ndkパスを追加することです。
[ファイル]-> [プロジェクト構造]をクリックします



Android studio2.3以降は、NDKプロジェクトを自動的に作成して開発時間を節約できるC ++サポートオプションをサポートしています。
プロジェクトが作成された後、cppフォルダーがsrc / main /の下に自動的に作成され、native-lib.cppファイルがその下に作成されていることがわかります。

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_example_v_1fanlulin_testdemoforopencv_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

内部にはサンプル関数があり、C ++を使用して文字列「HellofromC ++」を返します。
このメソッドは、Jniを介してAndroidJavaコードから呼び出すことができます。

Javaコードでのアプローチは次のとおりです。

package com.example.v_fanlulin.testdemoforopencv;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.4000106090
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}


沿って

static {
    System.loadLibrary("native-lib");
}

native-libライブラリをロードします。

沿って

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
public native String stringFromJNI();

ネイティブメソッドが宣言されており、native-lib.cppに実装されています。

c ++コードとjavaコードでは、c ++を呼び出すjavaを実装するには、c ++を動的ライブラリにコンパイルする必要があります。これには、c ++コードをjavaで呼び出すことができる動的ライブラリにコンパイルするために使用される重要なファイルCMakeLists.txtが必要です。ライブラリ、パス、ソースファイル、およびコンパイルに必要なその他の情報を宣言します。

CMakeLists.txtの完全なコンテンツは次のとおりです。

   # For more information about using CMake with Android Studio, read the
    # documentation: https://d.android.com/studio/projects/add-native-code.html
    
    # Sets the minimum version of CMake required to build the native library.
    
    cmake_minimum_required(VERSION 3.4.1)
    
    # Creates and names a library, sets it as either STATIC
    # or SHARED, and provides the relative paths to its source code.
    # You can define multiple libraries, and CMake builds them for you.
    # Gradle automatically packages shared libraries with your APK.
    
    add_library( # Sets the name of the library.
                 native-lib
    
                 # Sets the library as a shared library.
                 SHARED
    
                 # Provides a relative path to your source file(s).
                 src/main/cpp/native-lib.cpp )
    
    # Searches for a specified prebuilt library and stores the path as a
    # variable. Because CMake includes system libraries in the search path by
    # default, you only need to specify the name of the public NDK library
    # you want to add. CMake verifies that the library exists before
    # completing its build.
    
    find_library( # Sets the name of the path variable.
                  log-lib
    
                  # Specifies the name of the NDK library that
                  # you want CMake to locate.
                  log )
    
    # Specifies libraries CMake should link to your target library. You
    # can link multiple libraries, such as libraries you define in this
    # build script, prebuilt third-party libraries, or system libraries.
    
    target_link_libraries( # Specifies the target library.
                           native-lib
    
                           # Links the target library to the log library
                           # included in the NDK.
                           ${log-lib} )

この時点で、AndroidでC ++コードを呼び出すすべてのコンポーネントが完成しています。opencvコードの呼び出しについても同じことが言えます。


4.opencvライブラリを統合します

4.1opencvライブラリをインポートする

opencv-3.2.0-android-sdk \ OpenCV-android-sdk \ sdk \ nativeの下にあるlibsフォルダーをプロジェクトのメインディレクトリにコピーし、名前をjniLibsに変更します。

4.2配置CMakeLists.txt

opencvのパスを設定し、ネイティブの依存関係を構成し、libopencv_java3.soファイルをインポートして、最後にtarget_link_librariesでlib_opencvをリンクします。
完全なCMakeLists.txtは次のとおりです。

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

set(pathToOpenCv E:/Android/opencv-3.2.0-android-sdk/OpenCV-android-sdk)#设置OpenCv的路径变量
# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

#支持-std=gnu++11
set(CMAKE_VERBOSE_MAKEFILE on)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
#配置加载native依赖
include_directories(${pathToOpenCv}/sdk/native/jni/include)

set(CURRENT_DIR ${CMAKE_SOURCE_DIR})
# 在Gradle Console输出信息
# CMAKE_SOURCE_DIR:
message("CURRENT_DIR:" ${CMAKE_SOURCE_DIR})

#动态方式加载
add_library(lib_opencv STATIC IMPORTED ) #表示创建一个导入库,静态方式
#引入libopencv_java3.so文件
set_target_properties(lib_opencv
                       PROPERTIES
                       IMPORTED_LOCATION ${CURRENT_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java3.so
                       )

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib}
                       android -ljnigraphics lib_opencv)

4.3コードの宣言と実装

MainActivityで呼び出すネイティブメソッドを宣言します。たとえば、画像のぼかしメソッドを呼び出します。

public native int[] imgBlur();

宣言後、cppで実装する必要があります。コードプロンプトalt + enterを使用して、native-lib.cppで関数のjni宣言と関数本体を直接生成すると非常に便利です。

関数に対応するopencvコードを記述するだけで、画像処理を実行できます。

書き込み後、完全なnative-lib.cppファイルは次のようになります。

#include <jni.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_example_v_1fanlulin_testdemoforopencv_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

extern "C"
JNIEXPORT jintArray JNICALL
Java_com_example_v_1fanlulin_testdemoforopencv_MainActivity_imgBlur(JNIEnv *env, jobject instance,
                                                                    jintArray buf, jint w,
                                                                    jint h) {
    jint *cbuf = env->GetIntArrayElements(buf, JNI_FALSE );
    if (cbuf == NULL) {
        return 0;
    }

    Mat imgData(h, w, CV_8UC4, (unsigned char *) cbuf);
    /*图像处理开始*/
    cvtColor(imgData,imgData,CV_BGRA2BGR);
    blur(imgData,imgData,Size(20,20));
    cvtColor(imgData,imgData,CV_BGR2BGRA);
    /*图像处理结束*/
    uchar *ptr = imgData.data;
    int size = w * h;
    jintArray result = env->NewIntArray(size);
    env->SetIntArrayRegion(result, 0, size, (const jint *)ptr);
    env->ReleaseIntArrayElements(buf, cbuf, 0);
    return result;
}

MainActivityでネイティブメソッドを呼び出します。完全なコードは次のとおりです。

package com.example.v_fanlulin.testdemoforopencv;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.4000106090
    static {
        System.loadLibrary("native-lib");
    }

    private ImageView mImageView;
    private Bitmap bitmapBack;//用于备份的bitmap

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView =  (ImageView) findViewById(R.id.iv);
    }

    /**
     * 恢复为原图
     * @param view
     */
    public void converToOrig(View view) {
        //直接从备份的bitmapBack拿图片
        if(bitmapBack==null){
            bitmapBack = BitmapFactory.decodeResource(getResources(), R.mipmap.genie);

        }
        mImageView.setImageBitmap(bitmapBack);

    }

    /**
     * 模糊图像
     * @param view
     */
    public void converToBlur(View view) {
        //从imageview上获取bitmap图片
        mImageView.setDrawingCacheEnabled(true);
        Bitmap bitmap = mImageView.getDrawingCache();

        int w=bitmap.getWidth(),h=bitmap.getHeight();
        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);
        //调用native函数,模糊图像
        int[] resultInt=imgBlur(pix, w, h);
        Bitmap resultImg=Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        resultImg.setPixels(resultInt, 0, w, 0, 0,w, h);
        mImageView.setDrawingCacheEnabled(false);
        mImageView.setImageBitmap(resultImg);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    public native int[] imgBlur(int[] buf,int w,int h);
}

4.3操作効果

元の画像:
元の画像

ぼかした後:

ぼかし後

5.発生する可能性のあるその他のエラーと解決策

5.1パッケージの競合

Error:Execution failed for task ':app:preDebugAndroidTestBuild'.
>Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

解決策:
アプリのbuild.gradleの依存関係に追加します。

  androidTestCompile('com.android.support:support-annotations:26.1.0'){
        force = true
 }

参考記事:https//www.jianshu.com/p/9f5758c36b34

おすすめ

転載: blog.csdn.net/fxjzzyo/article/details/86650133