How to put an image into a MAT in openCV, through the android NDK (c++)

放肆的年华 提交于 2021-02-07 20:25:23

问题


I'm using OpenCv through the Android NDK (using c++) I would like to save an image into MAT format and then display it on my android application.

I have saved the image in assets. imread() does not work in the NKD because it cannot find the file path to the image, however, I can use AssetManager to load an asset and it finds the path perfectly. This method saves the data into a char* buffer.

How can I, either use something similar to imread() to save the image into a MAT, or convert the char* buffer data into a MAT in order to display it on screen and later on manipulate with other openCV functions?


回答1:


Use code snippet

extern "C"
JNIEXPORT int JNICALL
Java_com_example_opencv_test_NativeLib_checkNativeImage(JNIEnv *env,
                                                    jclass type,
                                                    jobject jBitmap,
                                                    jint width,
                                                    jint height) {

void *pPixelData = nullptr;
if (AndroidBitmap_lockPixels(env, jBitmap, &pPixelData) ==
    ANDROID_BITMAP_RESULT_SUCCESS) {

    // Android bitmap (Bitmap.Config.ARGB_8888) to Mat
    // Android and OpenCV have different color channels order, just swap it
    // You need cppFlags "-std=c++14" for this code
    // See [opencv_src]\modules\java\generator\src\cpp\utils.cpp for details about PremultiplyAlpha
    // Use https://docs.opencv.org/java/2.4.2/org/opencv/android/Utils.html for Mat in Java

    cv::Mat temp = cv::Mat(cvSize(width, height), CV_8UC4, pPixelData); // 4 channels
    cv::Mat img;
    cv::cvtColor(temp, img, CV_BGRA2RGBA);

    // ... use Mat Image


    // back to Android Bitmap
    cvtColor(img, temp, CV_RGBA2BGRA); // Swap colors back
    memcpy(pPixelData, temp.data, static_cast<size_t>(width * height * 4));


    AndroidBitmap_unlockPixels(env, jBitmap);

    return EXIT_SUCCESS;
}

return EXIT_FAILURE;

}


来源:https://stackoverflow.com/questions/47798642/how-to-put-an-image-into-a-mat-in-opencv-through-the-android-ndk-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!