问题
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