JavaCV实现人脸检测功能

本文实例为大家分享了JavaCV实现人脸检测功能的具体代码,供大家参考,具体内容如下

/*
 * Copyright (C) 2010,2011,2012 Samuel Audet
 *
 * FacePreview - A fusion of OpenCV's facedetect and Android's CameraPreview samples,
 *        with JavaCV + JavaCPP as the glue in between.
 *
 * This file was based on CameraPreview.java that came with the Samples for
 * Android SDK API 8, revision 1 and contained the following copyright notice:
 *
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * IMPORTANT - Make sure the AndroidManifest.xml file looks like this:
 *
 * <?xml version="1.0" encoding="utf-8"?>
 * <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 *   package="com.googlecode.javacv.facepreview"
 *   android:versionCode="1"
 *   android:versionName="1.0" >
 *   <uses-sdk android:minSdkVersion="4" />
 *   <uses-permission android:name="android.permission.CAMERA" />
 *   <uses-feature android:name="android.hardware.camera" />
 *   <application android:label="@string/app_name">
 *     <activity
 *       android:name="FacePreview"
 *       android:label="@string/app_name"
 *       android:screenOrientation="landscape">
 *       <intent-filter>
 *         <action android:name="android.intent.action.MAIN" />
 *         <category android:name="android.intent.category.LAUNCHER" />
 *       </intent-filter>
 *     </activity>
 *   </application>
 * </manifest>
 */ 

package com.googlecode.javacv.facepreview; 

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import com.googlecode.javacpp.Loader;
import com.googlecode.javacv.cpp.opencv_objdetect; 

import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*; 

// ---------------------------------------------------------------------- 

public class FacePreview extends Activity {
  private FrameLayout layout;
  private FaceView faceView;
  private Preview mPreview; 

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // Hide the window title.
    requestWindowFeature(Window.FEATURE_NO_TITLE); 

    super.onCreate(savedInstanceState); 

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 

    // Create our Preview view and set it as the content of our activity.
    try {
      layout = new FrameLayout(this);
      faceView = new FaceView(this);
      mPreview = new Preview(this, faceView);
      layout.addView(mPreview);
      layout.addView(faceView);
      setContentView(layout);
    } catch (IOException e) {
      e.printStackTrace();
      new AlertDialog.Builder(this).setMessage(e.getMessage()).create().show();
    }
  }
} 

// ---------------------------------------------------------------------- 

class FaceView extends View implements Camera.PreviewCallback {
  public static final int SUBSAMPLING_FACTOR = 4; 

  private IplImage grayImage;
  private CvHaarClassifierCascade classifier;
  private CvMemStorage storage;
  private CvSeq faces; 

  public FaceView(FacePreview context) throws IOException {
    super(context); 

    // Load the classifier file from Java resources.
    File classifierFile = Loader.extractResource(getClass(),
      "/com/googlecode/javacv/facepreview/haarcascade_frontalface_alt2.xml",
      context.getCacheDir(), "classifier", ".xml");
    if (classifierFile == null || classifierFile.length() <= 0) {
      throw new IOException("Could not extract the classifier file from Java resource.");
    } 

    // Preload the opencv_objdetect module to work around a known bug.
    Loader.load(opencv_objdetect.class);
    classifier = new CvHaarClassifierCascade(cvLoad(classifierFile.getAbsolutePath()));
    classifierFile.delete();
    if (classifier.isNull()) {
      throw new IOException("Could not load the classifier file.");
    }
    storage = CvMemStorage.create();
  } 

  public void onPreviewFrame(final byte[] data, final Camera camera) {
    try {
      Camera.Size size = camera.getParameters().getPreviewSize();
      processImage(data, size.width, size.height);
      camera.addCallbackBuffer(data);
    } catch (RuntimeException e) {
      // The camera has probably just been released, ignore.
    }
  } 

