|
| 1 | +import cv2 |
| 2 | +import mediapipe as mp |
| 3 | +import time |
| 4 | +import pyautogui |
| 5 | + |
| 6 | +mp_drawing = mp.solutions.drawing_utils |
| 7 | +mp_hands = mp.solutions.hands |
| 8 | + |
| 9 | +cap = cv2.VideoCapture(0) # Use the default camera |
| 10 | + |
| 11 | +# Set up the MediaPipe Hands model |
| 12 | +with mp_hands.Hands( |
| 13 | + static_image_mode=False, |
| 14 | + max_num_hands=1, |
| 15 | + min_detection_confidence=0.5) as hands: |
| 16 | + |
| 17 | + while cap.isOpened(): |
| 18 | + # Read a frame from the camera |
| 19 | + success, image = cap.read() |
| 20 | + if not success: |
| 21 | + break |
| 22 | + |
| 23 | + # Flip the image horizontally for a more natural feel |
| 24 | + image = cv2.flip(image, 1) |
| 25 | + |
| 26 | + # Convert the image to RGB and process it with MediaPipe Hands |
| 27 | + image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) |
| 28 | + results = hands.process(image_rgb) |
| 29 | + |
| 30 | + # Draw landmarks on the image |
| 31 | + if results.multi_hand_landmarks: |
| 32 | + for hand_landmarks in results.multi_hand_landmarks: |
| 33 | + mp_drawing.draw_landmarks( |
| 34 | + image, hand_landmarks, mp_hands.HAND_CONNECTIONS) |
| 35 | + |
| 36 | + # Check for swipe gesture |
| 37 | + thumb_tip = hand_landmarks.landmark[mp_hands.HandLandmark.THUMB_TIP] |
| 38 | + index_tip = hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP] |
| 39 | + if (index_tip.x - thumb_tip.x) > 0.05: |
| 40 | + print("Swipe Right") |
| 41 | + pyautogui.press("left") |
| 42 | + time.sleep(1) |
| 43 | + elif (index_tip.x - thumb_tip.x) < -0.1: |
| 44 | + print("Swipe Left") |
| 45 | + pyautogui.press("right") |
| 46 | + time.sleep(2) |
| 47 | + |
| 48 | + # Display the image |
| 49 | + cv2.imshow('MediaPipe Hands', image) |
| 50 | + |
| 51 | + # Check for exit key |
| 52 | + if cv2.waitKey(5) & 0xFF == 27: |
| 53 | + break |
| 54 | + |
| 55 | +cap.release() |
| 56 | +cv2.destroyAllWindows() |
0 commit comments