| 환경 | 비고 |
|---|---|
| macOS + Git Shell | 로컬에서 직접 git 명령 사용 |
| Windows + WSL (Ubuntu) | Linux 기반 명령어와 패키지 관리가 가능 |
Conda 가상환경 (media) | conda create -n media python=3.10 후 conda activate media |
Tip : 가상환경에 문제가 생기면
~/miniconda3/envs/media폴더를 삭제하고 다시 만들면 된다.
pip install mediapipe==0.10.9 # 최신 안정 버전 권장
pip show mediapipe # 패키지 위치, 버전, 의존성 확인
pip show 의 출력에 Location: ~/miniconda3/envs/media/lib/python3.10/site-packages 와 같이 가상환경 경로가 표시된다.
site-packages/
└─ mediapipe/
├─ __init__.py
├─ python/
│ └─ solutions/
│ ├─ __init__.py
│ ├─ face_detection/
│ │ ├─ __init__.py
│ │ └─ face_detection.py
│ ├─ hands/
│ ├─ pose/
│ └─ face_mesh/
└─ solutions/
└─ drawing_utils.py
mp.solutions.face_detection 로 접근하면 face_detection 모듈이 로드된다. import mediapipe as mp 후 F12(Go to definition) 를 누르면 해당 소스 파일을 바로 열어볼 수 있다. (cv2 모듈은 WSL 환경에서는 원격 파일을 탐색하기 어려워 별도 설정이 필요함) mp_face_detection = mp.solutions.face_detection
face_detector = mp_face_detection.FaceDetection(
model_selection=0, # 0: Short‑Range(≤2 m), 1: Full‑Range(≤5 m)
min_detection_confidence=0.5) # 0~1 사이, 기본값 0.5
| 파라미터 | 의미 | 권장값 |
|---|---|---|
model_selection | Short‑Range(0) – 근거리(≈2 m) 전용 / Full‑Range(1) – 원거리(≈5 m) 전용 | 상황에 따라 선택 |
min_detection_confidence | 검출 신뢰도 임계값 | 0.5 ~ 0.7 (거짓 양성 억제) |
Webcam은 일반적으로 좌우가 뒤집힌(미러) 영상을 제공한다.
MediaPipe는 실제 카메라 센서 좌표를 그대로 반환하므로, 좌우가 반대로 보인다.
# 좌우 반전 보정 (필요 시)
frame = cv2.flip(frame, 1) # 1: 좌우 반전
results.detections 은 mediapipe.framework.formats.detection_pb2.Detection 객체 리스트이다.
각 Detection 은 다음 정보를 포함한다.
| 필드 | 설명 |
|---|---|
location_data.relative_bounding_box | (x_min, y_min, width, height) 가 모두 0‒1 로 정규화된 값 |
location_data.relative_keypoints | 6개 Landmark (순서: RIGHT_EYE, LEFT_EYE, NOSE_TIP, MOUTH_CENTER, RIGHT_EAR_TRAGION, LEFT_EAR_TRAGION) |
score | 검출 신뢰도 (0‒1) |
h, w, _ = frame.shape
bbox = detection.location_data.relative_bounding_box
xmin = int(bbox.xmin * w)
ymin = int(bbox.ymin * h)
width = int(bbox.width * w)
height = int(bbox.height * h)
# Landmark 변환 (예: 오른쪽 눈)
kp = detection.location_data.relative_keypoints[0] # 0: RIGHT_EYE
x_eye = int(kp.x * w)
y_eye = int(kp.y * h)
MediaPipe 자체 drawing_utils 를 이용하면 Bounding Box와 6개의 Landmark 를 한 번에 그릴 수 있다.
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_drawing.draw_detection(frame, detection) # 자동 그리기
주의 :
draw_detection은 BGR 이미지에서도 바로 사용 가능하지만, 키포인트 색상·크기 를 직접 커스터마이징하려면drawing_utils.draw_landmarks를 활용한다.
import cv2
import mediapipe as mp
mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils
def run_face_detection():
cap = cv2.VideoCapture(0) # 기본 webcam
with mp_face_detection.FaceDetection(
model_selection=0,
min_detection_confidence=0.5) as detector:
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# OpenCV는 BGR → MediaPipe는 RGB
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = detector.process(rgb)
if results.detections:
for det in results.detections:
# 자동 그리기
mp_drawing.draw_detection(frame, det)
# 필요 시 직접 좌표 출력
bbox = det.location_data.relative_bounding_box
h, w, _ = frame.shape
print(f"BBox (pixel): "
f"{int(bbox.xmin*w):04d}, {int(bbox.ymin*h):04d}, "
f"{int(bbox.width*w):04d}, {int(bbox.height*h):04d}")
cv2.imshow('MediaPipe Face Detection', frame)
if cv2.waitKey(5) & 0xFF == 27: # ESC 키 종료
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
run_face_detection()
핵심 포인트
1. cv2.cvtColor(..., cv2.COLOR_BGR2RGB) 로 색상 순서를 맞춘다.
2. detector.process() 은 RGB 이미지만 받는다.
3. mp_drawing.draw_detection 은 정규화 좌표 를 자동으로 픽셀 좌표로 변환 후 그린다.
| 솔루션 | 주요 기능 | 주요 파라미터 |
|---|---|---|
mp.solutions.hands | 21개의 손 관절 좌표, 제스처 인식 | model_complexity (0‒2), min_detection_confidence |
mp.solutions.pose | 33개의 전신 관절 좌표 | model_complexity, smooth_landmarks |
mp.solutions.face_mesh | 468개의 얼굴 정밀 메쉬, Iris(홍채) 포함 | refine_landmarks=True 시 5개의 Iris 포인트 제공 |
mp.solutions.objectron | 3D 객체(컵·병·볼 등) 추적 | max_num_objects, min_detection_confidence |
각 솔루션은 mp_drawing.draw_landmarks 로 시각화가 가능하며, Python, JavaScript, Android (Kotlin/Java) 등 다양한 플랫폼을 지원한다.
Q. “MediaPipe에서 모델 선택(
model_selection) 값이 의미하는 것이 무엇인가요?”
A.model_selection=0은 Short‑Range 모델로, 약 2 m 이내의 가까운 얼굴을 최적화한다.model_selection=1은 Full‑Range 모델로, 5 m 정도까지 떨어진 얼굴까지 인식한다. 두 모델은 내부적으로 서로 다른 가중치를 사용하므로 상황에 맞게 선택한다.
Q. “Webcam 영상을 반전 없이 사용하려면 어떻게 해야 하나요?”
A.cv2.flip(frame, 1)로 좌우를 뒤집어주면 MediaPipe 결과와 화면이 일치한다. 반전이 필요 없을 경우,flip호출을 생략하고 결과 좌표에w - x로 보정한다.
Q. “
mp_drawing.draw_detection은 어떤 정보를 그려 주나요?”
A. 정규화된 Bounding Box와 6개의 Landmark(두 눈·코·입·양쪽 귀 트라거스)를 자동으로 픽셀 좌표 변환 후 화면에 표시한다.
(강의 중 별도의 질문이 제공되지 않아 위와 같이 예상 질문을 정리했습니다.)
conda)에서 pip install mediapipe 로 설치한다. mp.solutions.face_detection.FaceDetection 에서 model_selection(0·1) 과 min_detection_confidence 를 설정한다. Detection 객체는 정규화된 Bounding Box와 6개 Landmark 를 제공한다. x * width, y * height 로 변환해 픽셀 좌표를 얻는다. mp_drawing.draw_detection 로 자동 시각화가 가능하고, 직접 그리려면 drawing_utils.draw_landmarks 를 사용한다. cv2.flip 으로 보정하거나 좌표를 반전한다. min_detection_confidence 를 높이면 거짓 양성를 줄일 수 있다(0.6~0.7 권장). | 분야 | 학습 내용 | 참고 자료 |
|---|---|---|
| OpenCV Haar Cascade | CascadeClassifier 로 전통적인 객체 탐지 (얼굴·고양이·차량) | https://github.com/KrishArul26/Cars_Counting |
| MediaPipe 공식 문서 | 모든 솔루션 API, 파라미터 상세 설명 | https://developers.google.com/mediapipe/solutions |
| MediaPipe Python 코드 | mediapipe/python/solutions/*.py 직접 읽기 | pip show mediapipe 로 위치 확인 후 열기 |
| Hands·Pose 실습 | 손 제스처 인식, 전신 포즈 추정 예제 | https://github.com/google/mediapipe/tree/main/examples/python/hand_tracking |
| Face‑Mesh & Iris | 고정밀 얼굴 메쉬와 홍채 추출 | https://github.com/google/mediapipe/tree/main/mediapipe/python/solutions/face_mesh |
| Web 기반 MediaPipe | JavaScript (MediaPipe JS) 로 웹 페이지에 적용 | https://github.com/google/mediapipe/tree/master/mediapipe/javascript |
| 실무 프로젝트 | 데이터 파이프라인 → MediaPipe 인식 → OpenCV 후처리 → 모델 학습 (예: drowsy‑driver detection) | http://www.nefus.kr/2021_Demonstration/Drowsy_Driver/index.html |
실무 팁: 프로젝트 초기 단계에서 가상환경·Git 로 코드 버전을 관리하고,
git pull --rebase로 협업 시 충돌을 최소화한다. MediaPipe 결과물을 파일(예: JSON) 로 저장해두면 후처리·학습용 데이터 로 재활용하기 쉽다.