因为经常需要使用OpenCV,所以试下Kotlin如何使用OpenCV库
OpenCV导入
OpenCV有封装好的Android库,直接去这里下载:
OpenCV
下载好后在项目里通过Import Module导入到项目中
初始化
OpenCV在Application中初始化:
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
MMKV.initialize(this);
if (!OpenCVLoader.initDebug()){
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
private val mLoaderCallback: BaseLoaderCallback = object : BaseLoaderCallback(this) {
override fun onManagerConnected(status: Int) {
}
}
}
格式转换
-
首先加载Assets目录下图片,通过ImageView展示
var am = this.resources.assets; var inputStream = am.open("test.jpg"); var bitmap = BitmapFactory.decodeStream(inputStream); binding.iv1.setImageBitmap(bitmap);
-
Bitmap转Mat,然后转成灰度图
var mat = Mat(bitmap.width,bitmap.height,CvType.CV_8UC3); Utils.bitmapToMat(bitmap,mat); Imgproc.cvtColor(mat,mat,Imgproc.COLOR_RGB2GRAY);
绘制文字和图形
var point1 = Point(100.0, 100.0);
var point2 = Point(200.0, 200.0);
Imgproc.line(mat, point1, point2, rectScalar, 5);
Imgproc.putText(mat,"Hello",point1,4, 1.0,rectScalar,5);
最后再转Bitmap展示
var bitmap2 = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.RGB_565);
Utils.matToBitmap(mat,bitmap2);
binding.iv2.setImageBitmap(bitmap2);
效果如下: