Android 通過(guò)cmake的方式接入opencv的方法步驟
簡(jiǎn)述
上篇 我們通過(guò)Java sdk的方式已經(jīng)將opencv接入到項(xiàng)目中了,如果想使用opencv sdk 提供的 C++ 頭文件與 .so動(dòng)態(tài)庫(kù),自己封裝jni這樣使用上篇的方式顯然是不能實(shí)現(xiàn)的。所以本篇我們介紹通過(guò)cmake的方式接入opencv。
接入步驟
1、新建jni項(xiàng)目

具體創(chuàng)建過(guò)程參考上篇:通過(guò)Java sdk方式接入opencv 。
2、導(dǎo)入so庫(kù)
在項(xiàng)目app/src/main目錄下新建jniLibs,并將解壓后的opencv sdk 目錄下對(duì)應(yīng)的路徑 sdk/native/libs 中的文件復(fù)制到j(luò)niLibs中。


2、導(dǎo)入cpp文件
將opencv sdk 目錄下對(duì)應(yīng)的路徑 sdk/native/jni/include 中的文件復(fù)制到cpp目錄中。


3、修改CMakeLists
將src/main/cpp 中的CMakeLists移動(dòng)到app目錄下。

2.修改CMakeLists中的內(nèi)容
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# 設(shè)置CMAKE的版本號(hào)
cmake_minimum_required(VERSION 3.4.1)
# 設(shè)置include文件夾的地址
include_directories(${CMAKE_SOURCE_DIR}/src/main/cpp/include)
# 設(shè)置opencv的動(dòng)態(tài)庫(kù)
add_library(libopencv_java4 SHARED IMPORTED)
set_target_properties(libopencv_java4 PROPERTIES IMPORTED_LOCATION
${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java4.so)
add_library( # Sets the name of the library.
native-lib #.so庫(kù)名 可自定義
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/native-lib.cpp)
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)
target_link_libraries( # Specifies the target library.
native-lib
libopencv_java4
# Links the target library to the log library
# included in the NDK.
${log-lib})
修改app 中的build.gradle文件 defaultConfig 中配置cmake和ndk
externalNativeBuild {
cmake {
cppFlags "-std=c++11"
arguments "-DANDROID_STL=c++_shared"
}
}
ndk{
abiFilters "armeabi-v7a","arm64-v8a"
}
android 中配置jniLibs
sourceSets{
main{
jniLibs.srcDirs = ['src/main/jniLibs']
}
}
android 中配置cmake和ndk相關(guān)
externalNativeBuild {
cmake {
path file('CMakeLists.txt')
version "3.10.2"
}
}
splits {
abi {
enable true
reset()
include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' //select ABIs to build APKs for
universalApk true //generate an additional APK that contains all the ABIs
}
}
如果是老項(xiàng)目則不必配置splits否則會(huì)報(bào)錯(cuò),只需要干掉下面的代碼
splits {
abi {
enable true
reset()
include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' //select ABIs to build APKs for
universalApk true //generate an additional APK that contains all the ABIs
}
}
最終配置完的代碼為:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.jd.opencv"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags "-std=c++11"
arguments "-DANDROID_STL=c++_shared"
}
}
ndk{
abiFilters "armeabi-v7a","arm64-v8a"
}
}
sourceSets{
main{
jniLibs.srcDirs = ['src/main/jniLibs']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path file('CMakeLists.txt')
version "3.10.2"
}
}
splits {
abi {
enable true
reset()
include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' //select ABIs to build APKs for
universalApk true //generate an additional APK that contains all the ABIs
}
}
project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
output.versionCodeOverride =
project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 1000000 + android.defaultConfig.versionCode
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
使用
我們將一張彩色圖片通過(guò) opencv 處理成一張灰色的照片。
1、編寫處理照片的代碼。
創(chuàng)建native代碼
object NativeLibUtils{
init {
System.loadLibrary("native-lib")
}
external fun bitmap2Grey(pixels: IntArray, w: Int, h: Int): IntArray
}
創(chuàng)建 jni 代碼
#include <jni.h>
#include <jni.h>
#include <string>
#include<opencv2/opencv.hpp>
#include<iostream>
#include <opencv2/imgproc/types_c.h>
#include <unistd.h>
using namespace cv;
using namespace std;
extern "C"
JNIEXPORT jintArray JNICALL
Java_com_mp5a5_opencv_NativeLibUtils_bitmap2Gray(JNIEnv *env, jobject instance, jintArray pixels,
jint w, jint h) {
jint *cur_array;
jboolean isCopy = static_cast<jboolean>(false);
cur_array = env->GetIntArrayElements(pixels, &isCopy);
if (cur_array == NULL) {
return 0;
}
Mat img(h, w, CV_8UC4, (unsigned char *) cur_array);
cvtColor(img, img, CV_BGRA2GRAY);
cvtColor(img, img, CV_GRAY2BGRA);
int size = w * h;
jintArray result = env->NewIntArray(size);
env->SetIntArrayRegion(result, 0, size, (jint *) img.data);
env->ReleaseIntArrayElements(pixels, cur_array, 0);
return result;
}
調(diào)用 native 代碼來(lái)實(shí)現(xiàn)彩色圖片轉(zhuǎn)換成灰色圖片
private fun showGrayImg() {
val w = bitmap.width
val h = bitmap.height
val pixels = IntArray(w * h)
bitmap.getPixels(pixels, 0, w, 0, 0, w, h)
val resultData: IntArray = NativeLibUtils.bitmap2Gray(pixels, w, h)
val resultImage = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
resultImage.setPixels(resultData, 0, w, 0, 0, w, h)
iv_image.setImageBitmap(resultImage)
}
完整轉(zhuǎn)換的代碼
class OpenCvActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var bitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_opencv)
bitmap = BitmapFactory.decodeResource(resources, R.mipmap.person)
iv_image.setImageBitmap(bitmap)
btn_btn1.setOnClickListener(this)
btn_btn2.setOnClickListener(this)
}
override fun onClick(v: View?) {
v?.id?.let {
when (it) {
R.id.btn_btn1 -> {
showGrayImg()
}
R.id.btn_btn2 -> {
showRgbImg()
}
}
}
}
private fun showRgbImg() {
bitmap = BitmapFactory.decodeResource(resources, R.mipmap.person)
iv_image.setImageBitmap(bitmap)
}
private fun showGrayImg() {
val w = bitmap.width
val h = bitmap.height
val pixels = IntArray(w * h)
bitmap.getPixels(pixels, 0, w, 0, 0, w, h)
val resultData: IntArray = NativeLibUtils.bitmap2Gray(pixels, w, h)
val resultImage = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
resultImage.setPixels(resultData, 0, w, 0, 0, w, h)
iv_image.setImageBitmap(resultImage)
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/ll_location"
app:srcCompat="@mipmap/person" />
<LinearLayout
android:id="@+id/ll_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="@+id/btn_btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="灰度圖" />
<Button
android:id="@+id/btn_btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="色圖" />
</LinearLayout>
</RelativeLayout>
顯示效果:

效果圖
Demo 的 Github 地址 https://github.com/Mp5A5/AndroidOpenCv
到此這篇關(guān)于Android 通過(guò)cmake的方式接入opencv的方法步驟的文章就介紹到這了,更多相關(guān)Android cmake接入opencv內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
談?wù)凙ndroid Fragments 詳細(xì)使用
本篇文章主要介紹了Android Fragments 詳細(xì)使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-12-12
Android實(shí)現(xiàn)excel/pdf/word/odt/圖片相互轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了Android如何實(shí)現(xiàn)excel/pdf/word/odt/圖片之間的相互轉(zhuǎn)換,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-04-04
淺析Android圓形進(jìn)度條ProgressBar如何實(shí)現(xiàn)固定進(jìn)度
之前遇到一個(gè)問(wèn)題,發(fā)現(xiàn)Android里的圓形進(jìn)度條無(wú)法固定一個(gè)進(jìn)度,所以這篇文章就來(lái)和大家探索一下圓形進(jìn)度條ProgressBar如何實(shí)現(xiàn)固定進(jìn)度,希望對(duì)大家有所幫助2024-03-03
Android 自定義通用的loadingview實(shí)現(xiàn)代碼
本篇文章主要介紹了Android 自定義通用的loadingview實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-01-01
android實(shí)現(xiàn)驗(yàn)證碼按鈕
這篇文章主要為大家詳細(xì)介紹了android實(shí)現(xiàn)驗(yàn)證碼按鈕功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
Android開(kāi)發(fā)中Looper.prepare()和Looper.loop()
Looper用于封裝了android線程中的消息循環(huán),默認(rèn)情況下一個(gè)線程是不存在消息循環(huán)(message loop)的,具體調(diào)用方法大家可以通過(guò)本文學(xué)習(xí)2016-11-11
Flutter實(shí)現(xiàn)購(gòu)物車功能(代碼+邏輯)
本文主要介紹了Flutter實(shí)現(xiàn)購(gòu)物車功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03
解決Android 5.1限制外置SD卡寫入權(quán)限的問(wèn)題
今天小編就為大家分享一篇解決Android 5.1限制外置SD卡寫入權(quán)限的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08

