LYNX

Links

Tags

Categories

openCV安装

AS和cmake笔记

android的cpu架构

  • android查看cpu架构(termux)
cat /proc/cpuinfo
  • AArch32ARMv7架构的一种执行状态
  • AArch64ARMv8架构的一种执行状态
  • 64位ARMv8包含上面两种状态

cmake在AS中的使用

不要把mkcmake两种方法混淆

输出控制(message)

(TODO)如果想直接看到打印信息,使用WARNING以上的级别进行打印

  • message(WARNING "fuck")
    • Build->Build Output->CMake warnings查看
    • Build->Build Output->Toggle View查看

Android

Android Studio版本为3.5

OpenCV for Android 3.x:只使用java模块

参考:CSDN,示例:压缩图片

  1. File->New->Import Module->选择opencv文件夹下的sdk/java文件夹,此时Android Studio会自动加载Module name
  2. File->Project Structure->Dependencies->选择app->添加Module Dependency->选择opencv
  3. 将opencv文件夹下的sdk/native/libs下自己手机cpu对应的架构文件夹复制到app/libs
  4. 将opencv模块的build.gradlecomplieSdkVersion,buildToolVersion,minSdkVersion,targetSdkVersion改成和appbuild.gradle一样
  5. appbuild.gradleandroid节点下添加
    sourceSets {
    main {
    jni.srcDirs = []
    jniLibs.srcDirs = ['libs']
    }
    }

然后点击sync now

  1. 在使用opencv前进行初始化
    static {
    if (!OpenCVLoader.initDebug()) {
    ...
    }
    }

