最近在做图片的处理,涉及到opencv的jni环境搭建,顺便记录下
推荐一个关于jni开发环境搭建的博客:,因为opencv的jni环境搭建差不多
一、Android Opencv jni开发环境搭建:

1、下载个opencv的sdk,目前写的demo用的是:opencv-3.4.1-android-sdk

将文件夹OpenCV-android-sdk\sdk\native\jni\include拷入项目jinLibs目录

OpenCV后端目录结构 opencv jni_本地库


OpenCV后端目录结构 opencv jni_本地库_02


2、将OpenCV-android-sdk\sdk\native\libs下的so文件拷入项目中对应的文件夹

OpenCV后端目录结构 opencv jni_本地库_03

OpenCV后端目录结构 opencv jni_本地库_04


3、配置CMakeLists.txt

配置opencv的头文件,根据自己放的路径写,比如我头文件存放的路径在main/jniLibs/include,CMakeLists.txt存放在main/cpp,那么我include头文件的路径就是:“…/jniLibs/include”

OpenCV后端目录结构 opencv jni_本地库_05


添加动态库libopencv_java3.so

OpenCV后端目录结构 opencv jni_OpenCV后端目录结构_06


OpenCV后端目录结构 opencv jni_本地库_07


4、配置CMakeLists.txt路径

在模块的build.gradle配置如下路径,配置在Android标签下

OpenCV后端目录结构 opencv jni_本地库_08


如果需要指定ndk编译cpu架构的类型,在defaultConfig配置ndk 指定类型

OpenCV后端目录结构 opencv jni_OpenCV后端目录结构_09


5:以上步骤配置完成,可以敲代码了

编写代码路径根据自己习惯操作的放置,demo中放在main/cpp下,项目中以opencv_jni.cpp为例

OpenCV后端目录结构 opencv jni_本地库_10


添加文件后需要在CMakeLists.txt配置,将opencv_jni.cpp源码添加到本地库opencv_jni

OpenCV后端目录结构 opencv jni_环境搭建_11


OpenCV后端目录结构 opencv jni_本地库_12


6:配置好以上信息,接下来编写一个图片灰色处理来验证,demo中直接在MainActivity实现,根据自己的需求可以单独写个文件

首先加载本地库,步骤五添加的本地库名

OpenCV后端目录结构 opencv jni_OpenCV后端目录结构_13


编写实现的方法

OpenCV后端目录结构 opencv jni_OpenCV后端目录结构_14


写完后alt+enter,默认会在opencv_jni.cpp生成对应的方法,方法的结构就是文件夹路径+方法声明的类+方法名,我在MAinActivity中声明所以就是MainActivity_getGray

OpenCV后端目录结构 opencv jni_OpenCV后端目录结构_15


在opencv_jni.cpp实现一些图片处理的过程

OpenCV后端目录结构 opencv jni_android_16


activity中调用

OpenCV后端目录结构 opencv jni_本地库_17


图片处理对比

OpenCV后端目录结构 opencv jni_android_18

OpenCV后端目录结构 opencv jni_环境搭建_19


demo地址:https://github.com/972242736/OpencvJniDemo/tree/master/app