AndroidStudio NDK之使用OpenCV

目录

  • 一、前言
  • 二、OpenCV介绍
  • 三、OpenCV模块介绍
  • 四、运行环境
  • 五、准备工作
  • 六、编译所需so
  • 七、遇到的问题及其解决方法
  • 八、效果图

一、前言

为了将c++代码移植到Android,并且c++里面用的是opencv,那么就需要在android里面通过底层调用opencv。

二、OpenCV介绍

OpenCV是一个基于开源的跨平台计算机视觉库,实现了许多图像处理和计算机视觉方面的通用算法,是计算机视觉领域最有力的研究工具之一。
OpenCV应用领域: 人机互动 物体识别 图像分割 人脸识别 动作识别 运动跟踪 机器人 运动分析 机器视觉 结构分析 汽车安全驾驶 自动驾驶。。。

三、OpenCV模块介绍

  • 1.core,核心功能模块,主要包含如下的内容:
      OpenCV基本数据结构(Basic Structures);
      基本的C语言数据结构和操作(Basic C Structures and Operations);
      动态数据结构(DynamicStructures);
      数组操作相关函数(Operations on Arrays);
      绘图功能(Drawing Functions);
      XML和YAML语法的支持(XML/YAML Persistence);
      XML和YAML语法的支持的C语言接口(XML/YAML Persistence (C API));
      聚类(Clustering);
      辅助功能与系统函数和宏(Utility and System Functions and Macros);
      与OpenGL的互操作(OpenGL interoperability);
  • 2.imgproc,是Image Processing的简写。图像处理模块,主要包含以下内容:
      线性和非线性的图像滤波(Image Filtering);
      图像的几何变换(Geometric ImageTransformations);
      图像的其他变换(Miscellaneous Image Transformations);
      直方图(Histograms);
      结构分析和形状描述(Structural Analysis and Shape Descriptors);
      运动分析和目标跟踪(Motion Analysis and Object Tracking);
      特征检测(Feature Detection);
      目标检测(Object Detection);
  • 3.highgui,是High-level GUI and Media I/O的简写。高层用户界面模块和媒体输入/输出模块,主要包含以下内容:
      用户界面(User Interface);
      图片和视频的读写(Reading and Writing Images and Video);
      QT新功能(Qt New Functions);
  • 4.features2d,是2D Features Framework的简写。二维特征框架模块,主要包含以下内容:
      人脸识别
      VR和AR
      特征的检测和描述(Feature Detection and Description);
      特征检测器的通用接口(Common Interfaces of Feature Detectors);
      描述符提取器的通用接口(Common Interfaces of Descriptor Extractors);
      描述符匹配器的通用接口(Common Interfaces of Descriptor Matchers);
      通用描述符匹配器通用接口(Common Interfaces of Generic Descriptor Matchers);
      关键点和匹配结果的绘制功能(Drawing Function of Keypoints and Matches);
      目标分类(Object Categorization);
  • 5.flann,Clustering and Search in Multi-Dimensional Spaces,多维空间聚类和搜索模块,
    主要包含以下内容:
    • 快速近视最近邻搜索(Fast Approximate Nearest Neighbor Search);
    • 聚类(Clustering);
  • 6.video,是Video Analysis的简写。视频分析模块,主要包含以下内容:
       运动分析和目标跟踪(Motion Analysis and Object Tracking),视频相关的,上面提到的是图片相关的;
  • 7.calib3d ,是Camera Calibration and 3D
     Reconstruction的简写。这个模块主要是相机校准和三维重建相关的内容,包括基本的多视角几何算法、单个立体摄像头标定、物体姿态估计、立体相似性算法,3D信息的重建等。

四、运行环境

  • Android Studio 3.3.2
  • opencv-4.0.1-android-sdk.zip
  • NDK

五、准备工作

1、首先我们去下载:
https://opencv.org/releases.html
 opencv-4.0.1-android-sdk
2、点击Android pack下载opencv-4.0.1-android-sdk.zip
然后解压到目录下
目录结构
3、启动Android Studio ,在SDK Manager下安装好CMake\LLDB\NDK
CMake\LLDB\NDK
4、创建工程(创建步骤这里省略)
5、开始配置opencv
在src/main下创建jni(用于存放我们写的c++代码),然后复制下载的OpenCV-android-sdk\sdk\native\jni目录下的include 到jni目录
同时别忘记复制sdk\native\libs 到工程中的jniLibs目录下
6 开始写c/c++文件
首先创建一个java类

package com.cayden.opencvtest;
/**
 * Created by caydencui on 2019/3/27.
 */
public class NativeLib {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public static native int[] Bitmap2Grey(int[] pixels,int w,int h);
}

然后在jni目录下创建文件native-lib.cpp

//
// Created by caydencui on 2019/3/27.
//
#include <jni.h>
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;

extern "C" JNIEXPORT jintArray

JNICALL
Java_com_cayden_opencvtest_NativeLib_Bitmap2Grey(
        JNIEnv *env,
        jobject /* this */,jintArray buf,jint w,jint h) {
    jint *cbuf;
    jboolean ptfalse = false;
    cbuf = env->GetIntArrayElements(buf, &ptfalse);
    if(cbuf == NULL){
        return 0;
    }

    Mat imgData(h, w, CV_8UC4, (unsigned char*)cbuf);
    // 注意,Android的Bitmap是ARGB四通道,而不是RGB三通道
    cvtColor(imgData,imgData,CV_BGRA2GRAY);
    cvtColor(imgData,imgData,CV_GRAY2BGRA);

    int size=w * h;
    jintArray result = env->NewIntArray(size);
    env->SetIntArrayRegion(result, 0, size, (jint*)imgData.data);
    env->ReleaseIntArrayElements(buf, cbuf, 0);
    return result;
}

7 创建CMakeLists.txt【很重要的哦,因为cmake会找这个文件然后进行编译】
里面的很多属性 可以看一下英文大概知道什么意思

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# 设置CMAKE的版本号
cmake_minimum_required(VERSION 3.4.1)

# 设置include文件夹的地址
include_directories(${CMAKE_SOURCE_DIR}/src/main/jni/include)

# 设置opencv的动态库
add_library(libopencv_java3 SHARED IMPORTED)
set_target_properties(libopencv_java3 PROPERTIES IMPORTED_LOCATION
            ${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java3.so)

add_library( # Sets the name of the library.
             native-lib #.so库名 可自定义

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/jni/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} )

9 最后需要在app中的build.gradle进行配置(这里直接给出编译正确的文件代码,此前编译这个里面容易出问题,需要引起注意)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.cayden.opencvtest"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        externalNativeBuild {
            cmake {
                cppFlags ""
                arguments "-DANDROID_STL=c++_shared"
            }
        }
        ndk{
            abiFilters "armeabi-v7a","arm64-v8a"
        }

    }

    sourceSets{
        main{
            jniLibs.srcDirs = ['src/main/jniLibs']
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path file('CMakeLists.txt')
        }
    }

    splits {
        abi {
            enable true
            reset()
            include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' //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]

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    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'
}

六、编译所需so

经过上面的环境配置,现在可以进行编译,如果没有问题会生成对应的so动态库,具体目录如图
动态库目录

七、遇到的问题及其解决方法

1、opencv jni文件的导入方式问题
我这里采用的是<>
2、编译时候cmake参数设置
cmake {
cppFlags “”
arguments “-DANDROID_STL=c++_shared”
}

八、效果图

最后加上一个Activity 写一个界面
如图效果:

最后附上源码地址:https://github.com/cayden/OpenCVTest

感谢大家的阅读,也希望能转发并关注我的公众号

公众号

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cuiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值