1. OpenCV 简介

OpenCV的全称是Open Source Computer Vision Library,是一个跨平台的计算机视觉库。OpenCV是由英特尔公司发起并参与开发,以BSD许可证授权发行,可以在商业和研究领域中免费使用。OpenCV可用于开发实时的图像处理、计算机视觉以及模式识别程序。该程序库也可以使用英特尔公司的IPP进行加速处理。

2. OpenCV 下载和环境配置

  • 下载地址:https://opencv.org/releases/
  • 在项目main目录下新建目录jniLibs/ 。将上一步下载的include头文件和so动态库放入里面
  • 修改cmake文件,将opencv.so 链接进 libnative.so 中
    cmake.txt: 重要
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.18.1)

# Declares and names the project.

project("opencvndk")
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
#判断编译器类型,如果是gcc编译器,则在编译选项中加入c++11支持
if(CMAKE_COMPILER_IS_GNUCXX)
    set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
    message(STATUS "optional:-std=c++11")
endif(CMAKE_COMPILER_IS_GNUCXX)


#需要引入我们头文件,以这个配置的目录为基准
include_directories(${CMAKE_SOURCE_DIR}/../jniLibs/include)

# 添加依赖 opencv.so 库
set(CURRENT_DIR ${CMAKE_SOURCE_DIR}/../)
add_library(
        opencv_java4
        SHARED
        IMPORTED)
set_target_properties(
        opencv_java4
        PROPERTIES IMPORTED_LOCATION
        ${CURRENT_DIR}/../../libs/${ANDROID_ABI}/libopencv_java4.so)


# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
        opencvndk

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        native-lib.cpp)




# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

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)

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
        opencvndk
        #加入该依赖库
        opencv_java4
        # Links the target library to the log library
        # included in the NDK.
        ${log-lib})

环境配置遇到的坑:

  1. set_target_properties 中路径错误
  2. 最新版本的AndroidStudio 不要将第三方的so 放在jniLibs 目录下,不然会有重复依赖的报错
  3. build.gradle 中 需要加上argments 不然也会报错libc++_shared.so 找不到
    image-20220529162816503
    4.最后附上项目目录截图:
    image-20220529163016624
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