1:用Android studio创建C++项目
2:下载opencv的android sdk
3:将下载好的包加压,把native文件夹下的include拷贝到项目的cpp目录下
4:将native文件夹下libs目录的so包拷贝到jniLibs目录下
若没有jniLibs目录可以通过下面方法加入
?5:然后打开我们的CMakeLists.txt文件开始引入我们的opencv
cmake_minimum_required(VERSION 3.10.2)
project("shaderlearning")//这个可以不用管
include_directories(include)//这个是刚刚加入的include文件
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -L${CMAKE_SOURCE_DIR}/../../../libs/${ANDROID_ABI}")//设置so的路径
add_library(
shaderlearning
SHARED
native-lib.cpp)
find_library(
log-lib
log)
target_link_libraries(
shaderlearning
${log-lib}
opencv_java4 //这个即是我们刚刚下载的opencv
jnigraphics//这个是做bitmap处理的按需加入
${android}
)
6:需要指定下我们so使用的环境
?7:接下来我们看看怎么使用
#include <jni.h>
#include <string>
#include <iostream>
#include <android/bitmap.h>
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
extern "C"
JNIEXPORT jobject JNICALL
Java_com_henry_rtmp_shaderlearning_MainActivity_mixImageSecond(JNIEnv *env, jobject thiz,
jstring src_first,
jstring src_second) {
const char *image_url_first=env->GetStringUTFChars(src_first,0);
const char *image_url_second=env->GetStringUTFChars(src_second,0);
Mat src = imread(image_url_first);
Mat src_mask_one = imread(image_url_second);
/* 算术运算-加 */
Mat src_add(src.size(), src.type());
src_add = 0.5 * src + 0.5 * src_mask_one;
unsigned char *imgData=src_add.data;
int nOutHeight=src_add.rows;
int nOutWidth=src_add.cols;
jclass bitmapCls = env->FindClass("android/graphics/Bitmap");
jmethodID createBitmapFunction = env->GetStaticMethodID(bitmapCls,"createBitmap",
"(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
jstring configName = env->NewStringUTF("ARGB_8888");
jclass bitmapConfigClass = env->FindClass("android/graphics/Bitmap$Config");
jmethodID valueOfBitmapConfigFunction = env->GetStaticMethodID(
bitmapConfigClass, "valueOf",
"(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
jobject bitmapConfig = env->CallStaticObjectMethod(bitmapConfigClass,
valueOfBitmapConfigFunction,configName);
jobject bitmap = env->CallStaticObjectMethod(bitmapCls,
createBitmapFunction,
nOutWidth,
nOutHeight, bitmapConfig);
unsigned char *resultBitmapPixels = NULL;
AndroidBitmap_lockPixels(env, bitmap, (void**)&resultBitmapPixels);
for(int i=0;i<nOutWidth*nOutHeight;i++)
{
resultBitmapPixels[4*i] = imgData[3*i];
resultBitmapPixels[4*i+1] = imgData[3*i+1];
resultBitmapPixels[4*i+2] = imgData[3*i+2];
resultBitmapPixels[4*i+3] = (unsigned char)255;
}
AndroidBitmap_unlockPixels(env, bitmap);//最终得到的就是bitmap
return bitmap;
}
一个简单的2个图片的线性合并的demo。
sdk下载路径 opencvandroidsdk-Android文档类资源-CSDN下载
|