스마트 인재개발원

(광주인공지능학원) 3차프로젝트 MediaPipe 복습하기

앨런튜링_ 2021. 8. 29. 22:57

The solution utilizes a two-step detector-tracker ML pipeline, proven to be effective in our MediaPipe Hands and MediaPipe Face Mesh solutions. Using a detector, the pipeline first locates the person/pose region-of-interest (ROI) within the frame. The tracker subsequently predicts the pose landmarks and segmentation mask within the ROI using the ROI-cropped frame as input. Note that for video use cases the detector is invoked only as needed, i.e., for the very first frame and when the tracker could no longer identify body pose presence in the previous frame. For other frames the pipeline simply derives the ROI from the previous frame’s pose landmarks.

The pipeline is implemented as a MediaPipe graph that uses a pose landmark subgraph from the pose landmark module and renders using a dedicated pose renderer subgraph. The pose landmark subgraph internally uses a pose detection subgraph from the pose detection module.

Note: To visualize a graph, copy the graph and paste it into MediaPipe Visualizer. For more information on how to visualize its associated subgraphs, please see visualizer documentation.

Pose Estimation Quality

To evaluate the quality of our models against other well-performing publicly available solutions, we use three different validation datasets, representing different verticals: Yoga, Dance and HIIT. Each image contains only a single person located 2-4 meters from the camera. To be consistent with other solutions, we perform evaluation only for 17 keypoints from COCO topology.

Person/pose Detection Model (BlazePose Detector)

The detector is inspired by our own lightweight BlazeFace model, used in MediaPipe Face Detection, as a proxy for a person detector. It explicitly predicts two additional virtual keypoints that firmly describe the human body center, rotation and scale as a circle. Inspired by Leonardo’s Vitruvian man, we predict the midpoint of a person’s hips, the radius of a circle circumscribing the whole person, and the incline angle of the line connecting the shoulder and hip midpoints.

 

토폴로지

현재 인체 포즈의 표준은 COCO 토폴로지로, 몸체, 팔, 다리 및 얼굴에 걸쳐 17 개의 경계부분(landmark)로 구성됩니다. 그러나 COCO 키포인트는 발목 및 손목 지점에만 국한되며 손과 발에 대한 스케일 및 방향 정보가 부족하므로 피트니스 및 댄스와 같은 실제 응용 프로그램에 필수적입니다. 더 많은 키포인트를 포함하는 것은 손, 얼굴 또는 발과 같은 도메인 별 포즈 추정 모델의 후속 적용에 중요합니다.

BlazePose를 통해 우리는 COCO, BlazeFace 및 BlazePalm 토폴로지의 상위 집합 인 33 개의 인체 키포인트의 새로운 토폴로지를 제시합니다. 이를 통해 얼굴 및 손 모델과 일치하는 포즈 예측만으로 신체 의미를 결정할 수 있습니다.

 

포즈 추정을 위해 검증된 2 단계 detector-tracker ML 파이프라인을 사용합니다. 이 파이프 라인은 감지기를 사용하여 먼저 프레임 내에서 포즈 관심 영역 (ROI)을 찾습니다. 추적기는 이후 이 ROI에서 33 개의 포즈 키포인트를 모두 예측합니다. 동영상 사용 사례의 경우 감지기는 첫 번째 프레임에서만 실행됩니다. 후속 프레임의 경우 아래에 설명된 대로 이전 프레임의 포즈 키포인트에서 ROI를 도출합니다.

BlazeFace를 확장하여 포즈 감지

포즈 감지 및 추적 모델로 구성된 전체 ML 파이프라인의 실시간 성능을 위해서는 각 구성 요소가 프레임 당 몇 밀리 초만 사용하여 매우 빨라야 합니다. 이를 달성하기 위해 우리는 몸통의 위치에 대한 신경망에 대한 가장 강력한 신호가 사람의 얼굴(고대비 기능과 비교적 작은 외형 차이로 인해)이라는 것을 관찰합니다. 따라서 우리는 1인 사용 사례에서 머리를 볼 수 있어야 한다는 강력한 가정(많은 모바일 및 웹 애플리케이션에 대해 유효함)을 만들어 빠르고 가벼운 포즈 디텍터를 획득합니다.

결과적으로 우리는 밀리 초 미만의 BlazeFace 모델에서 영감을 얻은 얼굴 감지기를 포즈 감지기의 프락시로 훈련했습니다. 이 모델은 프레임 내에서 사람의 위치만 감지하며 개인을 식별하는 데 사용할 수 없습니다. 예측된 키포인트에서 ROI를 도출하는 Face Mesh 및 MediaPipe Hand 추적 파이프라인과는 달리, 인간 포즈 추적의 경우 인체 중심, 회전 및 배율을 원으로 확실하게 설명하는 두 개의 추가 가상 키포인트를 명시적으로 예측합니다. 레오나르도의 비트루비안 남성에서 영감을 받아 사람의 엉덩이 중간점, 전체 사람을 둘러싸는 원의 반경, 어깨와 엉덩이 중간 점을 연결하는 선의 경사 각도를 예측합니다. 따라서 특정 요가 아사나와 같이 매우 복잡한 경우에도 일관된 추적이 가능합니다. 아래 그림은 접근 방식을 보여줍니다.

