Python용 얼굴 인식 가이드

MediaPipe 얼굴 감지기 작업을 사용하면 이미지 또는 동영상에서 얼굴을 감지할 수 있습니다. 이때 이 작업을 사용하여 프레임 내에서 얼굴과 얼굴 특징을 찾을 수 있습니다. 이 작업에서는 단일 이미지 또는 연속된 연속된 이미지에서 작동하는 ML (머신러닝) 모델 이미지 스트림입니다. 이 작업은 다음과 함께 얼굴 위치를 출력합니다. 얼굴의 주요 포인트: 왼쪽 눈, 오른쪽 눈, 코끝, 입, 왼쪽 눈의 이주 및 있습니다.

이 지침에서 설명하는 코드 샘플은 GitHub 기능, 모델, 구성 옵션에 대한 자세한 내용은 개요를 참조하세요.

코드 예

얼굴 감지기의 코드 예는 참고하세요. 이 코드는 이 작업을 테스트하고 자체 얼굴 감지기를 만들기 시작했습니다. 데이터를 보고, 실행하고, 이 얼굴 인식기 예시 코드 할 수 있습니다.

Raspberry Pi용 얼굴 감지기를 구현하는 경우 다음을 참조하세요. Raspberry Pi 예시 앱을 엽니다.

설정

이 섹션에서는 개발 환경을 설정하는 주요 단계를 설명하고 코드 프로젝트를 살펴보겠습니다. 일반적인 정보 다음과 같은 MediaPipe 작업을 사용하기 위한 개발 환경 설정 자세한 내용은 Python 설정 가이드

<ph type="x-smartling-placeholder">

패키지

MediaPipe 얼굴 감지기 작업에는 mediapipe PyPI 패키지가 필요합니다. 다음을 사용하여 이러한 종속 항목을 설치하고 가져올 수 있습니다.

$ python -m pip install mediapipe

가져오기

다음 클래스를 가져와 얼굴 감지기 작업 함수에 액세스합니다.

import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision

모델

MediaPipe 얼굴 감지기 작업에는 다음과 호환되는 학습된 모델이 필요합니다. 태스크에 맞추는 것입니다. 얼굴 감지기에 사용할 수 있는 학습된 모델에 대한 자세한 내용은 다음을 참조하세요. 작업 개요의 모델 섹션을 확인합니다.

모델을 선택하고 다운로드한 후 로컬 디렉터리에 저장합니다.

model_path = '/absolute/path/to/face_detector.task'

BaseOptions 객체 model_asset_path 매개변수를 사용하여 경로를 지정합니다. 지정할 수도 있습니다 코드 예는 다음 섹션을 참고하세요.

할 일 만들기

MediaPipe 얼굴 감지기 작업은 create_from_options 함수를 사용하여 다음을 수행합니다. 작업을 설정하는 것입니다. create_from_options 함수는 값을 허용함 처리할 구성 옵션을 확인하세요. 구성에 관한 자세한 내용은 옵션은 구성 옵션을 참고하세요.

다음 코드는 이 작업을 빌드하고 구성하는 방법을 보여줍니다.

또한 이 샘플은 이미지에 대한 작업 구성의 변형도 보여줍니다. 동영상 파일, 라이브 스트림 등이 있죠

이미지

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the image mode:
options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.IMAGE)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

동영상

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the video mode:
options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

실시간 스트림

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
FaceDetectorResult = mp.tasks.vision.FaceDetectorResult
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the live stream mode:
def print_result(result: FaceDetectorResult, output_image: mp.Image, timestamp_ms: int):
    print('face detector result: {}'.format(result))

options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    result_callback=print_result)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

이미지와 함께 사용할 얼굴 감지기를 만드는 전체 예는 다음을 참조하세요. 코드 예를 참고하세요.

구성 옵션

이 작업에는 Python 애플리케이션을 위한 다음과 같은 구성 옵션이 있습니다.

옵션 이름 설명 값 범위 기본값
running_mode 작업의 실행 모드를 설정합니다. 세 가지 모드:

IMAGE: 단일 이미지 입력 모드입니다.

동영상: 동영상의 디코딩된 프레임 모드입니다.

LIVE_STREAM: 입력의 라이브 스트림 모드 데이터를 수집할 수 있습니다. 이 모드에서는 resultListener가 결과를 수신하도록 리스너를 설정하기 위해 호출 있습니다.
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
min_detection_confidence 성공으로 간주되기 위한 얼굴 인식의 최소 신뢰도 점수입니다. Float [0,1] 0.5
min_suppression_threshold 얼굴 인식이 겹치는 것으로 간주하기 위한 최소 비최대 억제 기준점입니다. Float [0,1] 0.3
result_callback 감지 결과를 수신하도록 결과 리스너를 설정합니다. 얼굴 감지기가 라이브 스트림에 있을 때 비동기식으로 있습니다. 달리기 모드가 LIVE_STREAM로 설정된 경우에만 사용할 수 있습니다. N/A Not set

