前言
开发环境
- Ubuntu 18.04
- Android Studio 3.2
- opencv for android sdk
功能介绍
- 加载opencv库
- 加载Adaboost 人脸检测模型
- 可以配置参数,灵活
- 模型可选
- 图片可从图库、相机两种方式读取
App界面设计
-
主界面, 可以在Menu中设置参数
主界面 -
设置人脸检测的参数
-
scaleFactor 缩放因子
-
minNeighbors 最小相邻数
-
minSize 最小人脸尺寸
-
maxSize 最大人脸尺寸
- 人脸检测界面 4.png
-
打开相机/图库界面
3.png -
人脸检测
5.jpg -
人脸检测结果
6.jpg
Android App流程
App流程比较简单,在人脸检测过程中,算法计算在子线程中运行,避免UI线程卡死。
- 动态权限申请
- 设置人脸检测参数(可选,默认参数)
- 后台线程运行模型加载,初始化
- 从图库、相机选择图片
- 执行人脸检测,后台开启一个线程
App功能实现
人脸检测算法实现
人脸检测算法采用OpenCV Adaboost级联分类器:
- CascadeClassifier
在 opencv for android sdk中已经提供了训练好的模型,xml文件:
image.png
image.png
image.png
在Android端,需要导入opencv 模块:
image.png image.png
人脸检测用到的类
opencv实现人脸检测非常简单,为了程序结果清晰化,新建一个JAVA类 FaceDetector, 包含3个方法:
- 构造方法
- init(): 进行检测器初始化
- detect(): 人脸检测
init: 需要设置人脸检测相关参数
detect: 输入为Mat 对象, BGR图像, 输入为一些列矩形框,因此采用Rect[]数组表示
package com.face.detection.adaboost;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Size;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.Objdetect;
import static org.opencv.imgproc.Imgproc.COLOR_BGR2GRAY;
import static org.opencv.imgproc.Imgproc.cvtColor;
public class FaceDetector {
private String modelName;
private CascadeClassifier classifier;
private double scaleFactor;
private int minNeighbors;
private Size minSize;
private Size maxSize;
private Mat imgGray;
private MatOfRect objects;
public FaceDetector(String modelName){
this.modelName = modelName;
imgGray = new Mat();
objects = new MatOfRect();
}
public boolean init(double scaleFactor, int minNeighbors, Size minSize, Size maxSize){
classifier = new CascadeClassifier(this.modelName);
this.scaleFactor = scaleFactor;
this.minNeighbors = minNeighbors;
this.minSize = minSize;
this.maxSize = maxSize;
return !classifier.empty();
}
public Rect[] detect(Mat imgBGR){
cvtColor(imgBGR, imgGray, COLOR_BGR2GRAY);
classifier.detectMultiScale(imgGray, objects,scaleFactor,minNeighbors, Objdetect.CASCADE_SCALE_IMAGE, minSize, maxSize);
if (objects.empty()){
return null;
}else {
return objects.toArray();
}
}
}
App交互逻辑设计
App比较简单,总共设计了3个界面,即3个Activity
image.png-
MainActivity
界面布局
MainActivity内的主要功能:
-
动态授权
App需要SD卡读写、相机权限。android6.0之后必须在代码中动态申请权限。
首先,在Manifest.xml中填写App需要的权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"
Java代码:
需要的权限
public static final String[] permissions =
{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
动态申请
首先判断版本,6.0之后动态申请
int k=0;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
for (String permission:Utils.permissions){
if (checkSelfPermission(permission)!=PackageManager.PERMISSION_GRANTED){
requestPermissions(Utils.permissions, 1234);
}else{
k++;
}
}
if (k==Utils.permissions.length){
backTsk.start();
}
}else{
backTsk.start();
}
授权回调函数
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==1234){
int k= 0 ;
for (int i=0;i<permissions.length;i++){
if (grantResults[i]==PackageManager.PERMISSION_DENIED){
Toast.makeText(this, permissions[i]+"申请失败!", Toast.LENGTH_SHORT).show();
}else{
k++;
}
}
if (k==Utils.permissions.length){
backTsk.start();
}
}
}
- 后台线程进行模型复制
因为CascadeClassifier分类器需要加载xml模型,在android工程中首先将xml模型复制到assets, 之后在SD卡创建目录,保存模型。
image.pngJava
private Thread backTsk = new Thread(new Runnable() {
@Override
public void run() {
Utils.createAppWorksapce();
try {
Utils.copyAssert(MainActivity.this);
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject jsonObject = Utils.loadParamFromJSON(Utils.mainWorksapce+File.separator+Utils.configParamFileName);
scaleFactor = jsonObject.getDouble("scaleFactor");
minNeighbors = jsonObject.getInt("minNeighbors");
minSize = jsonObject.getInt("minSize");
maxSize = jsonObject.getInt("maxSize");
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
btnStart.setEnabled(true);
}
});
}
});
public static void createAppWorksapce(){
String[] files = {mainWorksapce, modelWorkspace, picWorksapce};
for (String file:files){
if (!new File(file).exists()){
boolean ok = new File(file).mkdir();
}
}
}
public static void copyAssert(Context context) throws IOException {
android.content.res.AssetManager manager = context.getAssets();
String[] strs = modelListName;
int k=0;
for (String name:modelListName){
if (new File(modelWorkspace+File.separator+name).exists()){
k++;
}
}
if (k==modelListName.length&& (new File(mainWorksapce+File.separator+configParamFileNameDefault).exists())&& (new File(mainWorksapce+File.separator+configParamFileName).exists())){
return;
}
for (String str:strs){
InputStream inputStream = manager.open(str);
byte[] bytes = new byte[1024];
int len = 0;
OutputStream outputStream = new FileOutputStream(modelWorkspace+File.separator+str);
while ((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes, 0, len);
}
}
//json
InputStream inputStream = manager.open(configParamFileNameDefault);
byte[] bytes = new byte[1024];
int len = 0;
OutputStream outputStream = new FileOutputStream(mainWorksapce+File.separator+configParamFileNameDefault);
while ((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes, 0, len);
}
inputStream.close();
outputStream.close();
inputStream = manager.open(configParamFileName);
bytes = new byte[1024];
len = 0;
outputStream = new FileOutputStream(mainWorksapce+File.separator+configParamFileName);
while ((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes, 0, len);
}
}
-
ParamActivity
-
DetectActivity
网友评论