简体   繁体   English

如何将位图正确转换为OpenCV灰度Mat

[英]How to properly convert Bitmap to OpenCV grayscale Mat

I want to use this library inside Android project with integrated OpenCV module. 我想在带有集成OpenCV模块的Android项目中使用此库

Native function code: 本机功能代码:

extern "C" JNIEXPORT void JNICALL
Java_my_package_MyActivity_featherEdges(
        JNIEnv *env,
        jobject /* this */,
        cv::Mat &I,
        cv::Mat &p,
        cv::Mat &q
        ) {

    int r = 60;
    double eps = 1e-6;
    eps *= 255 * 255;
    q = guidedFilter(I, p, r, eps);
}

Kotlin-side mask Bitmap to Mat converter: Kotlin面罩位图到Mat转换器:

fun Bitmap.maskToMat(): Mat {
    val mat = Mat(this.width, this.height, CvType.CV_8UC1)
    val obj = copy(Bitmap.Config.ARGB_8888, true)
    Utils.bitmapToMat(obj, mat)
    Imgproc.cvtColor(mat, mat, CvType.CV_8UC1)
    Imgproc.cvtColor(mat, mat, Imgcodecs.IMREAD_GRAYSCALE)
    return mat
}

Original image Bitmap to Mat converter: 原始图像位图到Mat转换器:

fun Bitmap.objToMat(): Mat {
    val mat = Mat(this.width, this.height, CvType.CV_8UC1)
    val obj = copy(Bitmap.Config.ARGB_8888, true)
    Utils.bitmapToMat(obj, mat)
    return mat
}

I'm recieving this error: 我收到此错误:

terminating with uncaught exception of type cv::Exception: OpenCV(4.1.0) D:\BGErase\app\src\main\cpp\guidedfilter.cpp:191: error: (-215:Assertion failed) I.channels() == 1 || I.channels() == 3 in function 'GuidedFilter'

So how to properly convert Bitmap to Mat? 那么如何将位图正确转换为Mat? Firstly, I wanted to pass Bitmaps into native functions, however this was very complicated. 首先,我想将位图传递给本机函数,但这非常复杂。

I decided to just save Bitmaps on external storage, because bitmap conversion process is 30-40% slower, and then just pass absolute paths into native function: 我决定只将位图保存在外部存储上,因为位图转换过程要慢30-40%,然后才将绝对路径传递给本机函数:

extern "C" JNIEXPORT jint JNICALL
Java_my_package_name_MyActivity_featherEdges(
        JNIEnv *env,
        jobject /* this */,
        jstring obj_path,
        jstring mask_path,
        jstring result_path) {

    cv::Mat I = cv::imread(ConvertJString(env, obj_path), cv::IMREAD_COLOR);
    cv::Mat p = cv::imread(ConvertJString(env, mask_path), cv::IMREAD_GRAYSCALE);

    int r = 60;
    double eps = 1e-6;
    eps *= 255 * 255;
    cv::Mat q = guidedFilter(I, p, r, eps);

    cv::imwrite(ConvertJString(env, result_path), q);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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