Spaces:
Sleeping
Sleeping
File size: 9,551 Bytes
e317171 640b470 e317171 aaa2ffd e317171 aaa2ffd e317171 aaa2ffd e317171 aaa2ffd 547004e aaa2ffd e317171 aaa2ffd 547004e 36e6316 5362fbc e317171 |
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 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
import cv2
import torch
import random
import numpy as np
from mediapipe.python.solutions import pose
SELECTED_JOINTS = {
27: {
'pose': [0, 11, 12, 13, 14, 15, 16],
'hand': [0, 4, 5, 8, 9, 12, 13, 16, 17, 20],
}, # 27
}
def pad(joints: np.ndarray, num_frames: int = 150) -> np.ndarray:
'''
Add padding to the joints.
Parameters
----------
joints : np.ndarray
The joints to pad.
num_frames : int, default=150
The number of frames to pad.
Returns
-------
np.ndarray
The padded joints.
'''
if joints.shape[0] < num_frames:
L = joints.shape[0]
padded_joints = np.zeros((num_frames, joints.shape[1], joints.shape[2]))
padded_joints[:L, :, :] = joints
rest = num_frames - L
num = int(np.ceil(rest / L))
pad = np.concatenate([joints for _ in range(num)], 0)[:rest]
padded_joints[L:, :, :] = pad
else:
padded_joints = joints[:num_frames]
return padded_joints
def extract_joints(
source: str,
keypoints_detector,
resize_to: tuple = (256, 256),
num_joints: int = 27,
num_frames: int = 150,
num_bodies: int = 1,
num_channels: int = 3,
) -> np.ndarray:
'''
Extract the joints from the video.
Parameters
----------
source : str
The path to the video.
keypoints_detector : mediapipe.solutions.holistic.Holistic
The keypoints detector.
resize_to : tuple, default=(256, 256)
The size to resize the image.
num_joints : int, default=27
The number of joints.
num_frames : int, default=150
The number of frames.
num_bodies : int, default=1
The number of bodies.
num_channels : int, default=3
The number of channels.
Returns
-------
np.ndarray
The extracted joints.
'''
cap = cv2.VideoCapture(source)
extracted_joints = []
while cap.isOpened():
success, image = cap.read()
if not success:
break
image = cv2.resize(image, resize_to)
image = cv2.flip(image, flipCode=1)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
frame_joints = []
results = keypoints_detector.process(image)
pose = [(0.0, 0.0, 0.0)] * len(SELECTED_JOINTS[num_joints]['pose'])
if results.pose_landmarks is not None:
pose = [
(landmark.x * resize_to[0], landmark.y * resize_to[1], landmark.visibility)
for i, landmark in enumerate(results.pose_landmarks.landmark)
if i in SELECTED_JOINTS[num_joints]['pose']
]
frame_joints.extend(pose)
left_hand = [(0.0, 0.0, 0.0)] * len(SELECTED_JOINTS[num_joints]['hand'])
if results.left_hand_landmarks is not None:
left_hand = [
(landmark.x * resize_to[0], landmark.y * resize_to[1], landmark.visibility)
for i, landmark in enumerate(results.left_hand_landmarks.landmark)
if i in SELECTED_JOINTS[num_joints]['hand']
]
frame_joints.extend(left_hand)
right_hand = [(0.0, 0.0, 0.0)] * len(SELECTED_JOINTS[num_joints]['hand'])
if results.right_hand_landmarks is not None:
right_hand = [
(landmark.x * resize_to[0], landmark.y * resize_to[1], landmark.visibility)
for i, landmark in enumerate(results.right_hand_landmarks.landmark)
if i in SELECTED_JOINTS[num_joints]['hand']
]
frame_joints.extend(right_hand)
assert len(frame_joints) == num_joints, \
f'Expected {num_joints} joints, got {len(frame_joints)} joints.'
extracted_joints.append(frame_joints)
extracted_joints = np.array(extracted_joints)
extracted_joints = pad(extracted_joints, num_frames=num_frames)
fp = np.zeros(
(num_frames, num_joints, num_channels, num_bodies),
dtype=np.float32,
)
fp[:, :, :, 0] = extracted_joints
return np.transpose(fp, [2, 0, 1, 3])
def preprocess(
source: str,
keypoints_detector,
normalization: bool = True,
random_choose: bool = True,
window_size: int = 120,
) -> np.ndarray:
'''
Preprocess the video.
Parameters
----------
source : str
The path to the video.
keypoints_detector : mediapipe.solutions.holistic.Holistic
The keypoints detector.
normalization : bool, default=True
Whether to normalize the data.
random_choose : bool, default=True
Whether to randomly sample the data.
window_size : int, default=120
The window size.
Returns
-------
np.ndarray
The processed inputs for model.
'''
inputs = extract_joints(source=source, keypoints_detector=keypoints_detector)
T = inputs.shape[1]
ori_data = inputs
for t in range(T - 1):
inputs[:, t, :, :] = ori_data[:, t + 1, :, :] - ori_data[:, t, :, :]
inputs[:, T - 1, :, :] = 0
if random_choose:
inputs = random_sample_np(inputs, window_size)
else:
inputs = uniform_sample_np(inputs, window_size)
if normalization:
assert inputs.shape[0] == 3
inputs[0, :, :, :] = inputs[0, :, :, :] - inputs[0, :, 0, 0].mean(axis=0)
inputs[1, :, :, :] = inputs[1, :, :, :] - inputs[1, :, 0, 0].mean(axis=0)
return inputs[np.newaxis, :].astype(np.float32)
def random_sample_np(data: np.ndarray, size: int) -> np.ndarray:
'''
Sample the data randomly.
Parameters
----------
data : np.ndarray
The data to sample.
size : int
The size of the data to sample.
Returns
-------
np.ndarray
The sampled data.
'''
C, T, V, M = data.shape
if T == size:
return data
interval = int(np.ceil(size / T))
random_list = sorted(random.sample(list(range(T))*interval, size))
return data[:, random_list]
def uniform_sample_np(data: np.ndarray, size: int) -> np.ndarray:
'''
Sample the data uniformly.
Parameters
----------
data : np.ndarray
The data to sample.
size : int
The size of the data to sample.
Returns
-------
np.ndarray
The sampled data.
'''
C, T, V, M = data.shape
if T == size:
return data
interval = T / size
uniform_list = [int(i * interval) for i in range(size)]
return data[:, uniform_list]
def calculate_angle(
shoulder: list,
elbow: list,
wrist: list,
) -> float:
'''
Calculate the angle between the shoulder, elbow, and wrist.
Parameters
----------
shoulder : list
Shoulder coordinates.
elbow : list
Elbow coordinates.
wrist : list
Wrist coordinates.
Returns
-------
float
Angle in degree between the shoulder, elbow, and wrist.
'''
shoulder = np.array(shoulder)
elbow = np.array(elbow)
wrist = np.array(wrist)
radians = np.arctan2(wrist[1] - elbow[1], wrist[0] - elbow[0]) \
- np.arctan2(shoulder[1] - elbow[1], shoulder[0] - elbow[0])
angle = np.abs(radians * 180.0 / np.pi)
if angle > 180.0:
angle = 360 - angle
return angle
def do_hands_relax(
pose_landmarks: list,
angle_threshold: float = 160.0,
) -> bool:
'''
Check if the hand is down.
Parameters
----------
hand_landmarks : list
Hand landmarks.
angle_threshold : float, optional
Angle threshold, by default 160.0.
Returns
-------
bool
True if the hand is down, False otherwise.
'''
if pose_landmarks is None:
return True
landmarks = pose_landmarks.landmark
left_shoulder = [
landmarks[pose.PoseLandmark.LEFT_SHOULDER.value].x,
landmarks[pose.PoseLandmark.LEFT_SHOULDER.value].y,
landmarks[pose.PoseLandmark.LEFT_SHOULDER.value].visibility,
]
left_elbow = [
landmarks[pose.PoseLandmark.LEFT_ELBOW.value].x,
landmarks[pose.PoseLandmark.LEFT_ELBOW.value].y,
landmarks[pose.PoseLandmark.LEFT_SHOULDER.value].visibility,
]
left_wrist = [
landmarks[pose.PoseLandmark.LEFT_WRIST.value].x,
landmarks[pose.PoseLandmark.LEFT_WRIST.value].y,
landmarks[pose.PoseLandmark.LEFT_SHOULDER.value].visibility,
]
left_angle = calculate_angle(left_shoulder, left_elbow, left_wrist)
right_shoulder = [
landmarks[pose.PoseLandmark.RIGHT_SHOULDER.value].x,
landmarks[pose.PoseLandmark.RIGHT_SHOULDER.value].y,
landmarks[pose.PoseLandmark.RIGHT_SHOULDER.value].visibility,
]
right_elbow = [
landmarks[pose.PoseLandmark.RIGHT_ELBOW.value].x,
landmarks[pose.PoseLandmark.RIGHT_ELBOW.value].y,
landmarks[pose.PoseLandmark.RIGHT_SHOULDER.value].visibility,
]
right_wrist = [
landmarks[pose.PoseLandmark.RIGHT_WRIST.value].x,
landmarks[pose.PoseLandmark.RIGHT_WRIST.value].y,
landmarks[pose.PoseLandmark.RIGHT_SHOULDER.value].visibility,
]
right_angle = calculate_angle(right_shoulder, right_elbow, right_wrist)
is_visible = all(
[
left_shoulder[2] > 0,
left_elbow[2] > 0,
left_wrist[2] > 0,
right_shoulder[2] > 0,
right_elbow[2] > 0,
right_wrist[2] > 0,
]
)
return all(
[
is_visible,
left_angle < angle_threshold,
right_angle < angle_threshold,
]
)
|