import cv2
from cvzone.HandTrackingModule import HandDetector

ESC = 27

# 初始化手勢檢測器
detector = HandDetector(maxHands=2)  # maxHands=2 用來偵測最多兩隻手

# 打開 webcam
cap = cv2.VideoCapture(0)

while True:
    success, img = cap.read()
    if not success:
        break

    # 偵測手部位置
    hands, img = detector.findHands(img)

    # 處理每隻手
    if hands:
        for hand in hands:
            # 取得手的主要信息，例如手掌的位置、關鍵點等
            x, y, w, h = hand['bbox']  # 取得手的邊界框
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)  # 畫出手的邊界框

            # 繪製手部關鍵點
            for point in hand['lmList']:  # lmList 包含了手的關鍵點
                cv2.circle(img, (point[0], point[1]), 5, (255, 0, 0), cv2.FILLED)

    # 顯示影像
    cv2.imshow('Hand Gesture Tracking', img)

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

cap.release()
cv2.destroyAllWindows()