import cv2
import mediapipe as mp

ESC = 27

# 初始化 MediaPipe Face Mesh 模組
mp_face_mesh = mp.solutions.face_mesh
mp_drawing = mp.solutions.drawing_utils

# 開啟網路攝影機
cap = cv2.VideoCapture(0)

# 使用 Face Mesh 模型
with mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5) as face_mesh:
    while cap.isOpened():
        ret, frame = cap.read()
        
        if not ret:
            break
        
        # 將影像轉為 RGB（OpenCV 默認為 BGR）
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        
        # 偵測臉部並獲取關鍵點
        results = face_mesh.process(rgb_frame)
        
        if results.multi_face_landmarks:
            for face_landmarks in results.multi_face_landmarks:
                # 繪製臉部網格（臉部的 468 個關鍵點）
                mp_drawing.draw_landmarks(image=frame, landmark_list=face_landmarks, connections=mp_face_mesh.FACEMESH_TESSELATION)
        
        # 顯示結果
        cv2.imshow('Face Mesh', frame)

        # 按 'q' 鍵退出
        if cv2.waitKey(1) == ESC:
            break

# 釋放資源
cap.release()
cv2.destroyAllWindows()