欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

Android开发人脸识别统计人脸数

程序员文章站 2022-03-08 10:05:02
本文实例为大家分享了android开发人脸识别统计的具体代码,供大家参考,具体内容如下最近项目需求是统计当前摄像头中的人脸个数,安卓有提供现成的api,最终实现效果如上图。分析思路和步奏:主要使用到的...

本文实例为大家分享了android开发人脸识别统计的具体代码,供大家参考,具体内容如下

Android开发人脸识别统计人脸数

最近项目需求是统计当前摄像头中的人脸个数,安卓有提供现成的api,最终实现效果如上图。

分析思路和步奏:

主要使用到的类:surfaceview、cameramanager、cameradevice.statecallback、cameracapturesession.statecallback。

1.通过surfaceview展示预览区。
2.在surfaceview创建成功后通过cameramanager获取当前设备可用的摄像头。
3.检测摄像头权限。
4.通过cameramanager打开摄像头。
5.在打开成功的回调中通过cameradevice创建会话。
6.在会话创建成功的回调方法中创建预览请求。
7.在预览请求的回调方法oncapturecompleted()方法中获取预览界面中返回的人脸数。

以下是实现步骤:

1.xml

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical">

 <surfaceview
  android:id="@+id/sv"
  android:layout_width="match_parent"
  android:layout_height="0dp"
  android:layout_weight="1" />
</linearlayout>

java

cameramanager = (cameramanager) getsystemservice(context.camera_service);
  surfaceholder = sv.getholder();
  surface = surfaceholder.getsurface();
//获取可用的相机列表
     string[] cameraidlist = cameramanager.getcameraidlist();
if (checkselfpermission(manifest.permission.camera) != packagemanager.permission_granted) {
      // todo: consider calling
      // activity#requestpermissions
      // here to request the missing permissions, and then overriding
      // public void onrequestpermissionsresult(int requestcode, string[] permissions,
      //           int[] grantresults)
      // to handle the case where the user grants the permission. see the documentation
      // for activity#requestpermissions for more details.
      return;
     }
//获取开启相机的相关参数
     cameracharacteristics characteristics = cameramanager.getcameracharacteristics(cameraidlist[1]);
     //可用于判断是否支持人脸检测,以及支持到哪种程度
     facedetectmodes = characteristics.get(cameracharacteristics.statistics_info_available_face_detect_modes);//支持的人脸检测模式
     cameramanager.opencamera(cameraidlist[1], mstatecallback, null);
camera.createcapturesession(arrays.aslist(surface), new cameracapturesession.statecallback() {
     @override
     public void onconfigured(@nonnull cameracapturesession session) {
      
     }

     @override
     public void onconfigurefailed(@nonnull cameracapturesession session) {

     }
    }, new handler());
capturerequest.builder capturerequest = camera.createcapturerequest(cameradevice.template_preview);
       capturerequest.addtarget(surface);
       capturerequest.set(capturerequest.control_mode, camerametadata.control_mode_auto);
       capturerequest.set(capturerequest.statistics_face_detect_mode, getfacedetectmode());
       session.setrepeatingrequest(capturerequest.build(),capturecallback,new handler());
 /**
  * 预览回调
  */
 private cameracapturesession.capturecallback capturecallback = new cameracapturesession.capturecallback() {
  @override
  public void oncapturestarted(@nonnull cameracapturesession session, @nonnull capturerequest request, long timestamp, long framenumber) {
   super.oncapturestarted(session, request, timestamp, framenumber);
  }

  @override
  public void oncaptureprogressed(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull captureresult partialresult) {
   super.oncaptureprogressed(session, request, partialresult);
  }

  @override
  public void oncapturecompleted(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull totalcaptureresult result) {
   super.oncapturecompleted(session, request, result);
   face faces[] = result.get(captureresult.statistics_faces);
   if (faces.length != face) {
    log.e("lee", faces.length + "张脸");
   }
  }

  @override
  public void oncapturefailed(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull capturefailure failure) {
   super.oncapturefailed(session, request, failure);
  }

  @override
  public void oncapturesequencecompleted(@nonnull cameracapturesession session, int sequenceid, long framenumber) {
   super.oncapturesequencecompleted(session, sequenceid, framenumber);
  }

  @override
  public void oncapturesequenceaborted(@nonnull cameracapturesession session, int sequenceid) {
   super.oncapturesequenceaborted(session, sequenceid);
  }

  @override
  public void oncapturebufferlost(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull surface target, long framenumber) {
   super.oncapturebufferlost(session, request, target, framenumber);
  }
 };

