File size: 4,875 Bytes
ae419ed | 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 | from __future__ import annotations
import math
from typing import Iterable
import numpy as np
NUM_JOINTS = 17
COCO_BONES: list[tuple[int, int]] = [
(0, 1), (0, 2), (1, 3), (2, 4),
(5, 6), (5, 7), (7, 9), (6, 8), (8, 10),
(5, 11), (6, 12), (11, 12),
(11, 13), (13, 15), (12, 14), (14, 16),
]
LOWER_BODY = [11, 12, 13, 14, 15, 16]
UPPER_BODY = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def normalize_pose(kpts: np.ndarray, eps: float = 1e-6) -> np.ndarray:
"""Normalize COCO keypoints by per-frame visible bounding box."""
out = np.asarray(kpts, dtype=np.float32).copy()
xy = out[..., :2]
conf = out[..., 2]
for t in range(out.shape[0]):
valid = conf[t] > 0
if not np.any(valid):
out[t, :, :2] = 0
continue
pts = xy[t, valid]
mn = pts.min(axis=0)
mx = pts.max(axis=0)
center = (mn + mx) / 2.0
size = np.maximum(mx - mn, eps)
out[t, :, 0] = (out[t, :, 0] - center[0]) / size[0]
out[t, :, 1] = (out[t, :, 1] - center[1]) / size[1]
out[t, ~valid, :2] = 0
return out
def resample_or_pad(kpts: np.ndarray, clip_len: int) -> np.ndarray:
if len(kpts) == clip_len:
return kpts.astype(np.float32)
if len(kpts) <= 0:
return np.zeros((clip_len, NUM_JOINTS, 3), dtype=np.float32)
if len(kpts) < clip_len:
pad = np.repeat(kpts[-1:,...], clip_len - len(kpts), axis=0)
return np.concatenate([kpts, pad], axis=0).astype(np.float32)
idx = np.linspace(0, len(kpts) - 1, clip_len).round().astype(np.int64)
return kpts[idx].astype(np.float32)
def make_clips(kpts: np.ndarray, clip_len: int, stride: int) -> list[np.ndarray]:
if len(kpts) <= clip_len:
return [resample_or_pad(kpts, clip_len)]
clips = []
for start in range(0, len(kpts) - clip_len + 1, stride):
clips.append(kpts[start:start + clip_len].astype(np.float32))
if not clips:
clips.append(resample_or_pad(kpts, clip_len))
return clips
def bone_features(joint: np.ndarray) -> np.ndarray:
bone = np.zeros_like(joint, dtype=np.float32)
for parent, child in COCO_BONES:
bone[:, child, :2] = joint[:, child, :2] - joint[:, parent, :2]
bone[:, child, 2] = np.minimum(joint[:, child, 2], joint[:, parent, 2])
return bone
def temporal_diff(x: np.ndarray) -> np.ndarray:
diff = np.zeros_like(x, dtype=np.float32)
diff[1:] = x[1:] - x[:-1]
return diff
def dynamics_features(joint: np.ndarray) -> np.ndarray:
xy = joint[..., :2]
conf = joint[..., 2:3]
vel = temporal_diff(xy)
acc = temporal_diff(vel)
center = weighted_center(xy, conf)
center_vel = temporal_diff(center)
torso = torso_angle(xy)
hip = xy[:, [11, 12], 1].mean(axis=1, keepdims=True)
hip_drop = temporal_diff(hip)
aspect = body_aspect_ratio(xy, conf)
global_dyn = np.concatenate([center_vel, torso, hip_drop, aspect], axis=1)
global_dyn = np.repeat(global_dyn[:, None, :], NUM_JOINTS, axis=1)
return np.concatenate([vel, acc, global_dyn], axis=2).astype(np.float32)
def weighted_center(xy: np.ndarray, conf: np.ndarray, eps: float = 1e-6) -> np.ndarray:
w = np.clip(conf, 0.0, 1.0)
return (xy * w).sum(axis=1) / (w.sum(axis=1) + eps)
def torso_angle(xy: np.ndarray) -> np.ndarray:
shoulder = xy[:, [5, 6]].mean(axis=1)
hip = xy[:, [11, 12]].mean(axis=1)
vec = shoulder - hip
angle = np.arctan2(vec[:, 1], vec[:, 0]) / math.pi
return angle[:, None].astype(np.float32)
def body_aspect_ratio(xy: np.ndarray, conf: np.ndarray, eps: float = 1e-6) -> np.ndarray:
ratios = []
visible = conf[..., 0] > 0
for t in range(xy.shape[0]):
if not np.any(visible[t]):
ratios.append([0.0])
continue
pts = xy[t, visible[t]]
wh = pts.max(axis=0) - pts.min(axis=0)
ratios.append([float(wh[1] / (wh[0] + eps))])
return np.asarray(ratios, dtype=np.float32)
def mask_keypoints(
joint: np.ndarray,
mode: str,
amount: float = 0.0,
rng: np.random.Generator | None = None,
) -> np.ndarray:
rng = rng or np.random.default_rng()
out = joint.copy()
if mode == "clean":
return out
if mode.startswith("missing"):
prob = amount
mask = rng.random(out.shape[:2]) < prob
out[mask] = 0
elif mode == "lower_body":
out[:, LOWER_BODY] = 0
elif mode == "upper_body":
out[:, UPPER_BODY] = 0
elif mode == "low_conf":
out[out[..., 2] < 0.5] = 0
else:
raise ValueError(f"Unknown robustness mode: {mode}")
return out.astype(np.float32)
def infer_label_from_path(path: str) -> int:
parts = [p.lower() for p in path.replace("\\", "/").split("/")]
positives = {"fall", "falls", "fallen", "positive", "1"}
return int(any(p in positives for p in parts))
|