Android Jni 利用transpose()和flip()函数实现图像旋转90°

一,上java代码

private Button btnProc;
private ImageView imageView;
private Bitmap bmp;

// Used to load the 'native-lib' library on application startup.
static {
    System.loadLibrary("native-lib");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Example of a call to a native method
    btnProc = (Button) findViewById(R.id.btn_gray_process);
    imageView = (ImageView) findViewById(R.id.image_view);

    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.test7);
    imageView.setImageBitmap(bmp);
    btnProc.setOnClickListener(this);
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
public static native int[] grayProc(int[] pixels, int w, int h);


@Override
public void onClick(View view) {

    int w = bmp.getWidth();
    int h = bmp.getHeight();
    int[] pixels = new int[w*h];
    bmp.getPixels(pixels, 0, w, 0, 0, w, h);

    long startTime = System.currentTimeMillis();
    int[] resultInt = grayProc(pixels, w, h);
    long endTime = System.currentTimeMillis();

    Log.e("JNITime",""+(endTime-startTime));
    Bitmap resultImg = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

    //(@ColorInt int[] pixels, int offset, int stride,int x, int y, int width, int height)
    resultImg.setPixels(resultInt, 0, w, 0, 0, w, h);
    imageView.setImageBitmap(resultImg);

}

二,实现jni方法

extern “C”
JNIEXPORT jintArray JNICALL
Java_com_example_dgxq008_opencv_1readpixel_MainActivity_grayProc(JNIEnv *env, jclass type
, jintArray pixels_
, jint w
, jint h) {

jint* pixels = env->GetIntArrayElements(pixels_, NULL);
if (pixels==NULL){
    return 0;
}

//图片一进来时是ARGB  通过mat转换BGRA
Mat img(h,w,CV_8UC4,(uchar *)pixels);  //pixels 操作的是同一份数据
Mat temp;

transpose(img,temp);
//Size_(_Tp _width, _Tp _height);
resize(temp,img,Size(w,h));

/**
  * 翻转图片
  * 第三个参数,0以x轴进行翻转,1以y轴翻转,-1以xy同时翻转
  */
flip(img,img,1);

//对应数据指针
uchar* ptr = img.data;

int size = w*h;
jintArray result = env->NewIntArray(size);
env->SetIntArrayRegion(result,0,size,pixels);

env->ReleaseIntArrayElements(pixels_, pixels, 0);

return result;

}

你可能感兴趣的:(jni,openCV)