  protected void processImage(byte[] data, int width, int height) {
    // First, downsample our image and convert it into a grayscale IplImage
    int f = SUBSAMPLING_FACTOR;
    if (grayImage == null || grayImage.width() != width/f || grayImage.height() != height/f) {
      grayImage = IplImage.create(width/f, height/f, IPL_DEPTH_8U, 1);
    }
    int imageWidth = grayImage.width();
    int imageHeight = grayImage.height();
    int dataStride = f*width;
    int imageStride = grayImage.widthStep();
    ByteBuffer imageBuffer = grayImage.getByteBuffer();
    for (int y = 0; y < imageHeight; y++) {
      int dataLine = y*dataStride;
      int imageLine = y*imageStride;
      for (int x = 0; x < imageWidth; x++) {
        imageBuffer.put(imageLine + x, data[dataLine + f*x]);
      }
    }
    IplImage grayImageT = IplImage.create(height/f, width/f, IPL_DEPTH_8U, 1);
    //cvSaveImage("/storage/emulated/0/Pictures/grayImage.jpg",grayImage);
    cvTranspose(grayImage,grayImageT);
    //cvSaveImage("/storage/emulated/0/Pictures/grayImageT.jpg",grayImageT);
    cvFlip(grayImageT,grayImageT,0);
    //cvSaveImage("/storage/emulated/0/Pictures/grayImageT_X.jpg",grayImageT);
    cvFlip(grayImageT,grayImageT,1);
    //cvSaveImage("/storage/emulated/0/Pictures/grayImageT_Y.jpg",grayImageT); 

    cvClearMemStorage(storage);
    faces = cvHaarDetectObjects(grayImageT, classifier, storage, 1.1, 3, CV_HAAR_DO_CANNY_PRUNING);
    postInvalidate();
  } 

  @Override
  protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setTextSize(20); 

    String s = "FacePreview - This side up.";
    float textWidth = paint.measureText(s);
    canvas.drawText(s, (getWidth()-textWidth)/2, 20, paint); 

    if (faces != null) {
      paint.setStrokeWidth(2);
      paint.setStyle(Paint.Style.STROKE);
      float scaleX = (float)getWidth()/grayImage.width();
      float scaleY = (float)getHeight()/grayImage.height();
      int total = faces.total();
      for (int i = 0; i < total; i++) {
        CvRect r = new CvRect(cvGetSeqElem(faces, i));
        int x = r.x(), y = r.y(), w = r.width(), h = r.height();
        canvas.drawRect(x*scaleX, y*scaleY, (x+w)*scaleX, (y+h)*scaleY, paint);
      }
    }
    else{
      canvas.drawText("meiyoujiancedao", (getWidth()-textWidth)/2, 20, paint);
    }
  }
} 

// ---------------------------------------------------------------------- 

class Preview extends SurfaceView implements SurfaceHolder.Callback {
  SurfaceHolder mHolder;
  Camera mCamera;
  Camera.PreviewCallback previewCallback; 

  Preview(Context context, Camera.PreviewCallback previewCallback) {
    super(context);
    this.previewCallback = previewCallback; 

    // Install a SurfaceHolder.Callback so we get notified when the
    // underlying surface is created and destroyed.
    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  } 

  public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, acquire the camera and tell it where
    // to draw.
    mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
    try {
      mCamera.setPreviewDisplay(holder);
    } catch (IOException exception) {
      mCamera.release();
      mCamera = null;
      // TODO: add more exception handling logic here
    }
  } 

  public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    // Because the CameraDevice object is not a shared resource, it's very
    // important to release it when the activity is paused.
    mCamera.stopPreview();
    mCamera.release();
    mCamera = null;
  } 

  private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.05;
    double targetRatio = (double) w / h;
    if (sizes == null) return null; 

    Size optimalSize = null;
    double minDiff = Double.MAX_VALUE; 

    int targetHeight = h; 

    // Try to find an size match aspect ratio and size
    for (Size size : sizes) {
      double ratio = (double) size.width / size.height;
      if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
      if (Math.abs(size.height - targetHeight) < minDiff) {
        optimalSize = size;
        minDiff = Math.abs(size.height - targetHeight);
      }
    } 

    // Cannot find the one match the aspect ratio, ignore the requirement
    if (optimalSize == null) {
      minDiff = Double.MAX_VALUE;
      for (Size size : sizes) {
        if (Math.abs(size.height - targetHeight) < minDiff) {
          optimalSize = size;
          minDiff = Math.abs(size.height - targetHeight);
        }
      }
    }
    return optimalSize;
  } 

  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Now that the size is known, set up the camera parameters and begin
    // the preview.
    Camera.Parameters parameters = mCamera.getParameters(); 

    List<Size> sizes = parameters.getSupportedPreviewSizes();
    Size optimalSize = getOptimalPreviewSize(sizes, w, h);
    parameters.setPreviewSize(optimalSize.width, optimalSize.height); 

    mCamera.setParameters(parameters);
    if (previewCallback != null) {
      mCamera.setPreviewCallbackWithBuffer(previewCallback);
      Camera.Size size = parameters.getPreviewSize();
      byte[] data = new byte[size.width*size.height*
          ImageFormat.getBitsPerPixel(parameters.getPreviewFormat())/8];
      mCamera.addCallbackBuffer(data);
    }
    mCamera.startPreview();
  } 

} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

