| 3 | import numpy as np |
| 4 | |
| 5 | class PullUpCounter: |
| 6 | def __init__(self): |
| 7 | self.mp_pose = mp.solutions.pose |
| 8 | self.pose = self.mp_pose.Pose( |
| 9 | min_detection_confidence=0.5, |
| 10 | min_tracking_confidence=0.5 |
| 11 | ) |
| 12 | |
| 13 | self.counter = 0 |
| 14 | self.stage = None |
| 15 | self.bar_y = None |
| 16 | |
| 17 | def get_bounding_box(self, landmarks, indices, frame_shape): |
| 18 | """Get bounding box for specific landmarks""" |
| 19 | h, w = frame_shape[:2] |
| 20 | points = [] |
| 21 | |
| 22 | for idx in indices: |
| 23 | lm = landmarks[idx] |
| 24 | x, y = int(lm.x * w), int(lm.y * h) |
| 25 | points.append([x, y]) |
| 26 | |
| 27 | points = np.array(points) |
| 28 | x, y, w_box, h_box = cv2.boundingRect(points) |
| 29 | |
| 30 | padding = 20 |
| 31 | x = max(0, x - padding) |
| 32 | y = max(0, y - padding) |
| 33 | w_box = w_box + 2 * padding |
| 34 | h_box = h_box + 2 * padding |
| 35 | |
| 36 | return x, y, w_box, h_box |
| 37 | |
| 38 | def process_frame(self, frame): |
| 39 | h, w = frame.shape[:2] |
| 40 | |
| 41 | image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| 42 | image.flags.writeable = False |
| 43 | |
| 44 | results = self.pose.process(image) |
| 45 | |
| 46 | image.flags.writeable = True |
| 47 | image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) |
| 48 | |
| 49 | try: |
| 50 | if results.pose_landmarks: |
| 51 | landmarks = results.pose_landmarks.landmark |
| 52 | |
| 53 | left_wrist = landmarks[self.mp_pose.PoseLandmark.LEFT_WRIST.value] |
| 54 | right_wrist = landmarks[self.mp_pose.PoseLandmark.RIGHT_WRIST.value] |
| 55 | nose = landmarks[self.mp_pose.PoseLandmark.NOSE.value] |
| 56 | |
| 57 | left_wrist_pos = (int(left_wrist.x * w), int(left_wrist.y * h)) |
| 58 | right_wrist_pos = (int(right_wrist.x * w), int(right_wrist.y * h)) |
| 59 | nose_pos = (int(nose.x * w), int(nose.y * h)) |
| 60 | |
| 61 | self.bar_y = (left_wrist_pos[1] + right_wrist_pos[1]) // 2 |
| 62 | |