-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
210 lines (171 loc) · 7.88 KB
/
app.py
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
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 28 19:19:44 2021
@author: Sonu
"""
import time
from playsound import playsound
import csv
import numpy as np
import cv2
from flask import Flask, render_template, Response, request
import mediapipe as mp
workout = "squats"
md_drawing=mp.solutions.drawing_utils
md_drawing_styles=mp.solutions.drawing_styles
md_pose = mp.solutions.pose
app = Flask(__name__)
@app.route('/')
def index():
"""Video streaming home page."""
return render_template('index.html')
def diff(v1,v2):
result = ( (v1-v2)/(v1+v2)/2)*100
return abs(result)
def calculate_angle(a,b,c):
a = np.array(a) # First
b = np.array(b) # Mid
c = np.array(c) # End
radians = np.arctan2(c[1]-b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0])
angle = np.abs(radians*180.0/np.pi)
#if angle >180.0:
#angle = 360-angle
return angle
def bp_coordinates(body_parts, idx):
"""
Convenience method for getting (x, y) coordinates for
a given body part id.
returns tuple of (x, y) coordinates
"""
return (body_parts[idx].x, body_parts[idx].y)
def gen(exercice):
position = None
previous_time = 0
# creating our model to draw landmarks
mpDraw = mp.solutions.drawing_utils
# creating our model to detected our pose
my_pose = mp.solutions.pose
pose = my_pose.Pose()
counter = 0
stage = None
"""Video streaming generator function."""
cap = cv2.VideoCapture(0)
while True:
success, img = cap.read()
# converting image to RGB from BGR cuz mediapipe only work on RGB
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
result = pose.process(imgRGB)
if result.pose_landmarks:
mpDraw.draw_landmarks(img, result.pose_landmarks, my_pose.POSE_CONNECTIONS)
if result.pose_landmarks:
landmarks = result.pose_landmarks.landmark
#nose = (landmarks[0]) #array for nose
#left_eye_inner = (landmarks[1])
#e= np.array(landmarks)
#print(e)
#with open('readme.txt', 'w') as f:
# f.write(str(e) + str(""))
#print(keypoints)
#upper_body_cords_header = [landmarks[11],landmarks[13]]
#print(upper_body_cords_header)
try:
shoulder = [landmarks[md_pose.PoseLandmark.LEFT_SHOULDER.value].x,landmarks[md_pose.PoseLandmark.LEFT_SHOULDER.value].y]
elbow = [landmarks[md_pose.PoseLandmark.LEFT_ELBOW.value].x,landmarks[md_pose.PoseLandmark.LEFT_ELBOW.value].y]
wrist = [landmarks[md_pose.PoseLandmark.LEFT_WRIST.value].x,landmarks[md_pose.PoseLandmark.LEFT_WRIST.value].y]
hip = [landmarks[md_pose.PoseLandmark.LEFT_HIP.value].x,landmarks[md_pose.PoseLandmark.LEFT_HIP.value].y]
shoulderr = [landmarks[md_pose.PoseLandmark.RIGHT_SHOULDER.value].x,landmarks[md_pose.PoseLandmark.RIGHT_SHOULDER.value].y]
elbowr = [landmarks[md_pose.PoseLandmark.RIGHT_ELBOW.value].x,landmarks[md_pose.PoseLandmark.RIGHT_ELBOW.value].y]
wristr = [landmarks[md_pose.PoseLandmark.RIGHT_WRIST.value].x,landmarks[md_pose.PoseLandmark.RIGHT_WRIST.value].y]
angler = calculate_angle(shoulderr,elbowr,wristr)
knee = [landmarks[md_pose.PoseLandmark.LEFT_KNEE.value].x,landmarks[md_pose.PoseLandmark.LEFT_KNEE.value].y]
ankle = [landmarks[md_pose.PoseLandmark.LEFT_ANKLE.value].x,landmarks[md_pose.PoseLandmark.LEFT_ANKLE.value].y]
legs_angle = calculate_angle(hip,knee,ankle)
angle_knee = calculate_angle(hip, knee, ankle) #Knee joint angle
angle = calculate_angle(shoulder, elbow, wrist)
except:
pass
workout = exercice
if workout == "squats":
# Curl counter logic
if angle_knee > 169:
stage = "up"
if angle_knee <= 90 and stage =='up':
stage="down"
counter +=1
playsound('sound.mp3',block=False)
print(counter)
else:
if workout == "pushups":
if (angle > 160 and angler > 160):
stage = "down"
if (angle < 90 and stage =='down'and angler < 90):
stage="up"
counter +=1
playsound('sound.mp3',block=False)
print(counter)
if workout == "mma":
if (angle > 160 and angler > 160):
stage = "down"
if (angle < 50 and stage =='down'and angler < 90):
stage="up"
counter +=1
playsound('sound.mp3',block=False)
print(counter)
#print(str("ZERO :") +str(array_shoulder_l[0])+" "+str(array_shoulder_l[1]))
#insh = (str(calculate_angle(array_shoulder_l,array_forearm_l,array_wrist_l)))
#print(insh)
cv2.rectangle(img, (0,0), (225,73), (245,117,16), -1)
cv2.putText(img, str(legs_angle),
tuple(np.multiply(knee, [640, 480]).astype(int)),
cv2.FONT_HERSHEY_SIMPLEX, 5.5, (255, 255, 255), 2, cv2.LINE_AA
)
cv2.putText(img, (str(stage) + str(" ") + str(counter)+ str("")),
(10,60),
cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 2, cv2.LINE_AA)
# checking video frame rate
current_time = time.time()
fps = 1 / (current_time - previous_time)
previous_time = current_time
# Writing FrameRate on video
cv2.putText(img, str(int(fps)), (280, 50), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
#cv2.imshow("Pose detection", img)
frame = cv2.imencode('.jpg', img)[1].tobytes()
yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
key = cv2.waitKey(20)
if key == 27:
break
@app.route('/video_feed_pushups',methods=['GET', 'POST'])
def video_feed():
if request.method == 'POST':
# Then get the data from the form
tag = request.form['tag']
print(tag)
# Get the username/password associated with this tag
#user, password = tag_lookup(tag)
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen("pushups"),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/video_feed_squats',methods=['GET', 'POST'])
def squats():
if request.method == 'POST':
# Then get the data from the form
tag = request.form['tag']
print(tag)
# Get the username/password associated with this tag
#user, password = tag_lookup(tag)
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen("squats"),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/video_feed_mma',methods=['GET', 'POST'])
def mma():
if request.method == 'POST':
# Then get the data from the form
tag = request.form['tag']
print(tag)
# Get the username/password associated with this tag
#user, password = tag_lookup(tag)
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen("mma"),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__=="__main__":
app.run(debug=True)