import cv2
import mediapipe as mp

ESC = 27

mp_drawing = mp.solutions.drawing_utils
mp_face_mesh = mp.solutions.face_mesh

drawing_spec = mp_drawing.DrawingSpec(thickness = 1, circle_radius = 1)

cap = cv2.VideoCapture(0)
ratio = cap.get(cv2.CAP_PROP_FRAME_WIDTH) / cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
WIDTH = 400
HEIGHT = int(WIDTH / ratio)

face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence = 0.5, min_tracking_confidence = 0.5)

while cap.isOpened():
    ret, frame = cap.read()
    frame = cv2.resize(frame, (WIDTH, HEIGHT))
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame.flags.writeable = False
    results = face_mesh.process(frame)
    frame.flags.writeable = True
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

    if results.multi_face_landmarks:
        for face_landmarks in results.multi_face_landmarks:
		# 若是 Windows，請將 mp_face_mesh.FACEMESH_CONTOURS --> mp_face_mesh.FACEMESH_CONTOURS
            mp_drawing.draw_landmarks(image = frame,
                              landmark_list = face_landmarks,
                              connections = mp_face_mesh.FACEMESH_TESSELATION,
                              landmark_drawing_spec = drawing_spec,
                              connection_drawing_spec = drawing_spec)

    cv2.imshow('MediaPipe FaceMesh', frame)

    if cv2.waitKey(1) == ESC:
        break

cap.release()
cv2.destroyAllWindows()