根据最新android studio跟opencv折腾了一番不用opencvmanager的工程,备忘一下;
1.环境配置
1、Android Studio下载
2、 opencv 下载
见官网opencv.org 下载android下opencv包;
2.建立工程
1、
点击下一步,填写工程名字。点击finish后开始添加opencv库
2、添加opencv
File---->new----->import Module 选择opencv安装文件夹下的OpenCV-android-sdk\sdk\java文件夹
3、
直接点完finish工程建立完成。这时点击那个小锤子,会提示下出的错误。
主要是因为opencv3.4.5中把<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" />
这名话写在了 AndroidManifest.xml中,去这个文件中把其删除就可以了。
4、File---->Project Struct 设置Dependencies
点击OK即可。
4、为了不下载OpenCVmanager
在src---->main下新建一个文件libs , 将Opencv中sdk下的native中的libs中的文件复制到该文件夹下;
可是这些文件很大,可以任取一个出来,基本上都是这个数据结构,不过只有.so文件才是我们真正需要的,这里可以把其他文件全部删除,只留下.so文件即可,这样的话文件就比较小了。
在app-build.gradle中的android节点中加入自定义 jni的地址。
sourceSets {
main {
jniLibs.srcDirs = ['src/main/libs']
}
}
5、添加app的依赖 整个app下的build.gradle如下
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.opencvtest"
minSdkVersion 24
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
// ndk {
// abiFilters("armeabi", "armeabi-v7a", "x86", "mips")
// }
sourceSets {
main {
jniLibs.srcDirs = ['src/main/libs']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation project(':openCVLibrary345')
}
task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
from fileTree(dir: 'libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
6、
更改openCVLibrary345下的gradle文件中的相关属性。在这里主要涉及四个属性compileSdkVersion、buildToolsVersion、minSdkVersion、targetSdkVersion 更改后同步一下即可
7、androidMainfest.xml 如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.opencvtest">
android:versionCode="1"
android:versionName="1.0" >
<supports-screens android:resizeable="true"
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true" />
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
8、layout下xml如下
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:opencv="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<org.opencv.android.JavaCameraView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
android:id="@+id/tutorial1_activity_java_surface_view"
opencv:show_fps="true"
opencv:camera_id="any" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/buttonGray"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="@string/app_name"
/>
</RelativeLayout>
</FrameLayout>
9、测试代码如下:
public class MainActivity extends Activity implements CvCameraViewListener2 {
private static final String TAG = "OCVSample::Activity";
private CameraBridgeViewBase mOpenCvCameraView;
private boolean mIsJavaCamera = true;
private MenuItem mItemSwitchCamera = null;
private Mat mRgba;
private Button mBtn = null;
private boolean isProcess = false;
//建立连接
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
//构造函数
public MainActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
//onCreate函数
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
//
if (mIsJavaCamera)
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_java_surface_view);
// else
// mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_native_surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
mBtn = (Button) findViewById(R.id.buttonGray);
mBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
isProcess = !isProcess;
}
});
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onResume()
{
super.onResume();
if(!OpenCVLoader.initDebug()){
Log.d(TAG,"Internal OpenCV library not found. Using OpenCV manger for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_4_0,this,mLoaderCallback);
}else{
Log.d(TAG,"OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "called onCreateOptionsMenu");
mItemSwitchCamera = menu.add("Toggle Native/Java camera");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String toastMesage = new String();
Log.i(TAG, "called onOptionsItemSelected; selected item: " + item);
if (item == mItemSwitchCamera) {
mOpenCvCameraView.setVisibility(SurfaceView.GONE);
mIsJavaCamera = !mIsJavaCamera;
if (mIsJavaCamera) {
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_java_surface_view);
toastMesage = "Java Camera";
}
// else {
// mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_native_surface_view);
// toastMesage = "Native Camera";
// }
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
mOpenCvCameraView.enableView();
Toast toast = Toast.makeText(this, toastMesage, Toast.LENGTH_LONG);
toast.show();
}
return true;
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
}
public void onCameraViewStopped() {
mRgba.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
if(isProcess)
Imgproc.cvtColor(inputFrame.gray(), mRgba, Imgproc.COLOR_GRAY2RGBA, 4);
else
mRgba = inputFrame.rgba();
return mRgba;
}
}
工程下载目录为:
https://download.youkuaiyun.com/download/jaccen/11065911
补充 CMAKE库加载:
把从opencv官网中下载好的android包解压,你将看到如下文件结构
opencv静态库文件目录结构
opencv头文件目录结构
我们需要做的就是把.a
,.so
静态库动态库和头文件
加入到Android项目中去
项目中的目录结构
CMakeLists.txt
如下:
cmake_minimum_required(VERSION 3.4.1)
set(JNI_DIR "${CMAKE_SOURCE_DIR}/src/main/jni")
set(CPP_DIR "${CMAKE_SOURCE_DIR}/src/main/cpp")
add_library( native-lib
SHARED
src/main/cpp/native-lib.cpp )
#添加第三方mtnn.so库
add_library(mtnn
SHARED
IMPORTED)
set_target_properties(mtnn
PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libmtnn.so )
# 指定头文件路径
include_directories(${JNI_DIR}/${ANDROID_ABI}/include/)
# 添加opencv
include_directories(${CPP_DIR}/opencv_include/)
add_library(libopencv_calib3d STATIC IMPORTED)
set_target_properties(libopencv_calib3d PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_calib3d.a)
add_library(libopencv_core STATIC IMPORTED)
set_target_properties(libopencv_core PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_core.a)
add_library(libopencv_dnn STATIC IMPORTED)
set_target_properties(libopencv_dnn PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_dnn.a)
add_library(libopencv_features2d STATIC IMPORTED)
set_target_properties(libopencv_features2d PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_features2d.a)
add_library(libopencv_flann STATIC IMPORTED)
set_target_properties(libopencv_flann PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_flann.a)
add_library(libopencv_highgui STATIC IMPORTED)
set_target_properties(libopencv_highgui PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_highgui.a)
add_library(libopencv_imgcodecs STATIC IMPORTED)
set_target_properties(libopencv_imgcodecs PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_imgcodecs.a)
add_library(libopencv_imgproc STATIC IMPORTED)
set_target_properties(libopencv_imgproc PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_imgproc.a)
add_library(libopencv_ml STATIC IMPORTED)
set_target_properties(libopencv_ml PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_ml.a)
add_library(libopencv_objdetect STATIC IMPORTED)
set_target_properties(libopencv_objdetect PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_objdetect.a)
add_library(libopencv_photo STATIC IMPORTED)
set_target_properties(libopencv_photo PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_photo.a)
add_library(libopencv_shape STATIC IMPORTED)
set_target_properties(libopencv_shape PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_shape.a)
add_library(libopencv_stitching STATIC IMPORTED)
set_target_properties(libopencv_stitching PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_stitching.a)
add_library(libopencv_superres STATIC IMPORTED)
set_target_properties(libopencv_superres PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_superres.a)
add_library(libopencv_video STATIC IMPORTED)
set_target_properties(libopencv_video PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_video.a)
add_library(libopencv_videoio STATIC IMPORTED)
set_target_properties(libopencv_videoio PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_videoio.a)
add_library(libopencv_videostab STATIC IMPORTED)
set_target_properties(libopencv_videostab PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_videostab.a)
add_library(libopencv_java3 SHARED IMPORTED)
set_target_properties(libopencv_java3 PROPERTIES IMPORTED_LOCATION
${JNI_DIR}/${ANDROID_ABI}/libopencv_java3.so)
find_library( log-lib log )
target_link_libraries( native-lib mtnn
libopencv_calib3d
libopencv_core
libopencv_dnn
libopencv_features2d
libopencv_flann
libopencv_highgui
libopencv_imgcodecs
libopencv_imgproc
libopencv_ml
libopencv_objdetect
libopencv_photo
libopencv_shape
libopencv_stitching
libopencv_superres
libopencv_video
libopencv_videoio
libopencv_videostab
libopencv_java3
${log-lib}
)
build.gradle
如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.xxx.xxx"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
// 重点
cmake {
cppFlags "-std=c++11 -frtti -fexceptions"
}
}
// 重点
ndk {
abiFilter 'armeabi-v7a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
// 重点
sourceSets.main {
jniLibs.srcDirs('src/main/jni')
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}