This section shows the actual Python code for face detection and hand tracking using MediaPipe and OpenCV. You can run it to see live results from your webcam.
A. Basic Face Detection
import cv2
import mediapipe as mp
Initialize MediaPipe Face Detection
mp_face_detection = mp.solutions.face_detection
mp_drawing = mp.solutions.drawing_utils
Open webcam
cap = cv2.VideoCapture(0)
with mp_face_detection.FaceDetection(min_detection_confidence=0.5) as face_detection:
while cap.isOpened():
success, image = cap.read()
if not success:
continue
Convert BGR to RGB & process
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = face_detection.process(image_rgb)
Draw face detections
if results.detections:
for detection in results.detections:
mp_drawing.draw_detection(image, detection)
cv2.imshow('Face Detection', image)
if cv2.waitKey(5) & 0xFF == 27: # Press ESC to exit
break
cap.release()
cv2.destroyAllWindows()
B. Hand Tracking (Gesture Recognition)
import cv2
import mediapipe as mp
mp_hands = mp.solutions.hands
hands = mp_hands.Hands()
cap = cv2.VideoCapture(0)
while cap.isOpened():
success, image = cap.read()
if not success:
continue
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = hands.process(image_rgb)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp.solutions.drawing_utils.draw_landmarks(
image, hand_landmarks, mp_hands.HAND_CONNECTIONS)
cv2.imshow('Hand Tracking', image)
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()