-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
281 lines (235 loc) · 13.6 KB
/
Copy pathmain.py
File metadata and controls
281 lines (235 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import cv2
import mediapipe as mp
import numpy as np
import time
import threading
import pyttsx3
from exercise_tracker import ExerciseTracker, ExerciseType
from pose_utils import calculate_angle, get_landmark_coordinates, draw_progress_bar, draw_circular_gauge
# Initialize MediaPipe
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
# Initialize text-to-speech engine
tts_engine = pyttsx3.init()
tts_engine.setProperty('rate', 150) # Speed of speech
def speak_text(text):
"""Speak text using TTS in a separate thread to avoid blocking"""
def speak():
tts_engine.say(text)
tts_engine.runAndWait()
# Run in a separate thread to avoid blocking the main loop
thread = threading.Thread(target=speak)
thread.daemon = True
thread.start()
def speak_tutorial(tracker):
"""Speak the tutorial for the current exercise"""
tutorial_text = tracker.get_tutorial_text()
speak_text(tutorial_text)
#
def display_workout_info(image, tracker, w, h, landmarks=None):
"""Display all workout metrics and information on the image"""
# Scale UI elements based on screen size
scale_factor = max(1, w / 1280) # Scale based on width relative to 1280px
# Get current exercise data
current_data = tracker.get_current_data()
# Main status box - increased width to accommodate two-digit numbers
box_width = int(450 * scale_factor) # Increased from 400 to 450
box_height = int(240 * scale_factor)
cv2.rectangle(image, (0, 0), (box_width, box_height), (245, 117, 16), -1)
# Exercise type
exercise_name = tracker.exercise_type.name.replace('_', ' ').title()
cv2.putText(image, f'EXERCISE: {exercise_name}', (int(10 * scale_factor), int(20 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5 * scale_factor, (0, 0, 0), int(1 * scale_factor), cv2.LINE_AA)
# Rep data - adjusted positioning for better spacing
cv2.putText(image, 'REPS', (int(15 * scale_factor), int(50 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5 * scale_factor, (0, 0, 0), int(1 * scale_factor), cv2.LINE_AA)
if tracker.exercise_type == ExerciseType.BICEP_CURL:
# Format rep counters with fixed width to prevent overlap
left_rep_text = f"L:{current_data['left_counter']:2d}"
right_rep_text = f"R:{current_data['right_counter']:2d}"
# Display left rep counter
cv2.putText(image, left_rep_text,
(int(10 * scale_factor), int(80 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 1.2 * scale_factor, (255, 255, 255), int(2 * scale_factor), cv2.LINE_AA)
# Display right rep counter with proper spacing
cv2.putText(image, right_rep_text,
(int(80 * scale_factor), int(80 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 1.2 * scale_factor, (255, 255, 255), int(2 * scale_factor), cv2.LINE_AA)
else:
cv2.putText(image, str(current_data["total_reps"]),
(int(10 * scale_factor), int(80 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 1.5 * scale_factor, (255, 255, 255), int(2 * scale_factor), cv2.LINE_AA)
# Set data - moved further to the right
cv2.putText(image, 'SET', (int(160 * scale_factor), int(50 * scale_factor)), # Moved from 100 to 160
cv2.FONT_HERSHEY_SIMPLEX, 0.5 * scale_factor, (0, 0, 0), int(1 * scale_factor), cv2.LINE_AA)
cv2.putText(image, str(current_data["set_counter"]),
(int(160 * scale_factor), int(80 * scale_factor)), # Moved from 100 to 160
cv2.FONT_HERSHEY_SIMPLEX, 1.5 * scale_factor, (255, 255, 255), int(2 * scale_factor), cv2.LINE_AA)
# Stage data - moved further to the right
stage_text = ""
if tracker.exercise_type == ExerciseType.BICEP_CURL:
# Use screen-based left/right determination
screen_left, screen_right = tracker.determine_left_right(landmarks, (h, w))
left_stage = current_data['stage'][screen_left] or 'N/A'
right_stage = current_data['stage'][screen_right] or 'N/A'
stage_text = f"L:{left_stage:<4} R:{right_stage:<4}" # Fixed width formatting
else:
stage_text = current_data["stage"] or "N/A"
cv2.putText(image, 'STAGE', (int(220 * scale_factor), int(50 * scale_factor)), # Moved from 185 to 220
cv2.FONT_HERSHEY_SIMPLEX, 0.5 * scale_factor, (0, 0, 0), int(1 * scale_factor), cv2.LINE_AA)
cv2.putText(image, stage_text,
(int(220 * scale_factor), int(80 * scale_factor)), # Moved from 185 to 220
cv2.FONT_HERSHEY_SIMPLEX, 0.6 * scale_factor, (255, 255, 255), int(1 * scale_factor), cv2.LINE_AA) # Reduced font size
# Workout timer
workout_time = time.time() - tracker.start_time
minutes = int(workout_time // 60)
seconds = int(workout_time % 60)
cv2.putText(image, f'TIME: {minutes:02d}:{seconds:02d}', (int(10 * scale_factor), int(110 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5 * scale_factor, (0, 0, 0), int(1 * scale_factor), cv2.LINE_AA)
# Rest timer (if resting)
rest_remaining = tracker.get_rest_time_remaining()
if rest_remaining > 0:
cv2.putText(image, f'REST: {int(rest_remaining)}s', (int(10 * scale_factor), int(140 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6 * scale_factor, (0, 0, 255), int(2 * scale_factor), cv2.LINE_AA)
# Feedback with color coding - moved down to avoid overlap
if tracker.feedback:
# Split long feedback into multiple lines
words = tracker.feedback.split()
lines = []
current_line = ""
for word in words:
if len(current_line) + len(word) + 1 <= 30: # Limit line length
current_line += " " + word
else:
lines.append(current_line)
current_line = word
lines.append(current_line)
# Display each line
for i, line in enumerate(lines):
cv2.putText(image, line.strip(), (int(10 * scale_factor), int(180 * scale_factor + i*20)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5 * scale_factor, tracker.feedback_color, int(1 * scale_factor), cv2.LINE_AA)
# Instructions - moved to bottom of box
cv2.putText(image, '1:Bicep 2:Squat 3:Push-up 4:Lunge s:Save f:Fullscreen h:Help',
(int(10 * scale_factor), int(box_height - 10 * scale_factor)),
cv2.FONT_HERSHEY_SIMPLEX, 0.4 * scale_factor, (0, 0, 0), int(1 * scale_factor), cv2.LINE_AA)
#
def main():
# Initialize tracker
tracker = ExerciseTracker()
cap = cv2.VideoCapture(0)
# Check if camera opened successfully
if not cap.isOpened():
print("Error: Could not open camera.")
return
# Setup mediapipe instance
with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:
# Allow window resizing and set to full screen
cv2.namedWindow("Advanced Exercise Tracker", cv2.WINDOW_NORMAL)
cv2.setWindowProperty("Advanced Exercise Tracker", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
# Set camera resolution to HD for better quality
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
# Get image shape for dynamic coordinate calculation
h, w, _ = frame.shape
# Recolor image to RGB
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image.flags.writeable = False
# Make detection
results = pose.process(image)
# Recolor back to BGR
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Extract landmarks and process exercise
try:
if results.pose_landmarks:
landmarks = results.pose_landmarks.landmark
# Process based on exercise type
if tracker.exercise_type == ExerciseType.BICEP_CURL:
metrics = tracker.update_bicep_curl(landmarks, (h, w))
# Display angles for both arms
cv2.putText(image, f"L: {metrics['left_angle']:.1f}",
metrics['left_elbow_pos'],
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)
cv2.putText(image, f"R: {metrics['right_angle']:.1f}",
metrics['right_elbow_pos'],
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)
elif tracker.exercise_type == ExerciseType.SQUAT:
metrics = tracker.update_squat(landmarks, (h, w))
cv2.putText(image, f"Angle: {metrics['left_angle']:.1f}",
metrics['knee_pos'],
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)
elif tracker.exercise_type == ExerciseType.PUSH_UP:
metrics = tracker.update_push_up(landmarks, (h, w))
cv2.putText(image, f"Angle: {metrics['left_angle']:.1f}",
metrics['elbow_pos'],
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)
elif tracker.exercise_type == ExerciseType.LUNGE:
metrics = tracker.update_lunge(landmarks, (h, w))
cv2.putText(image, f"Angle: {metrics['left_angle']:.1f}",
metrics['knee_pos'],
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)
# Check set completion
tracker.check_set_completion()
# Speak feedback if needed
if tracker.should_speak_feedback():
speak_text(tracker.get_form_feedback())
except Exception as e:
print(f"Error processing landmarks: {e}")
# Display workout information
display_workout_info(image, tracker, w, h, landmarks if 'landmarks' in locals() else None)
# Draw progress bar and circular gauge
draw_progress_bar(image, tracker.rep_progress, (10, h-30), size=(200, 20), color=tracker.feedback_color)
draw_circular_gauge(image, tracker.symmetry_score, (w-50, 50), color=tracker.feedback_color)
# Render detections
if results.pose_landmarks:
mp_drawing.draw_landmarks(
image,
results.pose_landmarks,
mp_pose.POSE_CONNECTIONS,
mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=2),
mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)
)
# Display the image in full screen
cv2.imshow('Advanced Exercise Tracker', image)
# Key controls
key = cv2.waitKey(10) & 0xFF
if key == ord('q'):
break
elif key == ord('1'):
tracker.change_exercise(ExerciseType.BICEP_CURL)
speak_text("Switched to Bicep Curls. " + tracker.get_tutorial_text())
elif key == ord('2'):
tracker.change_exercise(ExerciseType.SQUAT)
speak_text("Switched to Squats. " + tracker.get_tutorial_text())
elif key == ord('3'):
tracker.change_exercise(ExerciseType.PUSH_UP)
speak_text("Switched to Push-ups. " + tracker.get_tutorial_text())
elif key == ord('4'):
tracker.change_exercise(ExerciseType.LUNGE)
speak_text("Switched to Lunges. " + tracker.get_tutorial_text())
elif key == ord('f'):
# Toggle full screen
current_mode = cv2.getWindowProperty("Advanced Exercise Tracker", cv2.WND_PROP_FULLSCREEN)
if current_mode == cv2.WINDOW_FULLSCREEN:
cv2.setWindowProperty("Advanced Exercise Tracker", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_NORMAL)
else:
cv2.setWindowProperty("Advanced Exercise Tracker", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
elif key == ord('s'):
# Save workout data to CSV
if tracker.save_to_csv():
cv2.putText(image, "Workout data saved!", (w//2-100, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
cv2.imshow('Advanced Exercise Tracker', image)
cv2.waitKey(1000) # Show message for 1 second
elif key == ord('h'):
# Speak tutorial for current exercise
speak_tutorial(tracker)
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()