메인
home
소프트웨어
home
🔓

5강. 미디어파이프 구동환경 확인

미디어파이프 샘플 코드

다음은 미디어파이프를 사용한 기본적인 손 인식 예제 코드입니다.

필요한 라이브러리 설치

pip install mediapipe opencv-python
Bash
복사

손 인식 샘플 코드

import cv2 import mediapipe as mp # MediaPipe 손 인식 초기화 mp_hands = mp.solutions.hands mp_drawing = mp.solutions.drawing_utils mp_drawing_styles = mp.solutions.drawing_styles # 웹캠 캡처 시작 cap = cv2.VideoCapture(0) # Hands 모델 설정 with mp_hands.Hands( model_complexity=0, min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands: while cap.isOpened(): success, image = cap.read() if not success: print("웹캠을 찾을 수 없습니다.") break # 이미지를 RGB로 변환 (MediaPipe는 RGB를 사용) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image.flags.writeable = False # 손 인식 수행 results = hands.process(image) # 이미지를 다시 BGR로 변환 (OpenCV는 BGR을 사용) image.flags.writeable = True 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, mp_drawing_styles.get_default_hand_landmarks_style(), mp_drawing_styles.get_default_hand_connections_style()) # 결과 화면에 표시 cv2.imshow('MediaPipe Hands', image) # 'q' 키를 누르면 종료 if cv2.waitKey(5) & 0xFF == ord('q'): break # 리소스 해제 cap.release() cv2.destroyAllWindows()
Python
복사

코드 설명

mp.solutions.hands: MediaPipe의 손 인식 솔루션을 불러옵니다.
mp_drawing: 감지된 랜드마크를 시각화하는 유틸리티입니다.
model_complexity: 모델의 복잡도 (0, 1)를 설정합니다. 0이 더 빠릅니다.
min_detection_confidence: 손 감지를 위한 최소 신뢰도 임계값입니다.
min_tracking_confidence: 손 추적을 위한 최소 신뢰도 임계값입니다.
results.multi_hand_landmarks: 감지된 손의 랜드마크 좌표를 포함합니다.

실행 방법

1.
위 코드를 mediapipe_hand_detection.py 파일로 저장합니다.
2.
터미널에서 다음 명령어로 실행합니다:
python mediapipe_hand_detection.py
Bash
복사
1.
웹캠 화면이 나타나고 손을 인식하여 랜드마크가 표시됩니다.
2.
'q' 키를 누르면 프로그램이 종료됩니다.