I am working on an android project to process images using Opencv. I wrote an android jni function that should return a vector but I can't figure out how to do that right.
I tried to convert the vector to jobjectArray but it's not working. Here is the code I'm working on:
jobjectArray
Java_com_grimg_testtt_MainActivity_getQuadrilateral(
JNIEnv *env,
jobject /* this */,
cv::Mat & grayscale,
cv::Mat & output) {
std::vector<std::string> vec;
cv::Mat approxPoly_mask(grayscale.rows, grayscale.cols, CV_8UC1);
approxPoly_mask = cv::Scalar(0);
std::vector<std::vector<cv::Point>> contours;
std::vector<int> indices(contours.size());
std::iota(indices.begin(), indices.end(), 0);
sort(indices.begin(), indices.end(), [&contours](int lhs, int rhs) {
return contours[lhs].size() > contours[rhs].size();
});
/// Find the convex hull object for each contour
std::vector<std::vector<cv::Point>> hull(1);
cv::convexHull(cv::Mat(contours[indices[0]]), hull[0], false);
std::vector<std::vector<cv::Point>> polygon(1);
approxPolyDP(hull[0], polygon[0], 20, true);
drawContours(approxPoly_mask, polygon, 0, cv::Scalar(255));
//imshow("approxPoly_mask", approxPoly_mask);
if (polygon[0].size() >= 4) // we found the 4 corners
{
return(polygon[0]);
}
return(std::vector<cv::Point>());
}
In the last two lines I'm getting this error which is obvious:
Returning 'std::vector<cv::Point> &' from a function returning 'jobjectArray': Types 'jobjectArray' and 'std::vector<cv::Point>' are not compatible.
What can I do to get over this problem?
Edit :
jclass clazz = (*env).FindClass("java/util/ArrayList");
jobjectArray result = (*env).NewObjectArray(polygon[0].size(), clazz, 0);
if (polygon[0].size() >= 4) // we found the 4 corners
{
for (int n=0;n<polygon[0].size();n++)
{
cv::Point point = (cv::Point) static_cast<cv::Point>(polygon[0][n]);
(*env).CallVoidMethod(result, (*env).GetMethodID(clazz, "add", "(java/lang/Object)V"), point);
}
return result;
}
return result;
}
Edit 2 :
jclass ptCls = env->FindClass("java/awt/Point");
jobjectArray result = (*env).NewObjectArray(polygon[0].size(), ptCls, NULL);
if (result == NULL) return NULL;
if (polygon[0].size() >= 4) // we found the 4 corners
{
for (int n=0;n<polygon[0].size();n++)
{
jobject point = (jobject) static_cast<jobject>(polygon[0][n]);
//(*env).CallVoidMethod(result, (*env).GetMethodID(ptCls, "add", "(java/lang/Object)V"), polygon[0][n]);
(*env).SetObjectArrayElement(result, polygon[0].size(), point);
}
return result;
}
return result;
Error
error: cannot cast from type 'std::__ndk1::__vector_base<cv::Point_<int>, std::__ndk1::allocator<cv::Point_<int> > >::value_type' (aka 'cv::Point_<int>') to pointer type 'jobject' (aka '_jobject *')
jobject point = (jobject) static_cast<jobject>(polygon[0][n]);