由于OpenCV开源图像处理代码简单,因此常用于各种平台中。采用NDK编程可以方便的使用OpenCV资源。
使用OpenCV的NDK编程主要包括两部分:
1、添加OpenCV库,用ndk-build编译,Linux系统下
1.1 Android.mk
LOCAL_PATH:=$(call my-dir)
include $(CLEAR_VARS)
OpenCV_INSTALL_MODULES := on
OpenCV_CAMERA_MODULES := off
OPENCV_LIB_TYPE :=STATIC
include /home/zzw/AndroidStudioProjects/opencv_face/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk //这里面包括OpenCV的配置
#LOCAL_SRC_FILES := squeezencnn_jni.cpp
LOCAL_MODULE := JNIpart
LOCAL_SRC_FILES := OpenCVNDK.cpp
LOCAL_LDLIBS += -llog -lGLESv2 -lEGL -ljnigraphics
include $(BUILD_SHARED_LIBRARY)
1.2 Application.mk 切记NDK的版本不能太高了
# APP_STL := stlport_static
APP_STL := gnustl_static
# APP_ABI := armeabi armeabi-v7a
APP_CPPFLAGS := -std=c++11 -frtti -fexceptions
APP_ABI := armeabi-v7a
APP_PLATFORM := android-14
#NDK_TOOLCHAIN_VERSION := 10
2、OpenCVNDK.cpp 文件编写
JNIEXPORT jobject JNICALL Java_com_example_root_cameralopencv_MainActivity_FaceDetection
(JNIEnv* env, jobject thiz, jobject bitmap)
{
AndroidBitmapInfo info;
AndroidBitmap_getInfo(env, bitmap, &info);
int width = info.width;
int height = info.height;
unsigned char* indata;
AndroidBitmap_lockPixels(env, bitmap, (void**)&indata);
//image copy bimap的数据格式为ARGB,因此需要后续的转化和采用CV_8UC4格式
cv::Mat imgData(height, width, CV_8UC4, indata);
AndroidBitmap_unlockPixels(env, bitmap);
//返回Bimap格式,Mat 转bimap.
jobject bitmaptemp;
jclass bitmapCls = env->GetObjectClass(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 newBitmap = env->CallStaticObjectMethod(bitmapCls, createBitmapFunction, info.width, info.height, bitmapConfig);
unsigned char* newBitmapPixels;
AndroidBitmap_lockPixels(env, newBitmap, (void**)&newBitmapPixels);
for(int i = 0; i < info.width*info.height*4; i+=4){
//unsigned char g = imgData.data[i];
newBitmapPixels[i] = imgData.data[i];
newBitmapPixels[i+1] = imgData.data[i+1];
newBitmapPixels[i+2] = imgData.data[i+2];
newBitmapPixels[i+3] = imgData.data[i+3];
}
AndroidBitmap_unlockPixels(env, newBitmap);
return newBitmap;
}
网友评论