以下就是所有代码:

mainactivity.java

package com.zg.lcddemo;

import android.manifest;
import android.content.contentvalues;
import android.content.context;
import android.content.pm.packagemanager;
import android.content.res.configuration;
import android.database.cursor;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.graphics.imageformat;
import android.graphics.rect;
import android.graphics.surfacetexture;
import android.hardware.camera;
import android.hardware.camera2.cameraaccessexception;
import android.hardware.camera2.cameracapturesession;
import android.hardware.camera2.cameracharacteristics;
import android.hardware.camera2.cameradevice;
import android.hardware.camera2.cameramanager;
import android.hardware.camera2.camerametadata;
import android.hardware.camera2.capturefailure;
import android.hardware.camera2.capturerequest;
import android.hardware.camera2.captureresult;
import android.hardware.camera2.totalcaptureresult;
import android.hardware.camera2.params.face;
import android.hardware.camera2.params.sessionconfiguration;
import android.hardware.camera2.params.streamconfigurationmap;
import android.media.facedetector;
import android.media.imagereader;
import android.net.uri;
import android.os.build;
import android.os.bundle;
import android.os.handler;
import android.os.handlerthread;
import android.os.message;
import android.provider.mediastore;
import android.util.log;
import android.util.size;
import android.view.surface;
import android.view.surfaceholder;
import android.view.surfaceview;
import android.view.view;
import android.widget.button;
import android.widget.imageview;
import android.widget.toast;

import androidx.annotation.nonnull;
import androidx.annotation.requiresapi;
import androidx.appcompat.app.appcompatactivity;

import java.io.bufferedinputstream;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.outputstream;
import java.util.arraylist;
import java.util.arrays;
import java.util.iterator;
import java.util.list;
import java.util.concurrent.semaphore;

public class mainactivity extends appcompatactivity {
 private surfaceview sv;
 private surfaceholder surfaceholder;
 private cameramanager cameramanager;
 private surface surface;
 int[] facedetectmodes;
 int face;
 list<bitmap> bitmaps = new arraylist<>();

 /**
  * 获取支持的最高人脸检测级别
  *
  * @return
  */
 private int getfacedetectmode() {
  if (facedetectmodes == null) {
   return capturerequest.statistics_face_detect_mode_full;
  } else {
   return facedetectmodes[facedetectmodes.length - 1];
  }
 }

 @requiresapi(api = build.version_codes.m)
 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  sv = findviewbyid(r.id.sv);
  cameramanager = (cameramanager) getsystemservice(context.camera_service);
  surfaceholder = sv.getholder();
  surface = surfaceholder.getsurface();
  surfaceholder.addcallback(new surfaceholder.callback() {
   @requiresapi(api = build.version_codes.m)
   @override
   public void surfacecreated(surfaceholder holder) {
    try {
     //获取可用的相机列表
     string[] cameraidlist = cameramanager.getcameraidlist();
     if (checkselfpermission(manifest.permission.camera) != packagemanager.permission_granted) {
      // todo: consider calling
      // activity#requestpermissions
      // here to request the missing permissions, and then overriding
      // public void onrequestpermissionsresult(int requestcode, string[] permissions,
      //           int[] grantresults)
      // to handle the case where the user grants the permission. see the documentation
      // for activity#requestpermissions for more details.
      return;
     }
     //获取开启相机的相关参数
     cameracharacteristics characteristics = cameramanager.getcameracharacteristics(cameraidlist[1]);
     //可用于判断是否支持人脸检测,以及支持到哪种程度
     facedetectmodes = characteristics.get(cameracharacteristics.statistics_info_available_face_detect_modes);//支持的人脸检测模式
     cameramanager.opencamera(cameraidlist[1], mstatecallback, null);
    } catch (cameraaccessexception e) {
     e.printstacktrace();
    }
   }

   @override
   public void surfacechanged(surfaceholder holder, int format, int width, int height) {

   }

   @override
   public void surfacedestroyed(surfaceholder holder) {

   }
  });

 }

 /**
  * 相机状态回调
  */
 private cameradevice.statecallback mstatecallback = new cameradevice.statecallback() {
  @override
  public void onopened(@nonnull final cameradevice camera) {
   //打开成功,可以获取cameradevice对象
   try {
    camera.createcapturesession(arrays.aslist(surface), new cameracapturesession.statecallback() {
     @override
     public void onconfigured(@nonnull cameracapturesession session) {
      try {
       capturerequest.builder capturerequest = camera.createcapturerequest(cameradevice.template_preview);
       capturerequest.addtarget(surface);
       capturerequest.set(capturerequest.control_mode, camerametadata.control_mode_auto);
       capturerequest.set(capturerequest.statistics_face_detect_mode, getfacedetectmode());
       session.setrepeatingrequest(capturerequest.build(),capturecallback,new handler());
      } catch (cameraaccessexception e) {
       e.printstacktrace();
      }
     }

     @override
     public void onconfigurefailed(@nonnull cameracapturesession session) {

     }
    }, new handler());
   } catch (cameraaccessexception e) {
    e.printstacktrace();
   }

  }

  @override
  public void ondisconnected(@nonnull cameradevice camera) {
   //断开连接
   toast.maketext(mainactivity.this, "ondisconnected", toast.length_short).show();
  }

  @override
  public void onerror(@nonnull cameradevice camera, final int error) {
   //发生异常
   toast.maketext(mainactivity.this, "onerror", toast.length_short).show();
  }
 };


 /**
  * 预览回调
  */
 private cameracapturesession.capturecallback capturecallback = new cameracapturesession.capturecallback() {
  @override
  public void oncapturestarted(@nonnull cameracapturesession session, @nonnull capturerequest request, long timestamp, long framenumber) {
   super.oncapturestarted(session, request, timestamp, framenumber);
  }

  @override
  public void oncaptureprogressed(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull captureresult partialresult) {
   super.oncaptureprogressed(session, request, partialresult);
  }

  @override
  public void oncapturecompleted(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull totalcaptureresult result) {
   super.oncapturecompleted(session, request, result);
   face faces[] = result.get(captureresult.statistics_faces);
   if (faces.length != face) {
    log.e("lee", faces.length + "张脸");
    face = faces.length;  
   }
  }

  @override
  public void oncapturefailed(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull capturefailure failure) {
   super.oncapturefailed(session, request, failure);
  }

  @override
  public void oncapturesequencecompleted(@nonnull cameracapturesession session, int sequenceid, long framenumber) {
   super.oncapturesequencecompleted(session, sequenceid, framenumber);
  }

  @override
  public void oncapturesequenceaborted(@nonnull cameracapturesession session, int sequenceid) {
   super.oncapturesequenceaborted(session, sequenceid);
  }

  @override
  public void oncapturebufferlost(@nonnull cameracapturesession session, @nonnull capturerequest request, @nonnull surface target, long framenumber) {
   super.oncapturebufferlost(session, request, target, framenumber);
  }
 };
}

xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical">

 <surfaceview
  android:id="@+id/sv"
  android:layout_width="match_parent"
  android:layout_height="0dp"
  android:layout_weight="1" />
</linearlayout>

以上就能实现统计当前摄像头下有多少个人脸。

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