BSuruchi commited on
Commit
fbc77ac
·
verified ·
1 Parent(s): cd228c0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +566 -0
app.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import pipeline
3
+ # Install mediapipe
4
+ #!pip install mediapipe
5
+
6
+ # *******Import necessary libraries***************
7
+ import math
8
+ import cv2
9
+ import numpy as np
10
+ from time import time
11
+ import mediapipe as mp
12
+ import matplotlib.pyplot as plt
13
+ from PIL import Image
14
+ #*******************Initialize the Pose Detection Model*****************
15
+
16
+ # Initializing mediapipe pose class.
17
+ mp_pose = mp.solutions.pose
18
+
19
+ # Setting up the Pose function.
20
+ pose = mp_pose.Pose(static_image_mode=True, min_detection_confidence=0.3, model_complexity=2)
21
+
22
+ # Initializing mediapipe drawing class, useful for annotation.
23
+ mp_drawing = mp.solutions.drawing_utils
24
+
25
+ #*********Read an Image************************
26
+
27
+ # !pip install requests
28
+ # import requests
29
+ # # Function to read an image from a URL
30
+ #def read_image_from_url(url1):
31
+ # response = requests.get(url1)
32
+ # image_array = np.asarray(bytearray(response.content), dtype=np.uint8)
33
+ # image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
34
+ # return image
35
+
36
+ # # GitHub URL of the image
37
+ # url1 = 'https://github.com/toanmolsharma/newprojecty/raw/main/media/sample.jpg'
38
+
39
+ # # Read the image from the URL
40
+ # sample_img = read_image_from_url(url1)
41
+
42
+ # # Read an image from the specified path.
43
+ # #sample_img = cv2.imread('media/sample.jpg')
44
+
45
+ # # Specify a size of the figure.
46
+ # plt.figure(figsize = [10, 10])
47
+
48
+ # # Display the sample image, also convert BGR to RGB for display.
49
+ #plt.title("Sample Image");plt.axis('off');plt.imshow(sample_img[:,:,::-1]);plt.show()
50
+
51
+
52
+
53
+ #*********************Pose Detection On Real-Time Webcam Feed/Video******
54
+
55
+ ## Setup Pose function for video.
56
+ #pose_video = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.5, model_complexity=1)
57
+
58
+ ## Initialize the VideoCapture object to read from the webcam.
59
+ #video = cv2.VideoCapture(1)
60
+
61
+ ## Create named window for resizing purposes
62
+ #cv2.namedWindow('Pose Detection', cv2.WINDOW_NORMAL)
63
+
64
+
65
+ ## Initialize the VideoCapture object to read from a video stored in the disk.
66
+ ##video = cv2.VideoCapture('media/running.mp4')
67
+
68
+ ## Set video camera size
69
+ #video.set(3,1280)
70
+ #video.set(4,960)
71
+
72
+ ## Initialize a variable to store the time of the previous frame.
73
+ #time1 = 0
74
+
75
+ ## Iterate until the video is accessed successfully.
76
+ #while video.isOpened():
77
+
78
+ # # Read a frame.
79
+ # ok, frame = video.read()
80
+
81
+ # # Check if frame is not read properly.
82
+ # if not ok:
83
+
84
+ # # Break the loop.
85
+ # break
86
+
87
+ # # Flip the frame horizontally for natural (selfie-view) visualization.
88
+ # frame = cv2.flip(frame, 1)
89
+
90
+ # # Get the width and height of the frame
91
+ # frame_height, frame_width, _ = frame.shape
92
+
93
+ # # Resize the frame while keeping the aspect ratio.
94
+ # frame = cv2.resize(frame, (int(frame_width * (640 / frame_height)), 640))
95
+
96
+ # # Perform Pose landmark detection.
97
+ #frame, _ = detectPose(frame, pose_video, display=False)
98
+
99
+ ## Set the time for this frame to the current time.
100
+ ##time2 = time()
101
+
102
+ # #Check if the difference between the previous and this frame time > 0 to avoid division by zero.
103
+ #if (time2 - time1) > 0:
104
+
105
+ # # Calculate the number of frames per second.
106
+ # frames_per_second = 1.0 / (time2 - time1)
107
+
108
+ # # Write the calculated number of frames per second on the frame.
109
+ #cv2.putText(frame, 'FPS: {}'.format(int(frames_per_second)), (10, 30),cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 3)
110
+
111
+ ## Update the previous frame time to this frame time.
112
+ ## As this frame will become previous frame in next iteration.
113
+ #time1 = time2
114
+
115
+ ## Display the frame.
116
+ #cv2.imshow('Pose Detection', frame)
117
+
118
+ # # Wait until a key is pressed.
119
+ # # Retreive the ASCII code of the key pressed
120
+ # k = cv2.waitKey(1) & 0xFF
121
+
122
+ # # Check if 'ESC' is pressed.
123
+ #if(k == 27):
124
+
125
+ # # Break the loop.
126
+ # break
127
+
128
+ ## Release the VideoCapture object.
129
+ #video.release()
130
+
131
+ ## Close the windows.
132
+ #cv2.destroyAllWindows()
133
+
134
+
135
+ #************************Create a Pose Detection Function*******************
136
+ def detectPose(image, pose, display=True):
137
+ '''
138
+ This function performs pose detection on an image.
139
+ Args:
140
+ image: The input image with a prominent person whose pose landmarks needs to be detected.
141
+ pose: The pose setup function required to perform the pose detection.
142
+ display: A boolean value that is if set to true the function displays the original input image, the resultant image,
143
+ and the pose landmarks in 3D plot and returns nothing.
144
+ Returns:
145
+ output_image: The input image with the detected pose landmarks drawn.
146
+ landmarks: A list of detected landmarks converted into their original scale.
147
+ '''
148
+
149
+ # Create a copy of the input image.
150
+ output_image = image.copy()
151
+
152
+ # Convert the image from BGR into RGB format.
153
+ imageRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
154
+
155
+ # Perform the Pose Detection.
156
+ results = pose.process(imageRGB)
157
+
158
+ # Retrieve the height and width of the input image.
159
+ height, width, _ = image.shape
160
+
161
+ # Initialize a list to store the detected landmarks.
162
+ landmarks = []
163
+
164
+ # Check if any landmarks are detected.
165
+ if results.pose_landmarks:
166
+
167
+ # Draw Pose landmarks on the output image.
168
+ mp_drawing.draw_landmarks(image=output_image, landmark_list=results.pose_landmarks,
169
+ connections=mp_pose.POSE_CONNECTIONS)
170
+
171
+ # Iterate over the detected landmarks.
172
+ for landmark in results.pose_landmarks.landmark:
173
+
174
+ # Append the landmark into the list.
175
+ landmarks.append((int(landmark.x * width), int(landmark.y * height),
176
+ (landmark.z * width)))
177
+
178
+ # Check if the original input image and the resultant image are specified to be displayed.
179
+ if display:
180
+
181
+ # Display the original input image and the resultant image.
182
+ plt.figure(figsize=[22,22])
183
+ plt.subplot(121);plt.imshow(image[:,:,::-1]);plt.title("Original Image");plt.axis('off');
184
+ plt.subplot(122);plt.imshow(output_image[:,:,::-1]);plt.title("Output Image");plt.axis('off');
185
+
186
+ # Also Plot the Pose landmarks in 3D.
187
+ mp_drawing.plot_landmarks(results.pose_world_landmarks, mp_pose.POSE_CONNECTIONS)
188
+
189
+ # Otherwise
190
+ else:
191
+
192
+ # Return the output image and the found landmarks.
193
+ return output_image, landmarks
194
+
195
+
196
+
197
+ # ********************Pose Classification with Angle Heuristics*****************
198
+
199
+ def calculateAngle(landmark1, landmark2, landmark3):
200
+ '''
201
+ This function calculates angle between three different landmarks.
202
+ Args:
203
+ landmark1: The first landmark containing the x,y and z coordinates.
204
+ landmark2: The second landmark containing the x,y and z coordinates.
205
+ landmark3: The third landmark containing the x,y and z coordinates.
206
+ Returns:
207
+ angle: The calculated angle between the three landmarks.
208
+ '''
209
+
210
+ # Get the required landmarks coordinates.
211
+ x1, y1, _ = landmark1
212
+ x2, y2, _ = landmark2
213
+ x3, y3, _ = landmark3
214
+
215
+ # Calculate the angle between the three points
216
+ angle = math.degrees(math.atan2(y3 - y2, x3 - x2) - math.atan2(y1 - y2, x1 - x2))
217
+
218
+ # Check if the angle is less than zero.
219
+ if angle < 0:
220
+
221
+ # Add 360 to the found angle.
222
+ angle += 360
223
+
224
+ # Return the calculated angle.
225
+ return angle
226
+
227
+
228
+
229
+ #***************************Create a Function to Perform Pose Classification***************
230
+
231
+ def classifyPose(landmarks, output_image, display=False):
232
+
233
+ # Initialize the label of the pose. It is not known at this stage.
234
+ label = "Unknown Pose"
235
+
236
+ # Specify the color (Red) with which the label will be written on the image.
237
+ color = (0, 0, 255)
238
+
239
+ # Calculate the required angles.
240
+ #----------------------------------------------------------------------------------------------------------------
241
+
242
+ # Get the angle between the left shoulder, elbow and wrist points.
243
+ left_elbow_angle = calculateAngle(landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value],
244
+ landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value],
245
+ landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value])
246
+
247
+ # Get the angle between the right shoulder, elbow and wrist points.
248
+ right_elbow_angle = calculateAngle(landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value],
249
+ landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value],
250
+ landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value])
251
+
252
+ # Get the angle between the left elbow, shoulder and hip points.
253
+ left_shoulder_angle = calculateAngle(landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value],
254
+ landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value],
255
+ landmarks[mp_pose.PoseLandmark.LEFT_HIP.value])
256
+
257
+ # Get the angle between the right hip, shoulder and elbow points.
258
+ right_shoulder_angle = calculateAngle(landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value],
259
+ landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value],
260
+ landmarks[mp_pose.PoseLandmark.RIGHT_ELBOW.value])
261
+
262
+ # Get the angle between the left hip, knee and ankle points.
263
+ left_knee_angle = calculateAngle(landmarks[mp_pose.PoseLandmark.LEFT_HIP.value],
264
+ landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value],
265
+ landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value])
266
+
267
+ # Get the angle between the right hip, knee and ankle points
268
+ right_knee_angle = calculateAngle(landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value],
269
+ landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value],
270
+ landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value])
271
+
272
+ #----------------------------------------------------------------------------------------------------------------
273
+ # Check for Five-Pointed Star Pose
274
+ if abs(landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value][1] - landmarks[mp_pose.PoseLandmark.LEFT_HIP.value][1]) < 100 and \
275
+ abs(landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value][1] - landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value][1]) < 100 and \
276
+ abs(landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value][0] - landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value][0]) > 200 and \
277
+ abs(landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value][0] - landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value][0]) > 200:
278
+ label = "Five-Pointed Star Pose"
279
+
280
+ # Check if it is the warrior II pose or the T pose.
281
+ # As for both of them, both arms should be straight and shoulders should be at the specific angle.
282
+ #----------------------------------------------------------------------------------------------------------------
283
+
284
+ # Check if the both arms are straight.
285
+ if left_elbow_angle > 165 and left_elbow_angle < 195 and right_elbow_angle > 165 and right_elbow_angle < 195:
286
+
287
+ # Check if shoulders are at the required angle.
288
+ if left_shoulder_angle > 80 and left_shoulder_angle < 110 and right_shoulder_angle > 80 and right_shoulder_angle < 110:
289
+
290
+ # Check if it is the warrior II pose.
291
+ #----------------------------------------------------------------------------------------------------------------
292
+
293
+ # Check if one leg is straight.
294
+ if left_knee_angle > 165 and left_knee_angle < 195 or right_knee_angle > 165 and right_knee_angle < 195:
295
+
296
+ # Check if the other leg is bended at the required angle.
297
+ if left_knee_angle > 90 and left_knee_angle < 120 or right_knee_angle > 90 and right_knee_angle < 120:
298
+
299
+ # Specify the label of the pose that is Warrior II pose.
300
+ label = 'Warrior II Pose'
301
+
302
+ #----------------------------------------------------------------------------------------------------------------
303
+
304
+ # Check if it is the T pose.
305
+ #----------------------------------------------------------------------------------------------------------------
306
+
307
+ # Check if both legs are straight
308
+ if left_knee_angle > 160 and left_knee_angle < 195 and right_knee_angle > 160 and right_knee_angle < 195:
309
+
310
+ # Specify the label of the pose that is tree pose.
311
+ label = 'T Pose'
312
+
313
+ #----------------------------------------------------------------------------------------------------------------
314
+
315
+ # Check if it is the tree pose.
316
+ #----------------------------------------------------------------------------------------------------------------
317
+
318
+ # Check if one leg is straight
319
+ if left_knee_angle > 165 and left_knee_angle < 195 or right_knee_angle > 165 and right_knee_angle < 195:
320
+
321
+ # Check if the other leg is bended at the required angle.
322
+ if left_knee_angle > 315 and left_knee_angle < 335 or right_knee_angle > 25 and right_knee_angle < 45:
323
+
324
+ # Specify the label of the pose that is tree pose.
325
+ label = 'Tree Pose'
326
+
327
+ # Check for Upward Salute Pose
328
+ if abs(landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value][0] - landmarks[mp_pose.PoseLandmark.LEFT_HIP.value][0]) < 100 and \
329
+ abs(landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value][0] - landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value][0]) < 100 and \
330
+ landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value][1] < landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value][1] and \
331
+ landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value][1] < landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value][1] and \
332
+ abs(landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value][1] - landmarks[mp_pose.PoseLandmark.RIGHT_SHOULDER.value][1]) < 50:
333
+ label = "Upward Salute Pose"
334
+
335
+ # Check for Hands Under Feet Pose
336
+ if landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value][1] > landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value][1] and \
337
+ landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value][1] > landmarks[mp_pose.PoseLandmark.RIGHT_KNEE.value][1] and \
338
+ abs(landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value][0] - landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value][0]) < 50 and \
339
+ abs(landmarks[mp_pose.PoseLandmark.RIGHT_WRIST.value][0] - landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value][0]) < 50:
340
+ label = "Hands Under Feet Pose"
341
+
342
+
343
+ #----------------------------------------------------------------------------------------------------------------
344
+
345
+ # Check if the pose is classified successfully
346
+ if label != 'Unknown Pose':
347
+
348
+ # Update the color (to green) with which the label will be written on the image.
349
+ color = (0, 255, 0)
350
+
351
+ # Write the label on the output image.
352
+ cv2.putText(output_image, label, (10, 30),cv2.FONT_HERSHEY_PLAIN, 2, color, 2)
353
+
354
+ # Check if the resultant image is specified to be displayed.
355
+ if display:
356
+
357
+ # Display the resultant image.
358
+ plt.figure(figsize=[10,10])
359
+ plt.imshow(output_image[:,:,::-1]);plt.title("Output Image");plt.axis('off');
360
+
361
+ else:
362
+
363
+ # Return the output image and the classified label.
364
+ return output_image, label
365
+
366
+ #******************************Pose Classification On Real-Time Webcam Feed*****************
367
+ '''
368
+ # Setup Pose function for video.
369
+ pose_video = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.5, model_complexity=1)
370
+
371
+ # Initialize the VideoCapture object to read from the webcam.
372
+ camera_video = cv2.VideoCapture(0)
373
+ camera_video.set(3,1280)
374
+ camera_video.set(4,960)
375
+
376
+ # Initialize a resizable window.
377
+ cv2.namedWindow('Pose Classification', cv2.WINDOW_NORMAL)
378
+
379
+ # Iterate until the webcam is accessed successfully.
380
+ while camera_video.isOpened():
381
+
382
+ # Read a frame.
383
+ ok, frame = camera_video.read()
384
+
385
+ # Check if frame is not read properly.
386
+ if not ok:
387
+
388
+ # Continue to the next iteration to read the next frame and ignore the empty camera frame.
389
+ continue
390
+
391
+ # Flip the frame horizontally for natural (selfie-view) visualization.
392
+ frame = cv2.flip(frame, 1)
393
+
394
+ # Get the width and height of the frame
395
+ frame_height, frame_width, _ = frame.shape
396
+
397
+ # Resize the frame while keeping the aspect ratio.
398
+ frame = cv2.resize(frame, (int(frame_width * (640 / frame_height)), 640))
399
+
400
+ # Perform Pose landmark detection.
401
+ frame, landmarks = detectPose(frame, pose_video, display=False)
402
+
403
+ # Check if the landmarks are detected.
404
+ if landmarks:
405
+
406
+ # Perform the Pose Classification.
407
+ frame, _ = classifyPose(landmarks, frame, display=False)
408
+
409
+ # Display the frame.
410
+ cv2.imshow('Pose Classification', frame)
411
+
412
+ # Wait until a key is pressed.
413
+ # Retreive the ASCII code of the key pressed
414
+ k = cv2.waitKey(1) & 0xFF
415
+
416
+ # Check if 'ESC' is pressed.
417
+ if(k == 27):
418
+
419
+ # Break the loop.
420
+ break
421
+
422
+ # Release the VideoCapture object and close the windows.
423
+ camera_video.release()
424
+ cv2.destroyAllWindows()
425
+
426
+
427
+ # Create a Gradio interface
428
+ iface = gr.Interface(
429
+ fn=detect_yoga_poses,
430
+ inputs=None,
431
+ outputs=None,
432
+ title="Live Yoga Pose Detection",
433
+ description="This app detects yoga poses from the live camera feed using MediaPipe.",
434
+ )
435
+ '''
436
+
437
+ #import streamlit as st
438
+ #import cv2
439
+ #import numpy as np
440
+ #from PIL import Image
441
+ #from transformers import pipeline
442
+
443
+ # Function to load model from Hugging Face
444
+ @st.cache(allow_output_mutation=True)
445
+ def load_model():
446
+ return pipeline("pose-detection", device=0) # Adjust device as per your requirement
447
+
448
+ # Function to detect yoga pose from image
449
+ def detect_yoga_pose(image):
450
+ # Convert PIL image to OpenCV format
451
+ cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
452
+ # Your pose detection logic here
453
+ # Replace the following line with your actual pose detection code
454
+ return "Detected yoga pose: Warrior II"
455
+
456
+ def main():
457
+ st.title("Yoga Pose Detection from Live Camera Feed")
458
+
459
+ # Load the model
460
+ model = load_model()
461
+
462
+
463
+
464
+
465
+ # Setup Pose function for video.
466
+ pose_video = mp_pose.Pose(static_image_mode=False, min_detection_confidence=0.5, model_complexity=1)
467
+
468
+ # Accessing web cam : Initialize the VideoCapture object to read from the webcam.
469
+ camera_video = cv2.VideoCapture(0)
470
+ camera_video.set(3,1280)
471
+ camera_video.set(4,960)
472
+
473
+ # Initialize a resizable window.
474
+ cv2.namedWindow('Pose Classification', cv2.WINDOW_NORMAL)
475
+
476
+ # Iterate until the webcam is accessed successfully.
477
+ while camera_video.isOpened():
478
+
479
+ # Read a frame.
480
+ ok, frame = camera_video.read()
481
+
482
+ # Check if frame is not read properly.
483
+ if not ok:
484
+
485
+ # Continue to the next iteration to read the next frame and ignore the empty camera frame.
486
+ continue
487
+
488
+ # Flip the frame horizontally for natural (selfie-view) visualization.
489
+ frame = cv2.flip(frame, 1)
490
+
491
+ # Get the width and height of the frame
492
+ frame_height, frame_width, _ = frame.shape
493
+
494
+ # Resize the frame while keeping the aspect ratio.
495
+ frame = cv2.resize(frame, (int(frame_width * (640 / frame_height)), 640))
496
+
497
+ # Perform Pose landmark detection.
498
+ frame, landmarks = detectPose(frame, pose_video, display=False)
499
+
500
+ # Check if the landmarks are detected.
501
+ if landmarks:
502
+
503
+ # Perform the Pose Classification.
504
+ frame, _ = classifyPose(landmarks, frame, display=False)
505
+
506
+ # Display the frame.
507
+ cv2.imshow('Pose Classification', frame)
508
+
509
+ # Wait until a key is pressed.
510
+ # Retreive the ASCII code of the key pressed
511
+ k = cv2.waitKey(1) & 0xFF
512
+
513
+ # Check if 'ESC' is pressed.
514
+ if(k == 27):
515
+
516
+ # Break the loop.
517
+ break
518
+
519
+ # Release the VideoCapture object, close Streamlit app and close the windows.
520
+ camera_video.release()
521
+ st.stop()
522
+ cv2.destroyAllWindows()
523
+
524
+
525
+
526
+
527
+
528
+
529
+
530
+
531
+
532
+
533
+
534
+ '''
535
+
536
+ # Accessing the webcam
537
+ cap = cv2.VideoCapture(0)
538
+
539
+ # Run the app
540
+ while True:
541
+ ret, frame = cap.read()
542
+
543
+ # Display the webcam feed
544
+ st.image(frame, channels="BGR")
545
+
546
+ # Convert the OpenCV frame to PIL image
547
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
548
+ #pil_image = Image.fromarray(frame)
549
+
550
+ # Detect yoga pose from the image
551
+ pose = detect_yoga_pose(pil_image)
552
+
553
+ # Display the detected yoga pose
554
+ st.write("Detected Yoga Pose:", pose)
555
+
556
+ # Close the webcam feed
557
+ if st.button("Stop"):
558
+ break
559
+
560
+ # Release the webcam and close Streamlit app
561
+ cap.release()
562
+ st.stop()
563
+ '''
564
+
565
+ if __name__ == "__main__":
566
+ main()