OpenCV使用(三):实现人脸检测

目录

8850933-715f2239bc0e06dd.png

效果展示

8850933-d1a6b88f11efeaaf.gif

OpenCV的人脸检测函数

OpenCV中的人脸检测是基于训练好的LBP与HAAR特征级联检测器完成的,它们就在sdk\etc目录下的haarcascades文件夹与lbpcascades文件夹里,我们要想实现人脸检测只需要加载这些xml数据并利用这些数据创建OpenCV中级联检测相关的API对象CascadeClassifier然后再调用它的人脸检测方法detectMultiScale即可,该方法的具体参数如下:
detectMultiScale(Mat image, MatOfRect objects, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize)

  • image:输入图像(即要检测的图像)
  • objects:用来存储检测结果,每个结果都为矩形
  • scaleFactor:尺度变换比率,基本在1.05~1.2之间比较好
  • minNeighbors:领域范围内符合条件的对象个数,它是输出检测目标的重要阈值,大小要适中
  • flags:OpenCV2.X使用的参数这里不需要,设置为0即可
  • minSize:对象检测的最小范围
  • maxSize:对象检测的最大范围

实现步骤

  1. 拷贝训练数据
    在res目录下新建raw目录,将lbpcascades文件夹下的lbpcascade_frontalface.xml拷贝进去


    8850933-39300bd10177e415.png
  2. 创建级联检测器对象
/**
     * 加载级联检测器对象
     * @throws IOException
     */
    private void initFaceDectector () throws IOException {
        InputStream inputStream = getResources().openRawResource(R.raw.lbpcascade_frontalface);
        File cascadeDir = getDir("cascase", Context.MODE_PRIVATE);
        File file = new File(cascadeDir.getAbsoluteFile(), "lbpcascade_frontalface.xml");
        FileOutputStream output = new FileOutputStream(file);
        byte[] buff = new byte[1024];
        int len;
        while ((len = inputStream.read(buff))!=-1){
            output.write(buff,0,len);
        }
        inputStream.close();
        output.close();
        cascadeClassifier = new CascadeClassifier(file.getAbsolutePath());
        file.delete();
        cascadeDir.delete();
    }
  1. 调用detectMultiScale方法
/**
     * 人脸检测
     */
    private void detectionFace() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.jiti);//获取要检测图像的Bitmap
        Mat matSrc = new Mat();
        Utils.bitmapToMat(bitmap,matSrc);//将Bitmp转换为Mat对象
        Mat matGray = new Mat();
        Imgproc.cvtColor(matSrc,matGray,Imgproc.COLOR_BGRA2GRAY);//将图像转换为灰度图像

        MatOfRect faces = new MatOfRect();//创建存放检测结果的对象

        cascadeClassifier.detectMultiScale(matGray,faces,1.1,3,0,new Size(50,50),new Size());//进行人脸检测

        List<Rect> rects = faces.toList();
        if(rects.size()>0){
            for (Rect rect:rects){
                Imgproc.rectangle(matSrc,rect.tl(),rect.br(),new Scalar(0,0,255),2,8,0);//将检测结果绘制为矩形
            }
        }
        Utils.matToBitmap(matSrc,bitmap);//将Mat转换为Bitmap
//        释放资源
        matGray.release();
        matSrc.release();
    }

猜你喜欢

转载自blog.csdn.net/weixin_33831196/article/details/90984199