Android NDK开发:实现图像映像
2019-08-13 本文已影响0人
itfitness
目录
效果演示
实现原理
实现原理其实很简单,就是X方向映像需要将左右两边的像素进行对调,Y轴是上下的像素对调,XY则是上下左右同时对调。
核心代码
核心代码是结合OpenCV在Native层实现的。
/**
* Java层的函数声明
* @param bitmap 传入的Bitmap对象
* @param type 映像类型,1:X轴、2:Y轴、3:XY轴
*/
public native void remap(Object bitmap,int type);
extern "C"
JNIEXPORT void JNICALL
Java_com_itfitness_opencvrehearse_demos_remap_RemapActivity_remap(JNIEnv *env, jobject instance,
jobject bitmap, jint type) {
AndroidBitmapInfo info;
void *pixels;
CV_Assert(AndroidBitmap_getInfo(env, bitmap, &info) >= 0);
CV_Assert(info.format == ANDROID_BITMAP_FORMAT_RGBA_8888 ||
info.format == ANDROID_BITMAP_FORMAT_RGB_565);
CV_Assert(AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0);
CV_Assert(pixels);
if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) {
Mat temp(info.height, info.width, CV_8UC4, pixels);
Mat dst = Mat(temp.size(),temp.type());
int width = temp.cols;
int height = temp.rows;
for (int row = 0; row < height;row++) {
for (int col = 0; col < width;col++) {
int b = temp.at<Vec4b>(row, col)[0];
int g = temp.at<Vec4b>(row, col)[1];
int r = temp.at<Vec4b>(row, col)[2];
int a = temp.at<Vec4b>(row, col)[3];
switch (type){
case 1:
//X轴
dst.at<Vec4b>(row, width-1 - col)[0] = b;
dst.at<Vec4b>(row, width-1 - col)[1] = g;
dst.at<Vec4b>(row, width-1 - col)[2] = r;
dst.at<Vec4b>(row, width-1 - col)[3] = a;
break;
case 2:
//Y轴
dst.at<Vec4b>(height - 1 - row, col)[0] = b;
dst.at<Vec4b>(height - 1 - row, col)[1] = g;
dst.at<Vec4b>(height - 1 - row, col)[2] = r;
dst.at<Vec4b>(height - 1 - row, col)[3] = a;
break;
case 3:
//XY轴
dst.at<Vec4b>(height - 1 - row, width - 1 - col)[0] = b;
dst.at<Vec4b>(height - 1 - row, width - 1 - col)[1] = g;
dst.at<Vec4b>(height - 1 - row, width - 1 - col)[2] = r;
dst.at<Vec4b>(height - 1 - row, width - 1 - col)[3] = a;
break;
}
}
}
dst.copyTo(temp);
dst.release();
}
AndroidBitmap_unlockPixels(env, bitmap);
}