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

时间:2019-07-14 15:40:11

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

我想在带有集成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);
}

科特林侧掩模的位图到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'

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

1 个答案:

答案 0 :(得分:0)

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