OpenCV3.4.1快速集成到Android studio中,10分钟搞定
1.下载地址(官网)
https://www.opencv.org/opencv-3-4-1.html
2.导入Module
3.删除以下代码
在OpenCV模块的清单文件中删除以下代码
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" />
4.配置OpenCVLibrary341的SDK版本
在build.gradle(Module:OpenCVLibrary341)中,修改以下属性
改为和build.gradle(Module:app)中的值一样
compileSdkVersion
minSdkVersion
targetSdkVersion
5.复制armeabi-v7a文件夹到项目的libs目录下(注意要有文件夹)
复制成功后,也可以删除掉其他的.a文件,只保留libopencv_java3.so
6.添加依赖
dependencies {
...
//让app包,与新添加的这个OpenCV库关联
implementation project(':openCVLibrary341')
//将打好jar包,添加到依赖中
implementation fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
}
//以下很重要
//将添加的.so文件,打包成jar
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)
}
7.初始化,图像转成灰色测试
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//初始化
if (OpenCVLoader.initDebug()) {
Toast.makeText(this, "OpenCVLoader初始化成功", Toast.LENGTH_SHORT).show();
}
//测试灰度
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
convert2Grey();
}
});
}
private void convert2Grey() {
Mat src = new Mat();//Mat是OpenCV的一种图像格式
Mat temp = new Mat();
Mat dst = new Mat();
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.mipmap.bd_logo1);
Utils.bitmapToMat(bitmap, src);
Imgproc.cvtColor(src, temp, Imgproc.COLOR_RGB2BGR);
Imgproc.cvtColor(temp, dst, Imgproc.COLOR_BGR2GRAY);
Utils.matToBitmap(dst, bitmap);
imageView.setImageBitmap(bitmap);
//
src.release();
temp.release();
dst.release();
}
private void initView() {
imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);
}
}