android studio之OpenCV(native)使用

参考博文:http://blog.csdn.net/sbsujjbcy/article/details/49520791

  • 拷贝OpenCV SDK下的native到工程的根目录下,如下图

这里写图片描述

  • 在main下创建jni目录,如图所示:

这里写图片描述

  • jni下创建android.mk和application.mk,编辑文件,内容如下:

android.mk

# Copyright (C) 2009 The Android Open Source Project
#
# 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.
#
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

OpenCV_INSTALL_MODULES := on
OpenCV_CAMERA_MODULES := off

OPENCV_LIB_TYPE := SHARED

ifeq ("$(wildcard $(OPENCV_MK_PATH))","")
include ../../../../native/jni/OpenCV.mk
else
include $(OPENCV_MK_PATH)
endif

LOCAL_MODULE    := OpenCV
LOCAL_SRC_FILES := IDCardRecognizeUtil.cpp\ com_hodi_hodi_opencv_OpenCVHelper.cpp
*[注意:所有要调用的C++/C类都要在这添加才可以使用]*

LOCAL_LDLIBS +=  -lm -llog

LOCAL_LDLIBS += -landroid
*【注意:landroid 可以调试打印出android的log信息,否则不行】*

include $(BUILD_SHARED_LIBRARY)

application.mk

APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -fexceptions
APP_ABI := all
【App_ABI:声明针对哪些cpu架构的.so】
  • 修改app/build.gradle,内容如下:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "com.hodi.hodi_opencv"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets.main.jni.srcDirs = []
    //禁止自带的ndk功能
    *【添加这行jni目录由蓝色变位黄色】*
    sourceSets.main.jniLibs.srcDirs = ['src/main/libs','src/main/jniLibs']
    //重定向so目录为src/main/libs,原来为src/main/jniLibs

    clean.dependsOn 'ndkClean'
}

task ndkBuild(type:Exec, group:'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, group:'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",'clean', '-C', file('src/main/jni').absolutePath
    } else {
        commandLine "$ndkDir/ndk-build",'clean', '-C', file('src/main/jni').absolutePath
    }
}

  • 创建一个native类,内容如下:
public class OpenCVHelper {
    static {
        System.loadLibrary("OpenCV");
    }
    public static native int[] gray(int[] buf, int w, int h);
    public static native int[] imageToGray(String path);

}
  • **再terminal ,输入javah -d jni -classpath [class路劲]
    com.hodi.hodi_opencv.OpenCVHelper生成.h**
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_hodi_hodi_opencv_OpenCVHelper */

#ifndef _Included_com_hodi_hodi_opencv_OpenCVHelper
#define _Included_com_hodi_hodi_opencv_OpenCVHelper
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_hodi_hodi_opencv_OpenCVHelper
 * Method:    recognizeIDCard
 * Signature: (Ljava/lang/String;Ljava/lang/String;)Z
 */
JNIEXPORT jstring JNICALL Java_com_hodi_hodi_1opencv_OpenCVHelper_recognizeIDCard
  (JNIEnv *, jclass, jobject,jstring, jstring);


#ifdef __cplusplus
}
#endif
#endif
  • 创建对应.h的实现类.cpp或.c
//
// Created by AA on 2016/11/18.
//

#include "com_hodi_hodi_opencv_OpenCVHelper.h"
#include "IDCardRecognizeUtil.h"

#include <string.h>

#include <Android/log.h>
#include <Android/asset_manager.h>
#include <Android/asset_manager_jni.h>

#define TAG "cn.linjk.ihouse.jni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__)
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__)

////////////////////////////////////////////////////////////////////////////////

extern "C" {
JNIEXPORT jstring JNICALL Java_com_hodi_hodi_1opencv_OpenCVHelper_recognizeIDCard
        (JNIEnv *, jclass, jobject,jstring, jstring);


////////////////////////////////////////////////////////////////////////////
JNIEXPORT jintArray JNICALL Java_com_hodi_hodi_1opencv_OpenCVHelper_gray(
        JNIEnv *env, jclass obj, jintArray buf, int w, int h) {

    jint *cbuf;
    cbuf = env->GetIntArrayElements(buf, JNI_FALSE );//将JNI数组转换为基本类型数组
    if (cbuf == NULL) {
        return 0;
    }

    Mat imgData(h, w, CV_8UC4, (unsigned char *) cbuf);

    uchar* ptr = imgData.ptr(0);
    for(int i = 0; i < w*h; i ++){
        //计算公式:Y(亮度) = 0.299*R + 0.587*G + 0.114*B
        //对于一个int四字节,其彩色值存储方式为:BGRA
        int grayScale = (int)(ptr[4*i+2]*0.299 + ptr[4*i+1]*0.587 + ptr[4*i+0]*0.114);
        ptr[4*i+1] = grayScale;
        ptr[4*i+2] = grayScale;
        ptr[4*i+0] = grayScale;
    }

    int size = w * h;
    jintArray result = env->NewIntArray(size);//生成新的数组
    env->SetIntArrayRegion(result, 0, size, cbuf);//为result赋值
    env->ReleaseIntArrayElements(buf, cbuf, 0);//释放内存
    return result;
}

}
  • 执行task ndkBuild,生成.so库
task ndkBuild(type:Exec, group:'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
    }
}
  • 在测试类调用,调用成功即可
package com.hodi.hodi_opencv;

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


public class MainActivity extends AppCompatActivity {

    private Button btn;
    private ImageView img;
    private Button btn_id;

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

        initView();
    }

    private void initView() {
        btn= (Button) findViewById(R.id.btn);
        img= (ImageView) findViewById(R.id.img);
        btn_id = (Button) findViewById(R.id.bt_id_card);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(
                        R.drawable.im)).getBitmap();

                int w = bitmap.getWidth();
                int h = bitmap.getHeight();

                int[] pix = new int[w * h];

                bitmap.getPixels(pix, 0, w, 0, 0, w, h);
                int [] resultPixes = OpenCVHelper.gray(pix,w,h);
                Bitmap result = Bitmap.createBitmap(w,h, Bitmap.Config.RGB_565);
                result.setPixels(resultPixes, 0, w, 0, 0,w, h);
                img.setImageBitmap(result);
            }
        });
}


}

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值