박민혀기

Mediapipe Example Code(Hand Tracking) 본문

Deep Learning

Mediapipe Example Code(Hand Tracking)

박민혀기 2023. 6. 1. 01:45
import cv2
import mediapipe as mp

# Mediapipe의 Hand Tracking 모듈을 초기화합니다.
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands

# Webcam 캡처를 위한 VideoCapture 객체를 생성합니다.
cap = cv2.VideoCapture(0)

# Hand Tracking을 위한 객체를 생성합니다.
with mp_hands.Hands(static_image_mode=False,
                    max_num_hands=2,
                    min_detection_confidence=0.5,
                    min_tracking_confidence=0.5) as hands:
    
    while cap.isOpened():
        # 프레임을 읽어옵니다.
        ret, frame = cap.read()
        
        # RGB로 변환하여 손 인식을 수행합니다.
        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        results = hands.process(image)
        
        # 결과를 화면에 표시합니다.
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                mp_drawing.draw_landmarks(image, hand_landmarks, mp_hands.HAND_CONNECTIONS)
        
        cv2.imshow('Hand Tracking', image)
        
        # 'q'를 누르면 종료합니다.
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

cap.release()
cv2.destroyAllWindows()