opencv for Java图像处理深度学习目标跟踪&&目标检测Android专题

Android—基于opencv人脸检测app制作

2019-04-18  本文已影响2人  侠之大者_7d3f

前言


开发环境


功能介绍


App界面设计

  1. 主界面, 可以在Menu中设置参数


    主界面
  2. 设置人脸检测的参数

设置参数

Android App流程

App流程比较简单,在人脸检测过程中,算法计算在子线程中运行,避免UI线程卡死。

  1. 动态权限申请
  2. 设置人脸检测参数(可选,默认参数)
  3. 后台线程运行模型加载,初始化
  4. 从图库、相机选择图片
  5. 执行人脸检测,后台开启一个线程

App功能实现

人脸检测算法实现

人脸检测算法采用OpenCV Adaboost级联分类器:

在 opencv for android sdk中已经提供了训练好的模型,xml文件:


image.png
image.png
image.png

在Android端,需要导入opencv 模块:


image.png image.png

人脸检测用到的

image.png

opencv实现人脸检测非常简单,为了程序结果清晰化,新建一个JAVA类 FaceDetector, 包含3个方法:

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内的主要功能:

  1. 动态授权
    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();
            }
        }
    }

  1. 后台线程进行模型复制

因为CascadeClassifier分类器需要加载xml模型,在android工程中首先将xml模型复制到assets, 之后在SD卡创建目录,保存模型。

image.png

Java

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);
        }



    }


上一篇下一篇

猜你喜欢

热点阅读