安卓如何在java中调用nativelib的对象
我正在做一个文档扫描仪。我正在使用opencv进行图像处理。在摄影机视图中,我在最大轮廓上包围矩形。正确地检测最大轮廓。现在我只想捕获用本机lib编写的boudingRect。cpp。所以我想要java类中本机库的对象。帮我弄到那个
本机库。cpp
extern "C"
JNIEXPORT void JNICALL
Java_prisca_ctest_OpenCvCamera_doWithMat(JNIEnv *env, jobject instance, jlong matAddrGr,
jlong matAddrRgba) {
try {
Mat &image = *(Mat *) matAddrRgba;
Rect bounding_rect;
Mat thr(image.rows, image.cols, CV_8UC1);
cvtColor(image, thr, CV_BGR2GRAY); //Convert to gray
threshold(thr, thr, 150, 255, THRESH_BINARY + THRESH_OTSU); //Threshold the gray
vector<vector<Point> > contours; // Vector for storing contour
vector<Vec4i> hierarchy;
findContours(thr, contours, hierarchy, CV_RETR_CCOMP,
CV_CHAIN_APPROX_SIMPLE); // Find the contours in the image
sort(contours.begin(), contours.end(),
compareContourAreas); //Store the index of largest contour
bounding_rect = boundingRect((const _InputArray &) contours[0]);
rectangle(image, bounding_rect, Scalar(250, 250, 250) , 5);
} catch (int a) {
}
}
活动
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cam);
mOpenCvCameraView = (JavaCameraView) findViewById(R.id.tutorial1_activity_java_surface_view);
mOpenCvCameraView.setVisibility(View.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnCapture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String timestamp = new SimpleDateFormat("ddMMyyyy_HHmmss", Locale.US).format(new Date());
File imgFolder = new File(FILE_LOCATION);
imgFolder.mkdir();
File image = new File(imgFolder, "Scan" + timestamp + ".jpg");
String fileName = FILE_LOCATION +
"/Scan" + timestamp + ".jpg";
Toast.makeText(OpenCvCamera.this, image + " saved", Toast.LENGTH_SHORT).show();
Imgcodecs.imwrite(fileName, mRgba);
}
}) ;
}
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
// input frame has RGBA format
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
doWithMat(mGray.getNativeObjAddr(), mRgba.getNativeObjAddr());
return mRgba;
}
我应该在Imgcodecs上面添加什么。imwrite(文件名,mRgba)裁剪矩阵并仅保存boundingRect部分
# 1 楼答案
假设您想调用本机JNI方法
Java_prisca_ctest_OpenCvCamera_doWithMat
首先,要从Java端调用这个方法,需要声明它。要声明它,您需要了解该方法的名称,它为您提供了所需的一切:
Java\u prisca\u ctest\u OpenCvCamera\u doWithMat:这意味着这将由Java执行
Java\ustrong>prisca\u ctest\u OpenCvCamera\u doWithMat:这部分是类的包
Java_prisca_ctest_strong>OpenCvCamera\u doWithMat:这部分是Java类的名称
Java_prisca_ctest_OpenCvCamera_doWithMat:这部分是方法的名称
考虑到这一点,我们需要知道参数。在这种情况下很容易:两个
jlong
参数转换为Javalong
创建一个
OpenCvCamera.java
类,并将其放入其中:现在可以通过导入类并调用
OpenCvCamera.doWithMat(long, long)
来调用该方法。请注意,这可能不是100%正确,我对JNI不太在行(尤其是在脑海中写下它),但这应该让你开始:)