构建环境:
OpenCV官网下载最新的OpenCV for Android SDK.我的版本是3.2.
解压目录如下:
打开sdk文件夹
可以看到java native etc三个文件夹。
java文件夹下是一个java library。可以直接导入到android studio中。
导入以后
添加依赖:
然后就可以使用了。
如果在项目中可以import JavaCameraView表明opencv库加载成功。
使用OpenCV Java库实现相机预览:
首先添加使用相机的权限。
下面是代码,比较简单:
package erg.opencv;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.InstallCallbackInterface;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
static String TAG = "MainActivity";
private JavaCameraView JavaCameraView;
private Mat Mat;
LoaderCallbackInterface LoaderCallbackInterface = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case org.opencv.android.LoaderCallbackInterface.SUCCESS:
JavaCameraView.enableView();
break;
default: {
super.onManagerConnected(status);
}
}
}
@Override
public void onPackageInstall(int operation, InstallCallbackInterface callback) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JavaCameraView = (org.opencv.android.JavaCameraView) findViewById(R.id.CameraView);
JavaCameraView.setVisibility(SurfaceView.VISIBLE);
JavaCameraView.setCvCameraViewListener(this);
}
@Override
public void onCameraViewStarted(int width, int height) {
Mat = new Mat(height, width, CvType.CV_8UC4);
}
@Override
public void onCameraViewStopped() {
Mat.release();
}
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Mat = inputFrame.rgba();
return Mat;
}
@Override
protected void onStart() {
super.onStart();
if (OpenCVLoader.initDebug()) {
Log.d(TAG, "Opencv Success");
LoaderCallbackInterface.onManagerConnected(BaseLoaderCallback.SUCCESS);
} else {
Log.d(TAG, "Opencv fail");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_2_0, this, LoaderCallbackInterface);
}
}
@Override
protected void onPause() {
super.onPause();
JavaCameraView.disableView();
}
@Override
protected void onResume() {
super.onResume();
JavaCameraView.enableView();
}
@Override
protected void onDestroy() {
super.onDestroy();
JavaCameraView.disableView();
}
}