准备工作
1 NDK(不需要指定版本目前最新19) CMake 正常使用AS的SDKManager添加即可 2 创建一个Project 记得勾选supportC++ 3 下载 openCv https://opencv.org/releases.html 当前最新 4.0.1
开始配置
注意:考虑到java处理图片的效率本人使用的并非是OpenCv提供的JavaSDK而是通过jni调用其提供的 libopencv_java4.so动态库 1 在main目录下创建jniLibs目录并把解压后的opencv的 sdk/native/libs/ 下的所有内容copy到jniLibs下:
2 修改CMakeLists.txt 文件:在 cmake_minimum_required(VERSION 3.4.1)下添加set(OPENCV_PATH #OpenCV的解压后的路径# )
set(CMAKE_VERBOSE_MAKEFILE on)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
include_directories(${OPENCV_PATH}/sdk/native/jni/include)
add_library(lib_opencv STATIC IMPORTED)
set_target_properties(lib_opencv
PROPERTIES
IMPORTED_LOCATION ${PROJECT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java4.so
)
复制代码
3 设置target_link_libraries:
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib}
android
-ljnigraphics
lib_opencv)
复制代码
4 修改native-lib:
#include
#include
#include
#include
#include
#include
using namespace cv;
using namespace std;
extern "C" JNIEXPORT jintArray JNICALL
Java_com_demo_androidopencvdemo_MainActivity_gray(JNIEnv *env, jobject instance, jintArray buf, jint w,
jint h) {
jint *cbuf = env->GetIntArrayElements(buf, JNI_FALSE);
if (cbuf == NULL) {
return 0;
}
Mat imgData(h, w, CV_8UC4, (unsigned char *) cbuf);
uchar *ptr = imgData.ptr(0);
for (int i = 0; i < w * h; i++) {
//计算公式:Y(亮度) = 0.299*R + 0.587*G + 0.114*B
//对于一个int四字节,其彩色值存储方式为:BGRA
int grayScale = (int) (ptr[4 * i + 2] * 0.299 + ptr[4 * i + 1] * 0.587 + ptr[4 * i + 0] * 0.114);
ptr[4 * i + 1] = grayScale;
ptr[4 * i + 2] = grayScale;
ptr[4 * i + 0] = grayScale;
}
int size = w * h;
jintArray result = env->NewIntArray(size);
env->SetIntArrayRegion(result, 0, size, cbuf);
env->ReleaseIntArrayElements(buf, cbuf, 0);
return result;
}
复制代码
5 调用在activity中调用:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
iv_source.setImageResource(R.mipmap.img_head)
val bitmapDrawable = resources.getDrawable(R.mipmap.img_head, null) as BitmapDrawable
val bitmap = bitmapDrawable.bitmap
val width = bitmap.width
val height = bitmap.height
val pix = IntArray(width * height)
bitmap.getPixels(pix, 0, width, 0, 0, width, height)
val resultPixels = gray(pix, width, height)
val result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
result.setPixels(resultPixels,0,width,0,0,width,height)
iv_target.setImageBitmap(result)
}
external fun gray(buf: IntArray, w: Int, h: Int): IntArray
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
}
复制代码
结果预览: