win0系统,android studio如何通过cmake安装opnecv
时间: 2023-04-10 13:04:11 浏览: 130
您可以按照以下步骤安装OpenCV:
1. 下载OpenCV的源代码并解压缩。
2. 打开Android Studio并创建一个新项目。
3. 在项目的build.gradle文件中添加以下代码:
```
externalNativeBuild {
cmake {
cppFlags ""
arguments "-DANDROID_STL=c++_shared"
}
}
```
4. 在app的build.gradle文件中添加以下代码:
```
android {
defaultConfig {
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
```
5. 在项目的根目录下创建一个CMakeLists.txt文件,并添加以下代码:
```
cmake_minimum_required(VERSION 3.4.1)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/native-lib.cpp )
# OpenCV
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/include)
add_library(lib_opencv SHARED IMPORTED)
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java4.so)
# Links your native library against one or more other native libraries.
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib}
# OpenCV
lib_opencv )
```
6. 在src/main/cpp文件夹下创建一个native-lib.cpp文件,并添加以下代码:
```
#include <jni.h>
#include <string>
#include <opencv2/opencv.hpp>
using namespace cv;
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
```
7. 在MainActivity.java文件中添加以下代码:
```
static {
System.loadLibrary("native-lib");
System.loadLibrary("opencv_java4");
}
```
8. 最后,您可以在MainActivity.java文件中调用OpenCV函数。
请注意,您需要将OpenCV库文件放在src/main/jniLibs文件夹中,并根据您的CPU架构选择正确的文件夹。
阅读全文