Search code examples
androidc++opencvandroid-ndkjava-native-interface

Android ndk pass OpenCV mat to jni containing double values



I use OpenCV4Android and I need to compute some values in C++ using Android NDK. In the OpenCV docs I read how to pass a Mat object between Java and C++ and this works fine for CV_8U int values. But if I use Mat type CV_64FC1 filled with doubles I get some strange values.

Is there any method that I need?

Java

MyNativeLib.myNativeFunction(mat.getNativeObjAddr());

C++

JNIEXPORT void JNICALL Java_de_my_package_MyNativeLib_myNativeFunction(JNIEnv *env, jlong mat_adress) {
  cv::Mat& mat = *((cv::Mat*) mat_adress);
  int i, j;
  for(int i = 0; i < mat.rows; i++) {
      for(int j = 0; j < mat.cols; j++) {
            if(i < 5 && j == 0)
                LOGI("Test output @ (%i,%i) = %f", i, j, (double) mat.data[i*mat.cols+j] );
      }
  }
}

My input using CV_8U int values:

108.0
100.0
111.0
112.0
119.0

My jni output

 Test output @ (0,0) = 108.000000
 Test output @ (0,0) = 100.000000
 Test output @ (0,0) = 111.000000
 Test output @ (0,0) = 112.000000
 Test output @ (0,0) = 119.000000

My input mat with type CV_64FC1

 109.32362448251978
 105.32362448251978 
 110.82362448251978
 111.32362448251978
 114.82362448251978

My jni output

 Test output @ (0,0) = 223.000000
 Test output @ (0,0) = 223.000000
 Test output @ (0,0) = 223.000000
 Test output @ (0,0) = 223.000000
 Test output @ (0,0) = 223.000000

Does anyone know why this happens?


Solution

  • According to the doc mat.data returns a uchar*.

    To get the double values you need to access pixels like:

     double val = mat.at<double>(i,j);
    

    or using pointers:

     double* pdata = mat.ptr<double>(0);
     double val = pdata[i*mat.step+j];
    

    or:

     double* prow = mat.ptr<double>(i);
     double val = prow(j);