Android Jni opencv中的重映射:remap()函數

一,上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;
Mat map_x,map_y;
map_x.create(img.size(),CV_32FC1);
map_y.create(img.size(),CV_32FC1);

for (int i = 0; i <img.rows ; ++i) {
    for (int j = 0; j < img.cols; ++j) {
        map_x.at<float>(i,j) = static_cast<float>(i);
        map_y.at<float>(i,j) = static_cast<float>(img.rows-j);
    }
}
//map對應type--》CV_16UC1, CV_32FC1,or none
remap(img,img,map_x,map_y,CV_INTER_LINEAR);

//對應數據指針
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;

}

發佈了46 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章