파이프라인의 포즈 추정 구성 요소는 각각 3 개의 자유도(x, y 위치 및 가시성)와 위에서 설명한 2 개의 가상 정렬 키포인트를 사용하여 33 개의 모든 키포인트의 위치를 예측합니다. 계산 집약적인 히트맵 예측을 사용하는 현재의 접근 방식과 달리, 우리 모델은 아래와 같이 모든 키포인트의 결합된 히트맵 / 오프셋 예측으로 감독되는 회귀 접근 방식을 사용합니다.

특히, 훈련 중에 먼저 히트 맵과 오프셋 손실을 사용하여 네트워크의 중앙 및 왼쪽 타워를 훈련합니다. 그런 다음 히트맵 출력을 제거하고 회귀 인코더 (오른쪽 타워)를 훈련하므로 히트 맵을 효과적으로 사용하여 경량 임베딩을 주도합니다.

POSE_LANDMARKS

A list of pose landmarks. Each landmark consists of the following:

  • x and y: Landmark coordinates normalized to [0.0, 1.0] by the image width and height respectively.
  • z: Represents the landmark depth with the depth at the midpoint of hips being the origin, and the smaller the value the closer the landmark is to the camera. The magnitude of z uses roughly the same scale as x.
  • visibility: A value in [0.0, 1.0] indicating the likelihood of the landmark being visible (present and not occluded) in the image.

POSE_WORLD_LANDMARKS

 

Another list of pose landmarks in world coordinates. Each landmark consists of the following:

  • x, y and z: Real-world 3D coordinates in meters with the origin at the center between hips.
  • visibility: Identical to that defined in the corresponding pose_landmarks.

SEGMENTATION_MASK

The output segmentation mask, predicted only when enable_segmentation is set to true. The mask has the same width and height as the input image, and contains values in [0.0, 1.0] where 1.0 and 0.0 indicate high certainty of a “human” and “background” pixel respectively. Please refer to the platform-specific usage examples below for usage details.

 

import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_pose = mp.solutions.pose

# For static images:
IMAGE_FILES = []
BG_COLOR = (192, 192, 192) # gray
with mp_pose.Pose(
    static_image_mode=True,
    model_complexity=2,
    enable_segmentation=True,
    min_detection_confidence=0.5) as pose:
  for idx, file in enumerate(IMAGE_FILES):
    image = cv2.imread(file)
    image_height, image_width, _ = image.shape
    # Convert the BGR image to RGB before processing.
    results = pose.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

    if not results.pose_landmarks:
      continue
    print(
        f'Nose coordinates: ('
        f'{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.NOSE].x * image_width}, '
        f'{results.pose_landmarks.landmark[mp_holistic.PoseLandmark.NOSE].y * image_height})'
    )

    annotated_image = image.copy()
    # Draw segmentation on the image.
    # To improve segmentation around boundaries, consider applying a joint
    # bilateral filter to "results.segmentation_mask" with "image".
    condition = np.stack((results.segmentation_mask,) * 3, axis=-1) > 0.1
    bg_image = np.zeros(image.shape, dtype=np.uint8)
    bg_image[:] = BG_COLOR
    annotated_image = np.where(condition, annotated_image, bg_image)
    # Draw pose landmarks on the image.
    mp_drawing.draw_landmarks(
        annotated_image,
        results.pose_landmarks,
        mp_pose.POSE_CONNECTIONS,
        landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style())
    cv2.imwrite('/tmp/annotated_image' + str(idx) + '.png', annotated_image)
    # Plot pose world landmarks.
    mp_drawing.plot_landmarks(
        results.pose_world_landmarks, mp_pose.POSE_CONNECTIONS)

# For webcam input:
cap = cv2.VideoCapture(0)
with mp_pose.Pose(
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as pose:
  while cap.isOpened():
    success, image = cap.read()
    if not success:
      print("Ignoring empty camera frame.")
      # If loading a video, use 'break' instead of 'continue'.
      continue

    # Flip the image horizontally for a later selfie-view display, and convert
    # the BGR image to RGB.
    image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
    # To improve performance, optionally mark the image as not writeable to
    # pass by reference.
    image.flags.writeable = False
    results = pose.process(image)

    # Draw the pose annotation on the image.
    image.flags.writeable = True
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    mp_drawing.draw_landmarks(
        image,
        results.pose_landmarks,
        mp_pose.POSE_CONNECTIONS,
        landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style())
    cv2.imshow('MediaPipe Pose', image)
    if cv2.waitKey(5) & 0xFF == 27:
      break
cap.release()

광주인공지능학원에서의 우리가 구현할 두번째 모션감지 기능이다.

광주인공지능학원에서 따로 수업 받지는 않았지만 기본적인 딥러닝의 토대를 배워서 학습모델을 쉽게 쓸 수 있는 것 같다.

내일은 마지막 등교일인데 아마 광주인공지능학원에서 최종 피드백과 리허설이 남았다. 

광주인공지능학원에 코로나로 오랜기간 휴관하면서 사실.. 프로젝트에 어려움도 있었지만 

후회없이 광주인공지능학원에서의 마지막 발표를 해보려한다.

광주인공지능학원에서의 다른팀은 얼마나 많은걸 준비하고 멋진 발표를할지 궁금하다 

"스마트인재개발원에서 진행된 수업내용입니다"

https://www.smhrd.or.kr/