|
| 1 | +import cv2 |
| 2 | +import mediapipe as mp |
| 3 | +import numpy as np |
| 4 | +import math |
| 5 | + |
| 6 | +def calculate_angle(a, b, c): |
| 7 | + a = np.array([a.x, a.y]) # First point |
| 8 | + b = np.array([b.x, b.y]) # Middle point |
| 9 | + c = np.array([c.x, c.y]) # End point |
| 10 | + |
| 11 | + radians = np.arctan2(c[1]-b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0]) |
| 12 | + angle = np.abs(radians*180.0/np.pi) |
| 13 | + |
| 14 | + if angle > 180.0: |
| 15 | + angle = 360 - angle |
| 16 | + |
| 17 | + return angle |
| 18 | + |
| 19 | +# Initialize variables |
| 20 | +counter = 0 |
| 21 | +stage = None |
| 22 | + |
| 23 | +cap = cv2.VideoCapture(0) |
| 24 | +mp_pose = mp.solutions.pose |
| 25 | +pose = mp_pose.Pose() |
| 26 | +mp_drawing = mp.solutions.drawing_utils |
| 27 | + |
| 28 | +while cap.isOpened(): |
| 29 | + ret, frame = cap.read() |
| 30 | + if not ret: |
| 31 | + break |
| 32 | + |
| 33 | + # Recolor image to RGB |
| 34 | + image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| 35 | + image.flags.writeable = False |
| 36 | + |
| 37 | + # Make detection |
| 38 | + results = pose.process(image) |
| 39 | + |
| 40 | + # Recolor back to BGR |
| 41 | + image.flags.writeable = True |
| 42 | + image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) |
| 43 | + |
| 44 | + # Extract landmarks |
| 45 | + try: |
| 46 | + landmarks = results.pose_landmarks.landmark |
| 47 | + |
| 48 | + # Get coordinates |
| 49 | + left_hip = landmarks[mp_pose.PoseLandmark.LEFT_HIP] |
| 50 | + left_knee = landmarks[mp_pose.PoseLandmark.LEFT_KNEE] |
| 51 | + left_ankle = landmarks[mp_pose.PoseLandmark.LEFT_ANKLE] |
| 52 | + |
| 53 | + # Calculate angle |
| 54 | + angle = calculate_angle(left_hip, left_knee, left_ankle) |
| 55 | + |
| 56 | + # Visualize angle |
| 57 | + cv2.putText(image, str(int(angle)), |
| 58 | + (int(left_knee.x * image.shape[1]), int(left_knee.y * image.shape[0])), |
| 59 | + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) |
| 60 | + |
| 61 | + # Squat logic |
| 62 | + if angle > 160: |
| 63 | + stage = 'up' |
| 64 | + if angle < 90 and stage == 'up': |
| 65 | + stage = 'down' |
| 66 | + counter += 1 |
| 67 | + print(f"Squat count: {counter}") |
| 68 | + |
| 69 | + except Exception as e: |
| 70 | + pass |
| 71 | + |
| 72 | + # Render squat count |
| 73 | + cv2.rectangle(image, (0, 0), (225, 73), (245, 117, 16), -1) |
| 74 | + cv2.putText(image, 'REPS', (15, 12), |
| 75 | + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) |
| 76 | + cv2.putText(image, str(counter), |
| 77 | + (10, 60), |
| 78 | + cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) |
| 79 | + |
| 80 | + # Display image |
| 81 | + cv2.imshow('Knee Exercise', image) |
| 82 | + |
| 83 | + if cv2.waitKey(10) & 0xFF == ord('q'): |
| 84 | + break |
| 85 | + |
| 86 | +cap.release() |
| 87 | +cv2.destroyAllWindows() |
0 commit comments