本文叙述使用Android Studio新建OpenCV工程。
1.构建OpenCV环境
下载Opencv for Android
新建一个工程
1.1导入OpenCV Module
File --> New --> Import Module
修改openCVLibrary410/build.gradle
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
defaultConfig {
// applicationId "org.opencv"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
1.2导入OPenCV的依赖
File --> Project Structure
将OpenCV-android-sdk\sdk\native\libs下所有文件夹复制到工程目录中的app\libs中,并在app模块对应的build.gradle中增加如下内容:
sourceSets{
main{
jniLibs.srcDirs=['libs']
}
}
在MainActivity中增加代码
if (OpenCVLoader.initDebug()) {
Log.i(TAG, "Loaded successfully...");
} else {
Log.i(TAG, "Can not to loaded...");
}
编译并运行app,在logcat中会出现如下内容
2.测试
1.res/drawable中添加一个图片
2.修改activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView1"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pikaqiu" />
<ImageView
android:id="@+id/imageView2"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/pikaqiu" />
</LinearLayout>
修改MAinActivity.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
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 static final String TAG = "MainActivity";
ImageView[] imageView = new ImageView[2];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (OpenCVLoader.initDebug()) {
Log.i(TAG, "Loaded successfully...");
} else {
Log.i(TAG, "Can not to loaded...");
}
imageView[0] = findViewById(R.id.imageView1);
imageView[1] = findViewById(R.id.imageView2);
Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.youname);
Bitmap grayBitmap = rgb2gray(srcBitmap);
imageView[0].setImageBitmap(srcBitmap);
imageView[1].setImageBitmap(grayBitmap);
}
public Bitmap rgb2gray(Bitmap rgbBm){
Mat rgbMat = new Mat();
Mat grayMat = new Mat();
Bitmap grayBm = Bitmap.createBitmap(rgbBm.getWidth(),
rgbBm.getHeight(),
Bitmap.Config.RGB_565);
Utils.bitmapToMat(rgbBm, rgbMat);
Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
Utils.matToBitmap(grayMat, grayBm);
rgbMat.release();
grayMat.release();
Log.i(TAG, "procSrc2Gray sucess...");
return grayBm;
}
}
编译并运行app,出现如下结果说明环境搭建成功了: