首先去官网下载最新的SDK,官网上有 OpenCV3OpenCV4两大版本,我这使用 OpenCV3版本的 SDK

下载好后解压压缩包,打开自己的项目File -> New -> Import Module 导入sdk 中的 java模块

导入module

导入后要做的几件事:

  1. 修改 modulebuild文件的版本号,改成和自己项目使用的一样就可以
apply plugin: 'com.android.library'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.0"

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 30
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}
  1. 修改 moduleAndroidManifest.xml文件,删除图片中 <uses-sdk .../> 代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.opencv"
      android:versionCode="34120"
      android:versionName="3.4.12">

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" />
</manifest>
  1. 在自己项目中引用该 module,新建 jniLibs目录,导入 sdk目录中 libs下对应的 so库。 为了减少安装包体积,只导入 armeabi-v7a的即可。

引入so库

到此,OpenCV库已经导入完成,写段代码调用下:

@Override
    protected void onResume() {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Log.i("OpenCV", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
        } else {
            Log.i("OpenCV", "OpenCV library found inside package. Using it!");
        }
    }

查看 log会发现有个 error信息(见图第一行),不过没有关系,不影响运行。

E/OpenCV/StaticHelper: OpenCV error: Cannot load info library for OpenCV
D/OpenCV/StaticHelper: Library list: ""
D/OpenCV/StaticHelper: First attempt to load libs
D/OpenCV/StaticHelper: Trying to init OpenCV libs
D/OpenCV/StaticHelper: Trying to load library opencv_java3
D/OpenCV/StaticHelper: Library opencv_java3 loaded
D/OpenCV/StaticHelper: First attempt to load libs is OK
I/OpenCV/StaticHelper: General configuration for OpenCV 3.4.12 =====================================
I/OpenCV/StaticHelper:   Version control:               3.4.12
I/OpenCV/StaticHelper:   Platform:
I/OpenCV/StaticHelper:     Timestamp:                   2020-10-11T01:01:06Z
I/OpenCV/StaticHelper:     Host:                        Linux 4.4.0-190-generic x86_64
I/OpenCV/StaticHelper:     Target:                      Linux 1 armv7-a
I/OpenCV/StaticHelper:     CMake:                       2.8.12.2
I/OpenCV/StaticHelper:     CMake generator:             Ninja
I/OpenCV/StaticHelper:     CMake build tool:            /usr/bin/ninja
I/OpenCV/StaticHelper:     Configuration:               Release
I/OpenCV/StaticHelper:   CPU/HW features:
I/OpenCV/StaticHelper:     Baseline:                    NEON
I/OpenCV/StaticHelper:       requested:                 DETECT
I/OpenCV/StaticHelper:       required:                  NEON
I/OpenCV/StaticHelper:       disabled:                  VFPV3
I/OpenCV/StaticHelper:   C/C++:
I/OpenCV/StaticHelper:     Built as dynamic libs?:      NO

解决办法就是从老版本的sdk中找到 libopencv_info.so文件放到项目中就行了。

接下来就可以愉快的玩耍了!

如果觉得我的文章对你有用,请随意赞赏