fall / src /dynafall /features.py
minhy112's picture
Upload project files excluding raw data folder
ae419ed verified
Raw
History Blame Contribute Delete
4.88 kB
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))