Android JNI中jfloatArray与jfloat*的相互转换

         本人近期在写JNI时,本地native传入的数据类型是float[] xx,对应的jni的参数类型即为jfloatArray xx,那么如何读取jfloatArray xx中的数据呢,具体详见本人的实践代码部分“jfloatArray转vector<float>”。

         同时在JNI中本人还遇到需要将std::vector<float>类型的数据转为jfloatArray类型后作为返回值返回。该部分的实现详见本人实践代码部分“vector<float>转jfloatArray”。

        虽然本人提供的转换代码仅仅是float类型的数据,但是可以据此参考转换适用于其他类型的数据转换。

一、JNI中“jfloatArray转vector<float>”

extern "C"
JNIEXPORT jfloat JNICALL
Java_com_xxxx_xxxx_xxxx_GetScore(JNIEnv *env, jobject thiz,
                                                         jfloatArray feature1,
                                                         jfloatArray feature2) {
    // TODO: implement GetScore()
    jfloat* featureData1 = (jfloat*)env->GetFloatArrayElements(feature1, 0);
    jsize featureSize1 = env->GetArrayLength(feature1);
    jfloat* featureData2 = (jfloat*)env->GetFloatArrayElements(feature2, 0);
    jsize featureSize2 = env->GetArrayLength(feature2);
    std::vector<float> featureVector1(featureSize1), featureVector2(featureSize1);
    if(featureSize1 != featureSize2){
        return 0;
    }

    for(int i=0; i < featureSize1; i++){
        featureVector1.push_back(featureData1[i]);
        featureVector2.push_back(featureData2[i]);
    }
    float score = faceFeature->GetScore(featureVector1, featureVector2);
    return score;
}

二、JNI中“vector<float>转jfloatArray”

extern "C"
JNIEXPORT jfloatArray JNICALL
Java_com_xxxx_xxxx_xxxxx_GetFaceFeature(JNIEnv *env, jobject thiz,
                                                               jobject bitmap) {
    // TODO: implement ForwardFaceFeature()
    cv::Mat mat;
    BitmapToMatrix(env, bitmap, mat);
    if(mat.channels()==4){
        cv::cvtColor(mat, mat, CV_RGBA2BGR);
    }else{
        cv::cvtColor(mat, mat, CV_RGB2BGR);
    };

    if(mat.empty()){
        return nullptr;
    }

    std::vector<float> faceFeatureData{};
    std::vector<std::vector<cv::Point2f>> key_pts;
    std::vector<cv::Rect> faces = faceDetect->GetMaximumFace(mat, key_pts);
    if((faces.size()<1)){
        __android_log_print(ANDROID_LOG_DEBUG, "FaceFeature", "fail to detect face.");
        return nullptr;
    }
    std::vector<cv::Mat> norm_face = faceAlign->GetAlignedFace(mat, key_pts, false);

    // Extract Face Feature
    faceFeatureData = faceFeature->GetFeature(norm_face[0]);

    jfloatArray faceFeatureArray = env->NewFloatArray(faceFeatureData.size());

    env->SetFloatArrayRegion(faceFeatureArray, 0, faceFeatureData.size(), faceFeatureData.data());
    return faceFeatureArray;
}

注:暂不提供bitmap转mat示例代码。

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页