简体   繁体   中英

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

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?

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM