亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

利用Android實現人臉識別并統計人臉數

發布時間:2020-10-26 16:02:54 來源:億速云 閱讀:243 作者:Leah 欄目:開發技術

利用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

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<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>

看完上述內容,你們掌握利用Android實現人臉識別并統計人臉數的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

星子县| 临沂市| 泽库县| 余庆县| 阜新市| 象山县| 唐河县| 乌审旗| 城步| 枣庄市| 鄂尔多斯市| 沈阳市| 南充市| 宿州市| 格尔木市| 汝州市| 五家渠市| 中山市| 且末县| 磴口县| 济南市| 兴业县| 石嘴山市| 锡林郭勒盟| 古田县| 辉县市| 清丰县| 阳东县| 九龙坡区| 花莲市| 苍溪县| 文山县| 灵台县| 井研县| 巫山县| 阿拉善右旗| 巴南区| 伊金霍洛旗| 泊头市| 宝清县| 贵南县|