常见问题

  1. Caused by: CvException [org.opencv.core.CvException: OpenCV(4.1.1) /build/master_pack-android/opencv/modules/java/generator/src/cpp/utils.cpp:101: error: (-215:Assertion failed)

MatBitmap互转的时候长宽设置不对

OpenCV for Android 3.x:使用native模块

方法一

  1. CMakeLists.txt编写

CMakeLists.txt中确定两个关键路径

  • /sdk/native/jni/include:头文件位置
  • /sdk/native/libs/${ANDROID_ABI}/libopencv_java3.so:库位置
cmake_minimum_required(VERSION 3.4.1)

#1
set(opencv_version OpenCV4-android-sdk)
set(opencv_lib libopencv_java4.so)

#2
include_directories(/home/lynx/fuck_mount/Android/Proj/${opencv_version}/sdk/native/jni/include)
add_library(fuck SHARED IMPORTED)
set_target_properties(fuck PROPERTIES IMPORTED_LOCATION
/home/lynx/fuck_mount/Android/Proj/${opencv_version}/sdk/native/libs/${ANDROID_ABI}/${opencv_lib})


add_library(保持原样)

find_library(保持原样)

target_link_libraries(
native-lib

#3
fuck

${log-lib})
  1. 修改app的build.gradle

android节点下插入

sourceSets {
main {
jniLibs.srcDirs = ['/home/lynx/fuck_mount/Android/Proj/OpenCV4-android-sdk/sdk/native/libs']
}
}

方法二

参考:CSDN

还没有成功

  1. CMakeLists.txt编写

CMakeLists.txt中确定一个关键路径

  • /sdk/native/jni/include:头文件位置
cmake_minimum_required(VERSION 3.4.1)

#1
set(opencv_version OpenCV4-android-sdk)
set(opencv_lib libopencv_java4.so)

#2
set(OpenCV_STATIC ON)
set(OpenCV_DIR /home/lynx/fuck_mount/Android/Proj/${opencv_version}/sdk/native/jni)
find_package(OpenCV REQUIRED)
if (OpenCV_FOUND)
message(WARNING "opencv libs: ${OpenCV_LIBS}")
else (OpenCV_FOUND)
message(WARNING "opencv not found")
endif(OpenCV_FOUND)

add_library(保持原样)

find_library(保持原样)

target_link_libraries(
native-lib

${log-lib}

#3
${OpenCV_LIBS})

常见问题

  1. java.lang.UnsatisfiedLinkError: dlopen failed: library "libopencv_java3.so" not found

这是由于忘记了上面的第2步.Android Studio默认的jni路径为app/src/main/jniLibs,除了在CMakeLists.txt中导入opencv的库以外还需要二选一

  • 将对应版本opencv的库(libs/下一级的各个${ANDROID_ABI}文件夹)移动到jniLibs
  • build.gradle中修改默认jni路径(见上面第2步)
  1. 各种undefined reference to *

std::ios_base::Init::Init()

未解决

  1. undefined reference to `AndroidBitmap_getInfo'

各类AndroidBitmap的问题

CMakeLists.txt增加

target_link_libraries(
# TODO 解决 AndroidBitmap 报错
jnigraphics)

参考:CSDN,这是一个很小的库,展示一个稳定的,基于C语言的接口,使本机代码安全地访问Java对象的像素缓冲区的位图

OpenCV for Android 4.x:使用native模块

方法一

3.x版本的方法一

常见问题

  1. java.lang.UnsatisfiedLinkError: dlopen failed: library "libc++_shared.so" not found

stackoverflow

(不确定的解决方法)在app的gradle中修改

externalNativeBuild {
cmake {
cppFlags ""
arguments "-DANDROID_STL=c++_shared"
}
}

不要使用gnustl_sharedgnustl_static,已经过时

  1. java.lang.UnsatisfiedLinkError: dlopen failed: library "libopencv_java4.so" not found

解决方案同3.x版本

OpenCV for Android 4.x:使用java+native模块

参考:CSDN

  1. 加载native模块

  2. File->New->Import Module->选择opencv文件夹下的sdk/java文件夹,自己定义模块的名字

  3. 修改模块的gradle文件

// 将原来的application改成library
apply plugin: 'com.android.library'

android {
// 将版本信息改得和`app`的`build.gradle`一样
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
// 删除applicationId
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
// 不改动
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
  1. (重复)修改app的gradle文件,加载native/lib模块

javacv(使用不完整OpenCV 4.1.0)

不同导入方法,import的class位置可能不同

opencv部分功能的初始化

github原文

Loader.load(opencv_java.class);// 不能直接放在class开头

使用远程导入

appbuild.gradle示例(最外节点)

ext {
versions = [
'javacv': '1.4.4',
'ffmpeg': '4.1',
'opencv': '4.0.1'
]
}

dependencies {
...
implementation(group: 'org.bytedeco', name: 'javacv-platform', version: versions.javacv) {
exclude group: 'org.bytedeco.javacpp-presets'
}
implementation group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: "${versions.ffmpeg}-${versions.javacv}"
implementation group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: "${versions.ffmpeg}-${versions.javacv}", classifier: 'android-arm'
implementation group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: "${versions.ffmpeg}-${versions.javacv}", classifier: 'android-arm64'
implementation group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: "${versions.opencv}-${versions.javacv}"
implementation group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: "${versions.opencv}-${versions.javacv}", classifier: 'android-arm'
implementation group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: "${versions.opencv}-${versions.javacv}", classifier: 'android-arm64'
}

作为lib导入

根据手机具体的cpu架构进行导入

appbuild.gradle

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
}

将文件(视具体情况)

  • javacpp.jar
  • javacv.jar
  • openblas.jar
  • openblas-android-arm64.jar
  • opencv.jar
  • opencv-android-arm64.jar
    复制到app/libs/文件夹里

常见错误

  1. cpu架构错误/缺少(需添加-android-arm之类的库)
2019-10-27 16:01:32.439 29256-29322/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.github.crazyorr.ffmpegrecorder, PID: 29256
java.lang.RuntimeException: An error occurred while executing doInBackground()
  1. 没有对opencv初始化
2019-10-27 16:00:43.930 28933-28933/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.javacv, PID: 28933
java.lang.UnsatisfiedLinkError: No implementation found for long org.opencv.core.Mat.n_Mat() (tried Java_org_opencv_core_Mat_n_1Mat and Java_org_opencv_core_Mat_n_1Mat__)
  1. 缺少openblas的相关jar
2019-10-27 15:59:23.158 28618-28618/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.javacv, PID: 28618
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/bytedeco/openblas/presets/openblas;

OpenCV 4.x source code

参考:CSDN

  1. 修改参数

Android Studio的sdk下的ndk:ndk/build/cmake/android.toolchain.cmake(第112行)

elseif(ANDROID_TOOLCHAIN_NAME MATCHES "-[0-9].[0-9]$")
set(ANDROID_TOOLCHAIN clang) # 将gcc改成clang
endif()

opencv 4.x源码:/platforms/android/build_sdk.py(第113行)

self.cmake_vars = dict(
ANDROID_STL="c++_static", # change `gnustl_static` to `c++_static` or `c++_shared`
ANDROID_ABI=self.name,
ANDROID_PLATFORM_ID=platform_id,
)

opencv 4.x源码:/CMakeLists.txt(第426行和429行)(可以根据需要修改)

# OCV_OPTION(BUILD_SHARED_LIBS        "Build shared libraries (.dll/.so) instead of static ones (.lib/.a)" NOT (ANDROID OR APPLE_FRAMEWORK) )
OCV_OPTION(BUILD_SHARED_LIBS "Build shared libraries (.dll/.so) instead of static ones (.lib/.a)" ON ) # 生成动态库
OCV_OPTION(BUILD_opencv_apps "Build utility applications (used for example to train classifiers)" (NOT ANDROID AND NOT WINRT) IF (NOT APPLE_FRAMEWORK) )
OCV_OPTION(BUILD_opencv_js "Build JavaScript bindings by Emscripten" OFF )
OCV_OPTION(BUILD_ANDROID_PROJECTS "Build Android projects providing .apk files" OFF )
# OCV_OPTION(BUILD_ANDROID_PROJECTS "Build Android projects providing .apk files" ON IF ANDROID )
  1. 配置JAVA_HOME

使用Android Studio的JDK位置

export JAVA_HOME=/home/lynx/fuck_mount/AS/jre
  1. 执行platforms/android/build_sdk.py,完成编译
./build_sdk.py --ndk-path {ndk路径} --sdk_path {android sdk路径} {目标位置} {opencv源码位置}
# example
/home/lynx/fuck_mount/opencv_4_1_0/opencv-4.1.0/platforms/android/build_sdk.py --ndk_path /home/lynx/fuck_mount/Android/SDK/ndk/18.1.5063045 --sdk_path /home/lynx/fuck_mount/Android/SDK /home/lynx/fuck_mount/opencv_4_1_0/android_build /home/lynx/fuck_mount/opencv_4_1_0/opencv-4.1.0
  • sdk-path:Android Studio的SDK目录
  • ndk-path:Android Studio的SDK目录下ndk/{ndk版本号文件}

额外说明

不需要额外安装的软件:jdk,ninja-build,ndk.直接使用android studio的即可
不需要安装的软件:ant,ccache

目前还没能成功编译android project

能够混合使用:

  • OpenCV 3.xjava库(配置见上)
  • TODO

常见问题

  1. java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.example.stitch-sPWgBONIqUrdX9XLB1OY6w==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.stitch-sPWgBONIqUrdX9XLB1OY6w==/lib/arm64, /data/app/com.example.stitch-sPWgBONIqUrdX9XLB1OY6w==/base.apk!/lib/arm64-v8a, /system/lib64, /product/lib64]]] couldn't find "libnative-lib.so"

缺少相应ABI的so库(目前计时在gradle里加入abiFilters也没有用),上述报错是因为没有编译全ABI.ABI配置:opencv-4.x/platforms/android/ndk-18-api-level-21.config.py

Linux

OpenCV source code

目前适用4.x,其余没试过

依赖包

sudo apt install libgtk2.0-dev pkg-config

命令行安装(TODO)

  1. cmake
cd {生成makefile的位置}
cmake {source的位置}
  1. make
cd {生成makefile的位置}
make
  1. make install
make install {安装的位置}

gui安装

参考:CSDN

  1. 安装cmake-gui
sudo apt install cmake-gui
  1. 启动cmake-gui
cd {build二进制文件的目录}
cmake-gui {opencv源代码}
  1. Configure->Unix Makefiles:Use default native compilers->finish

  2. 狂点Configure知道没有红色区域

  3. 赋值

变量名 赋值
CMAKE_BUILD_TYPE Release
CMAKE_INSTALL_PREFIX {自己定的cmake_install路径}
OPENCV_GENERATE_PKGCONFIG 勾选
OPENCV_EXTRA_MODULES_PATH {opencv-contrib}源代码/modules
BUILD_EXAMPLES 勾选
  1. 狂点Configure

  2. Generate,等到Generating done

  3. 在源代码路径make

sudo make -j4 # 具体看有多少cpu
cat /proc/cpuinfo | grep "processor" | wc -l # 查看cpu个数
sudo make install
  1. 配置opencv4.pc(2选1)

    • 修改PKG_CONFIG_PATH:增加{你cmake_install的路径}/lib/(opencv4.pc所在的文件夹路径)
    • (TODO,没试过)复制opencv4.pc/usr/lib/pkgconfig
  2. 配置库路径,(新建)/etc/ld.so.conf.d/opencv.conf

{你cmake_install路径}/lib/ # 自己的lib路径
sudo ldconfig
  1. 编译测试

如果是opencv.pcopencv4改成opencv

pkg-config --modversion opencv4
g++ a.cpp `pkg-config --cflags --libs opencv4` -o test && ./test

常见问题

  1. 在其他项目中用CMake导入OpenCV模块:
    find_package(OpenCV REQUIRED)
    include_directories(${OpenCV_INCLUDE_DIRS})

之后cmake出现By not providing "FindOpenCV.cmake" in CMAKE_MODULE_PATH ...:

这是由于没有设置环境变量OpenCV_DIR,设置为OpenCV编译后的目录下含有OpenCVConfig.cmake的对应路径

Tags

ndk

Categories

1 / 1