可能是版本问题,之前我在网上找到的那些不需要OpenCV Manager的教程都不能使用。
在官网中下载:https://opencv.org/releases/
选择 Menu -> “File” -> “New” -> “New Module” -> “Import Gradle project”
这种方法会将所有的OpenCV Android SDK内容拷贝到项目中,约200MB
选择openCV-android-sdk目录下的sdk文件夹,module名称改为:opencv
如果报错:A problem occurred evaluating project ‘:opencv’. Plugin with id ‘kotlin-android’ not found.,则注释掉build.grandle中的apply plugin: ‘kotlin-android’,
注意修改grandle的sdkVersion,修改到和项目相同。
然后同步(Sync Now)
此时可能会有没有安装CMAKE tool或者让你安装NDK之类的,
此时检查下setting.grandle是否包含类似的内容, 如果没有需要手动添加,正常情况下是有的:
include ':opencv'
project(':opencv').projectDir = new File(rootDir, 'OpenCV-android-sdk/sdk/')
在app/build.grandle中加入:
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':opencv')
加入后的样子:
此时OpenCV环境配置完成
在使用openCV时,需要加载库:
下面的两句任选则一句,添加在一个使用openCV之前的位置。
System.loadLibrary("opencv_java4");
OpenCVLoader.initDebug();
之后可用正常使用openCV库,进行一个简单测试:
package com.example.opencvtest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import static org.opencv.imgproc.Imgproc.COLOR_RGBA2BGRA;
import static org.opencv.imgproc.Imgproc.cvtColor;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
verifyStoragePermissions(this);
ImageView iv = findViewById(R.id.iv);
System.loadLibrary("opencv_java4");
String path = Environment.getExternalStorageDirectory().getPath()+"/Saber.JPG";
Mat a = Imgcodecs.imread(path);
Bitmap bitmap = Bitmap.createBitmap(a.height(),a.width(), Bitmap.Config.ARGB_8888);
a.convertTo(a, CvType.CV_8UC3);
cvtColor(a, a, COLOR_RGBA2BGRA);
Utils.matToBitmap(a,bitmap);
iv.setImageBitmap(bitmap);
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}