六.opencv環境搭建(cmake方式)
阿新 • • 發佈:2018-12-13
opencv全稱open source compute vision,開源的視覺庫
一.準備工作
匯入opencv的步驟還是相對簡單,準備步驟分為以下三步:
- 將OpenCV-android-sdk/sdk/native/libs拷貝到工程的jniLibs
- 將OpenCV-android-sdk/sdk/native/jni/include拷貝到src/main/cpp目錄(cpp目錄不存在就新建一個)
這時候,你的工程目錄應該如下圖:
二.建立include和so庫的繫結關係,CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
set(CMAKE_VERBOSE_MAKEFILE on)
set(libs "${CMAKE_SOURCE_DIR}/src/main/jniLibs")
add_library(native-lib
SHARED
src/main/cpp/Hello.cpp ) #新增.c原始檔
include_directories(src/main/cpp/include) #新增標頭檔案的位置
#新增庫物件,並設定引用方式
add_library(libopencv_java3 SHARED IMPORTED )
#設定libopencv_java3庫的位置
set_target_properties(libopencv_java3 PROPERTIES
IMPORTED_LOCATION "${libs}/${ANDROID_ABI}/libopencv_java3.so" )
target_link_libraries( # Specifies the target library.
native-lib -ljnigraphics libopencv_java3
# Links the target library to the log library
# included in the NDK.
${log-lib} )
三.呼叫opencv的方法
先看MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView contentTv = findViewById(R.id.tv_content);
contentTv.setText(getVersion());
}
static {
System.loadLibrary("native-lib");
}
public native String getVersion();
}
Hello.h會Include opencv的標頭檔案
#ifndef PRACTICLE_HELLO_H
#define PRACTICLE_HELLO_H
#include <jni.h>
#include <android/bitmap.h>
#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_a6_1opencv2_MainActivity_getVersion(JNIEnv *env, jobject instance);
#endif //PRACTICLE_HELLO_H
在看Hello.cpp
#include <jni.h>
#include "Hello.h"
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jstring JNICALL
Java_com_example_a6_1opencv2_MainActivity_getVersion(JNIEnv *env, jobject instance) {
const char *version = CV_VERSION;
return env->NewStringUTF(version);;
} ;
#ifdef __cplusplus
}
#endif