将一个Mat对象从jni返回给java

时间:2014-01-29 11:17:02

标签: java opencv java-native-interface

有人可以帮助我使用从本机c到java的对象数组返回吗? 我做了很大一部分,只需要设置Mat字段。

getFaces()函数应返回Face[]数组。 面部对象包含opencv.core.Rectopencv.core.Matintintint fields

JNIEXPORT jobjectArray JNICALL Java_com_faceprocessing_PersonDetector_nativeGetFaces (JNIEnv * jenv, jclass) {

if (faceContainer.size()==0) return NULL;

jclass faceClass = jenv->FindClass("com/faceprocessing/Face");

jmethodID faceCtorID = jenv->GetMethodID(faceClass, "<init>", "()V");
jfieldID facePosID = jenv->GetFieldID(faceClass, "Position", "Lorg/opencv/core/Rect;");
jfieldID faceIDID = jenv->GetFieldID(faceClass, "PredictedID", "I");
jfieldID faceGenderID = jenv->GetFieldID(faceClass, "PredictedGender", "I");
jfieldID faceAgeID = jenv->GetFieldID(faceClass, "PredictedAge", "I");

jclass rectClass = jenv->FindClass("org/opencv/core/Rect");
jmethodID rectCtorID = jenv->GetMethodID(rectClass, "<init>", "(IIII)V");

jclass matClass = jenv->FindClass("org/opencv/core/Mat");


int correctCount = 0;
for (int i=0; i<faceContainer.size(); i++) {
    Face* pFace = faceContainer.at(i);
    if (!pFace->isError) correctCount++;
}

jobjectArray jFaceArray = jenv->NewObjectArray(correctCount, faceClass, NULL);

int j=0;
for (int i=0; i<faceContainer.size(); i++) {

    Face* pFace = faceContainer.at(i);
    if (pFace->isError) continue;
    jobject jFace = jenv->NewObject(faceClass, faceCtorID);
    jobject jRect = jenv->NewObject(rectClass, rectCtorID, pFace->facePosition->x, pFace->facePosition->y, pFace->facePosition->width, pFace->facePosition->height);
    jenv->SetObjectField(jFace, facePosID, jRect);
    jenv->SetIntField(jFace, faceIDID, pFace->predictedID);
    jenv->SetIntField(jFace, faceGenderID ,pFace->predictedGender);
    jenv->SetIntField(jFace, faceAgeID, pFace->predictedAge);
    jenv->SetObjectArrayElement(jFaceArray,j,jFace);
    j++;
}

return jFaceArray;
}

1 个答案:

答案 0 :(得分:0)

如果我是你,我不会返回cv::Mat数组。我每次都会返回一个cv::Mat,并根据需要多次调用该函数在Java端创建数组。

所以基本上,我会有一个函数来获取数组的大小。另一个从面容器中获取面部图像的功能。

如果您不知道如何返回cv::Mat,请告诉我。

希望这有帮助。