import cv2
import os
import mediapipe as mp

class hand_pose:
    def __init__(self, min_dc=0.45, min_tc=0.45, max_nh=1):
        self.mp_drawing = mp.solutions.drawing_utils
        self.mp_hands = mp.solutions.hands
        self.hands = self.mp_hands.Hands(
            static_image_mode=False,
            max_num_hands=max_nh,
            min_detection_confidence=min_dc,
            min_tracking_confidence=min_tc
        )

    @staticmethod
    def img_show(img):
        cv2.imshow('MediaPipe Hands', img)
        cv2.waitKey(1)

    def draw(self, img):
        hand_local = []
        h_re = self.hands.process(img)
        if h_re.multi_hand_landmarks:
            for hand_landmarks in h_re.multi_hand_landmarks:
                self.mp_drawing.draw_landmarks(img,
                                               hand_landmarks,
                                               self.mp_hands.HAND_CONNECTIONS)
                self.img_show(img)

            '''获取手部关键点坐标'''
            for i in range(21):
                x = hand_landmarks.landmark[i].x * img.shape[1]
                y = hand_landmarks.landmark[i].y * img.shape[0]
                hand_local.append((x, y))
        return hand_local

if __name__ == "__main__":
    handpose = hand_pose()
    cap = cv2.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        handpose.draw(frame)