您可能感兴趣的文章:

  • Java+opencv3.2.0实现人脸检测功能
  • opencv实现图片与视频中人脸检测功能
  • OpenCV实现人脸检测
  • 基于openCV实现人脸检测
  • OpenCV实现人脸识别
  • opencv 做人脸识别 opencv 人脸匹配分析
  • OPENCV+JAVA实现人脸识别
(0)

相关推荐

  • opencv实现图片与视频中人脸检测功能

    本文实例为大家分享了opencv实现人脸检测功能的具体代码,供大家参考,具体内容如下 第一章:反思与总结 上一篇博客我相信自己将人脸检测中的AdaBoost算法解释的非常清晰了,以及如何训练人脸检测的强分类器:人脸检测中AdaBoost算法详解.事后,自我感觉对这个人脸检测还是不够具体,所以自己抽了一下午的时间用opencv实现图片与视频中的人脸检测,下面是我用vs2013加opencv4.9来实现的.做一下声明,我的代码是参考OpenCV实现人脸检测的一个博客写的,非常感谢这位博主,我学到了很

  • opencv 做人脸识别 opencv 人脸匹配分析

    机器学习 机器学习的目的是把数据转换成信息. 机器学习通过从数据里提取规则或模式来把数据转成信息. 人脸识别 人脸识别通过级联分类器对特征的分级筛选来确定是否是人脸. 每个节点的正确识别率很高,但正确拒绝率很低. 任一节点判断没有人脸特征则结束运算,宣布不是人脸. 全部节点通过,则宣布是人脸. 工业上,常用人脸识别技术来识别物体. 对图片进行识别 复制代码 代码如下: #include "opencv2/core/core.hpp" #include "opencv2/obj

  • OpenCV实现人脸检测

    前段日子,写了个人脸检测的小程序,可以检测标记图片.视频.摄像头中的人脸.效果还行吧,用的是opencv提供人脸库.至于具体的人脸检测原理,找资料去啃吧. 环境:VS2013+OPENCV2.4.10+Win8.1 一.基于对话框的MFC 首先,新建一个基于对话框的MFC应用程序,命名为myFaceDetect(取消"安全开发周期(SDL)检查"勾选,我自己习惯取消这个). 放置Button,设置Button的ID和Caption. 图片按钮--ID:IDC_FACEDETECT 视频

  • 基于openCV实现人脸检测

    openCV的人脸识别主要通过Haar分类器实现,当然,这是在已有训练数据的基础上.openCV安装在 opencv/opencv/sources/data/haarcascades_cuda(或haarcascades)中存在预先训练好的物体检测器(xml格式),包括正脸.侧脸.眼睛.微笑.上半身.下半身.全身等. openCV的的Haar分类器是一个监督分类器,首先对图像进行直方图均衡化并归一化到同样大小,然后标记里面是否包含要监测的物体.它首先由Paul Viola和Michael Jon

  • Java+opencv3.2.0实现人脸检测功能

    说到人脸检测,首先要了解Haar特征分类器.Haar特征分类器说白了就是一个个的xml文件,不同的xml里面描述人体各个部位的特征值,比如人脸.眼睛等等.OpenCV3.2.0中提供了如下特征文件: haarcascade_eye.xml haarcascade_eye_tree_eyeglasses.xml haarcascade_frontalcatface.xml haarcascade_frontalcatface_extended.xml haarcascade_frontalface

  • OpenCV实现人脸识别

    主要有以下步骤: 1.人脸检测 2.人脸预处理 3.从收集的人脸训练机器学习算法 4.人脸识别 5.收尾工作 人脸检测算法: 基于Haar的脸部检测器的基本思想是,对于面部正面大部分区域而言,会有眼睛所在区域应该比前额和脸颊更暗,嘴巴应该比脸颊更暗等情形.它通常执行大约20个这样的比较来决定所检测的对象是否为人脸,实际上经常会做上千次. 基于LBP的人脸检测器基本思想与基于Haar的人脸检测器类似,但它比较的是像素亮度直方图,例如,边缘.角落和平坦区域的直方图. 这两种人脸检测器可通过训练大的图

  • OPENCV+JAVA实现人脸识别

    本文实例为大家分享了JAVA实现人脸识别的具体代码,供大家参考,具体内容如下 官方下载 安装文件 ,以win7为例,下载opencv-2.4.13.3-vc14.exe 安装后,在build目录下 D:\opencv\build\java,获取opencv-2413.jar,copy至项目目录 同时需要dll文件 与 各 识别xml文件,进行不同特征的识别(人脸,侧脸,眼睛等) dll目录:D:\opencv\build\java\x64\opencv_java2413.dll xml目录:D:

  • JavaCV实现人脸检测功能

    本文实例为大家分享了JavaCV实现人脸检测功能的具体代码,供大家参考,具体内容如下 /* * Copyright (C) 2010,2011,2012 Samuel Audet * * FacePreview - A fusion of OpenCV's facedetect and Android's CameraPreview samples, * with JavaCV + JavaCPP as the glue in between. * * This file was based o

  • 50行Python代码实现人脸检测功能

    现在的人脸识别技术已经得到了非常广泛的应用,支付领域.身份验证.美颜相机里都有它的应用.用iPhone的同学们应该对下面的功能比较熟悉 iPhone的照片中有一个"人物"的功能,能够将照片里的人脸识别出来并分类,背后的原理也是人脸识别技术. 这篇文章主要介绍怎样用Python实现人脸检测.人脸检测是人脸识别的基础.人脸检测的目的是识别出照片里的人脸并定位面部特征点,人脸识别是在人脸检测的基础上进一步告诉你这个人是谁. 好了,介绍就到这里.接下来,开始准备我们的环境. 准备工作 本文的人

  • Android 中使用 dlib+opencv 实现动态人脸检测功能

    1 概述 完成 Android 相机预览功能以后,在此基础上我使用 dlib 与 opencv 库做了一个关于人脸检测的 demo.该 demo 在相机预览过程中对人脸进行实时检测,并将检测到的人脸用矩形框描绘出来.具体实现原理如下: 采用双层 View,底层的 TextureView 用于预览,程序从 TextureView 中获取预览帧数据,然后调用 dlib 库对帧数据进行处理,最后将检测结果绘制在顶层的 SurfaceView 中. 2 项目配置 由于项目中用到了 dlib 与 open

  • Python下应用opencv 实现人脸检测功能

    使用OpenCV's Haar cascades作为人脸检测,因为他做好了库,我们只管使用. 代码简单,除去注释,总共有效代码只有10多行. 所谓库就是一个检测人脸的xml 文件,可以网上查找,下面是一个地址: https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml 如何构造这个库,学习完本文后可以参考: http://note.sonots.com/Sc

  • Android FaceDetector实现人脸检测功能

    关于人脸检测被折磨了半个月,前2周开需求会时需要要做一个"人脸认证上传功能,具体是打开前置摄像头,识别出用户的脸并且脸在一个指定的圆圈内然后自动保存这个状态的图像待用户是否确定上传".听到这个需求我第一时间想到比较专业的图形处理库OpenCV.去github上面搜了一下关于openCV识别人脸的demo,样例确实有点多,也确实是可以实现 但是OpenCV库实在是有点大8M,用这个库估计会被构架师说死.然后我还搜过其它的第三方库(虹软,face++,阿里云人脸检测)这几款都不是省油的灯一

  • Vue+tracking.js 实现前端人脸检测功能

    项目中需要实现人脸登陆功能,实现思路为在前端检测人脸,把人脸照片发送到后端识别,返回用户token登陆成功 前端调用摄像头使用tracking.js检测视频流中的人脸,检测到人脸后拍照上传后端. 后端使用face_recognition人脸识别库,使用Flask提供restfulAP供前端调用 实现效果如下图: 登陆界面: 摄像头检测人脸界面: 前端代码如下: <template> <div id="facelogin"> <h1 class="

  • 微信小程序实现人脸检测功能

    本文为大家分享了微信小程序实现人脸检测的具体代码,供大家参考,具体内容如下 因为本文章的人脸检测技术运用的是百度云人工智能,首先要有百度云的账号. 近期,人脸识别已经升级到了V3,开启了测试,所以也依照v3文档进行了更新: 1.人脸识别的每个接口,都需要用到百度云的access_token,首先获取 access-token ,一个月之后access_token过期:可以将获取的存入文件,再次引用时可以判断其是否过期,然后引用或者重新获取: //获取access_token function r

  • OpenCV实现人脸检测功能

    本文实例为大家分享了OpenCV实现人脸检测功能的具体代码,供大家参考,具体内容如下 1.HAAR级联检测 #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; #include <iostream> #include <cstdlib> using namespace std; int main(int artc, char** argv) { face_detect_h

随机推荐