Android Studio3.0,在原有项目中进行ndk配置

1.配置NDK路径,如下:

File->Project Struture->SDK Location

2.更改app下的build.gradle文件

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.sunmi.opencv.camera"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    //add ndk begin
    sourceSets.main {
        jniLibs.srcDirs = ['libs']
        jni.srcDirs = []
    }
    externalNativeBuild {

        // Encapsulates your CMake build configurations.
        cmake {

            // Provides a relative path to your CMake build script.
            path "CMakeLists.txt"
        }
    }
    //add ndk end

}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation project(':openCVLibrary343')
}

task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

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

3.在app目录下添加CMakeLists.txt文件:

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

cmake_minimum_required(VERSION 3.4.1)

include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include)

add_library(libopencv_java3 SHARED IMPORTED)
set_target_properties(libopencv_java3 PROPERTIES IMPORTED_LOCATION
            ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libopencv_java3.so)

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 )

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 )

target_link_libraries( # Specifies the target library.
                       native-lib
                       libopencv_java3

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

4.在app/src/main目录下创建cpp目录,并添加native-lib.cpp文件,内容如下:

#include <jni.h>
#include <android/log.h>
#define ALOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"Jon",FORMAT,##__VA_ARGS__);

extern "C"
JNIEXPORT jstring JNICALL
Java_com_sunmi_opencv_camera_MainActivity_stringFromC(JNIEnv *env, jobject instance){
    ALOGE("Java_sunmi_opencv_camera_MainActivity_stringFromC");
    return env->NewStringUTF("hello NDK From C");
}

方法名遵循Java_com_包名_java类名_java方法名(JNIEnv *env, jobject instance)
5.在Java中调用

package com.sunmi.opencv.camera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button gray = null;
    private static final String TAG = "OpenCV.Jon";
    private ImageView imageView = null;
    private Button camera = null;
    static{
        System.loadLibrary("native-lib");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gray = findViewById(R.id.gray);
        gray.setOnClickListener(this);
        imageView = findViewById(R.id.gray_image);
        camera = findViewById(R.id.camera);
        camera.setOnClickListener(this);
        initOpenCVLibs();
        stringFromC();
    }

    private void initOpenCVLibs() {

        boolean Status =  OpenCVLoader.initDebug();
        if(Status != true)
        {
            Log.e(TAG, "OpenCV Init Failed");
        }else{
            Log.e(TAG, "OpenCV Init Success");
        }
    }
    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.gray)
        {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmap bitmap = null;
            bitmap = BitmapFactory.decodeResource(this.getResources(), R.raw.girl, options);
            Mat src = new Mat();
            Utils.bitmapToMat(bitmap,src);
            Imgproc.cvtColor(src,src,Imgproc.COLOR_BGR2GRAY);
            Utils.matToBitmap(src,bitmap);
            imageView.setImageBitmap(bitmap);
            src.release();
        }else if(view.getId() == R.id.camera) {
            Log.e(TAG,"OpenCamera");
            Intent intent = new Intent(this.getApplicationContext(),CameraOpenCV.class);
            startActivity(intent);
        }
    }
    public native String stringFromC();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值