【问题标题】:How to properly convert Bitmap to OpenCV grayscale Mat如何正确将位图转换为 OpenCV 灰度垫
【发布时间】:2019-11-23 12:17:51
【问题描述】:

我想在带有集成 OpenCV 模块的 Android 项目中使用 this library

本机功能代码:

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 端掩码 Bitmap 到 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
}

原始图像位图到 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
}

我收到此错误:

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'

那么如何正确地将 Bitmap 转换为 Mat 呢?首先,我想将位图传递给原生函数,但这非常复杂。

【问题讨论】:

    标签: android c++ opencv kotlin android-ndk


    【解决方案1】:

    我决定只将位图保存在外部存储上,因为位图转换过程要慢 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 2015-10-07
      • 2013-12-15
      • 2020-04-25
      • 2021-04-05
      相关资源
      最近更新 更多