本文主要是介绍实现Static Initialization从而不需要安装OpenCV Manager,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现Static Initialization就是指将OpenCV Library添加到app package中,不需要安装OpenCV Manager这个app就能运行,官方文档有介绍,但是不详细,尤其是最后那句代码到底要放在什么地方很多人都不清楚,其实并不需要像官方文档中介绍的那样配置,我想在这里介绍下如何修改FaceDetection项目的源码来做到这点。(最好是找一个包含jni代码的项目进行修改)
[1]打开jni下的Android.mk文件,修改OpenCV的那一部分,将off设置为on,并设置OpenCV_LIB_TYPE为SHARED,结果如下:
OpenCV_CAMERA_MODULES:=on
OpenCV_INSTALL_MODULES:=on
OpenCV_LIB_TYPE:=SHARED
include ${OpenCVROOT}/sdk/native/jni/OpenCV.mk
[2]打开FdActivity.java文件,在其中添加一个静态初始化块代码,它是用来加载OpenCV_java库的,由于FaceDetection中还用了另一个库detection_based_tracker(用于人脸跟踪),所以要在else子句中加载进来:
static {Log.i(TAG, "OpenCV library load!");if (!OpenCVLoader.initDebug()) {Log.i(TAG, "OpenCV load not successfully");} else {System.loadLibrary("detection_based_tracker");// load other libraries}
}
[3]删除FdActivity.java的OnResume()方法的最后那句,不让它去访问OpenCV Manager。
@Override
public void onResume() {super.onResume();
//OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);//
}
[4]修改FdActivity.java的OnCreate()方法,从上面的private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this)代码块中拷贝try-catch块放到OnCreate的setContentView()之后,然后拷贝mOpenCVCameraView.enableView();放到mOpenCVCameraView = (CameraBridgeViewBase) findViewById(R.id.fd_activity_surface_view);之后,修改后的OnCreate()方法如下:
public void onCreate(Bundle savedInstanceState) {Log.i(TAG, "called onCreate");super.onCreate(savedInstanceState);getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);setContentView(R.layout.face_detect_surface_view);//try {// load cascade file from application resourcesInputStream is = getResources().openRawResource(R.raw.lbpcascade_frontalface);File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");FileOutputStream os = new FileOutputStream(mCascadeFile);byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = is.read(buffer)) != -1) {os.write(buffer, 0, bytesRead);}is.close();os.close();mJavaDetector = new CascadeClassifier(mCascadeFile.getAbsolutePath());if (mJavaDetector.empty()) {Log.e(TAG, "Failed to load cascade classifier");mJavaDetector = null;} elseLog.i(TAG, "Loaded cascade classifier from " + mCascadeFile.getAbsolutePath());mNativeDetector = new DetectionBasedTracker(mCascadeFile.getAbsolutePath(), 0);cascadeDir.delete();} catch (IOException e) {e.printStackTrace();Log.e(TAG, "Failed to load cascade. Exception thrown: " + e);}mOpenCVCameraView = (CameraBridgeViewBase)findViewById(R.id.fd_activity_surface_view);mOpenCVCameraView.enableView();//mOpenCVCameraView.setCvCameraViewListener(this);
}
[5]OK,卸载安装好的OpenCV Manager,然后重新调试运行FaceDetection试试,它已经可以自行运行了!
这篇关于实现Static Initialization从而不需要安装OpenCV Manager的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!