데이터 준비

입력을 이미지 파일 또는 NumPy 배열로 준비합니다. 그런 다음 mediapipe.Image 객체로 변환합니다. 입력이 동영상 파일인 경우 웹캠으로 라이브 스트리밍하는 경우 입력 프레임을 Numpy로 로드하는 OpenCV 배열입니다.

이미지

import mediapipe as mp

# Load the input image from an image file.
mp_image = mp.Image.create_from_file('/path/to/image')

# Load the input image from a numpy array.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_image)
    

동영상

import mediapipe as mp

# Use OpenCV’s VideoCapture to load the input video.

# Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS
# You’ll need it to calculate the timestamp for each frame.

# Loop through each frame in the video using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

실시간 스트림

import mediapipe as mp

# Use OpenCV’s VideoCapture to start capturing from the webcam.

# Create a loop to read the latest frame from the camera using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

작업 실행

얼굴 인식기는 detect, detect_for_video, detect_async를 사용합니다. 함수를 사용하여 추론을 트리거합니다. 얼굴 인식에는 다음이 포함됩니다. 입력 데이터를 전처리하고 이미지에서 얼굴을 감지합니다.

다음 코드는 작업 모델로 처리를 실행하는 방법을 보여줍니다.

이미지

# Perform face detection on the provided single image.
# The face detector must be created with the image mode.
face_detector_result = detector.detect(mp_image)
    

동영상

# Perform face detection on the provided single image.
# The face detector must be created with the video mode.
face_detector_result = detector.detect_for_video(mp_image, frame_timestamp_ms)
    

실시간 스트림

# Send live image data to perform face detection.
# The results are accessible via the `result_callback` provided in
# the `FaceDetectorOptions` object.
# The face detector must be created with the live stream mode.
detector.detect_async(mp_image, frame_timestamp_ms)
    

다음에 유의하세요.

  • 동영상 모드 또는 라이브 스트림 모드에서 실행하는 경우 얼굴 감지기 작업에 입력 프레임의 타임스탬프를 제공합니다.
  • 이미지 또는 동영상 모델에서 실행하는 경우 얼굴 인식기 작업 입력 이미지 처리가 완료될 때까지 현재 스레드를 차단하거나 있습니다.
  • 라이브 스트림 모드에서 실행하면 얼굴 감지기 작업이 반환됩니다. 현재 스레드를 차단하지 않습니다. 그러면 감지 결과를 수신 대기하는 리스너가 입력 프레임에 연결됩니다. 얼굴 감지기 작업 시 감지 함수가 호출되는 경우 다른 프레임을 처리 중인 경우 작업은 새 입력 프레임을 무시합니다.

이미지에서 얼굴 감지기를 실행하는 전체 예는 다음을 참조하세요. 코드 예시 참조하세요.

결과 처리 및 표시

얼굴 감지기는 각 감지마다 FaceDetectorResult 객체를 반환합니다. 실행할 수 있습니다 결과 객체에는 인식된 얼굴에 대한 경계 상자와 인식된 각 얼굴의 신뢰도 점수입니다.

다음은 이 작업의 출력 데이터 예시를 보여줍니다.

FaceDetectionResult:
  Detections:
    Detection #0:
      BoundingBox:
        origin_x: 126
        origin_y: 100
        width: 463
        height: 463
      Categories:
        Category #0:
          index: 0
          score: 0.9729152917861938
      NormalizedKeypoints:
        NormalizedKeypoint #0:
          x: 0.18298381567001343
          y: 0.2961040139198303
        NormalizedKeypoint #1:
          x: 0.3302789330482483
          y: 0.29289937019348145
        ... (6 keypoints for each face)
    Detection #1:
      BoundingBox:
        origin_x: 616
        origin_y: 193
        width: 430
        height: 430
      Categories:
        Category #0:
          index: 0
          score: 0.9251380562782288
      NormalizedKeypoints:
        NormalizedKeypoint #0:
          x: 0.6151331663131714
          y: 0.3713381886482239
        NormalizedKeypoint #1:
          x: 0.7460576295852661
          y: 0.38825345039367676
        ... (6 keypoints for each face)

다음 이미지는 작업 출력을 시각화한 것입니다.

경계 상자가 없는 이미지의 경우 원본 이미지를 참고하세요.

얼굴 인식기 예시 코드는 자세히 알아보려면 코드 예를 참고하세요. 참조하세요.