最近项目有个需求需要实现物体追踪和人脸识别 ,需要Android实现对图像的处理用到opencv4android 做点笔记。
首先Android中使用opencv要下载个opencv官网接着配置环境 以前文章写过 这里就不赘述了opencv环境配置及免安装第三方软件
接下来就是布局,这里只需要一个按钮和一张图片就可以了,有两张图片一个是去灰度前,一个是后
<Button
android:id="@+id/top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start"
android:onClick="startTest"
android:layout_centerHorizontal="true"
/>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:src="@drawable/z"
android:layout_centerHorizontal="true"
android:background="@color/black"
android:layout_below="@+id/top"
/>
<ImageView
android:id="@+id/img_result"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:src="@drawable/z"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_below="@+id/img"
android:layout_marginTop="20dp"
android:background="@color/black"
/>
接着是核心代码 里面有注释
public static Bitmap setGray(Context context) {
//获取bitmap数据
Bitmap bitmap =getBitmap(R.drawable.z,context);
//bitmap 对象转换成 mat 对象 opencv使用的是mat对象
Mat src=new Mat();
Utils.bitmapToMat(bitmap,src);
//转化灰度结果 保存的mat
Mat dst=new Mat();
//转化成灰度图片
Imgproc.cvtColor(src,dst,Imgproc.COLOR_BGR2GRAY);
//转化会bitmat 对象
Utils.matToBitmap(dst,bitmap);
//释放资源
src.release();
dst.release();
return bitmap;
}
最后在同个imageView.setImageBitmap()设置回去 搞定!
if (mBitmap != null) {
Log.i(TAG, "startTest: !null");
mImgResult.setImageBitmap(mBitmap);
}
这个是源码opencvDemon