minhy112's picture
Add files using upload-large-folder tool
4c79aec verified
Raw
History Blame Contribute Delete
2.49 kB
from __future__ import annotations
import numpy as np
def resize_or_pad_sequence(arr: np.ndarray, target_frames: int) -> np.ndarray:
if arr.shape[0] == target_frames:
return arr
if arr.shape[0] > target_frames:
idx = np.linspace(0, arr.shape[0] - 1, target_frames).round().astype(int)
return arr[idx]
pad = np.repeat(arr[-1:], target_frames - arr.shape[0], axis=0)
return np.concatenate([arr, pad], axis=0)
def normalize_pose_sequence(pose: np.ndarray, min_conf: float = 0.05) -> np.ndarray:
pose = pose.astype(np.float32).copy()
xy = pose[..., :2]
conf = pose[..., 2:3] if pose.shape[-1] > 2 else np.ones((*pose.shape[:2], 1), dtype=np.float32)
valid = conf[..., 0] > min_conf
out_xy = np.zeros_like(xy, dtype=np.float32)
for t in range(pose.shape[0]):
mask = valid[t]
if mask.sum() < 2:
continue
pts = xy[t, mask]
center = (pts.min(axis=0) + pts.max(axis=0)) / 2.0
size = np.maximum(pts.max(axis=0) - pts.min(axis=0), 1.0)
scale = float(max(size[0], size[1], 1.0))
out_xy[t] = (xy[t] - center) / scale
return np.concatenate([out_xy, conf.astype(np.float32)], axis=-1)
def add_keypoint_noise(pose: np.ndarray, sigma: float, rng: np.random.Generator) -> np.ndarray:
if sigma <= 0:
return pose
noisy = pose.copy()
noisy[..., :2] += rng.normal(0.0, sigma, size=noisy[..., :2].shape).astype(np.float32)
return noisy
def apply_frame_drop(pose: np.ndarray, drop_ratio: float, rng: np.random.Generator) -> np.ndarray:
if drop_ratio <= 0:
return pose
out = pose.copy()
frames = out.shape[0]
keep = rng.random(frames) > drop_ratio
keep[0] = True
last = out[0].copy()
for t in range(frames):
if keep[t]:
last = out[t].copy()
else:
out[t] = last
return out
def pose_to_feature_vector(
pose: np.ndarray,
use_confidence: bool = True,
use_velocity: bool = True,
min_conf: float = 0.05,
) -> np.ndarray:
norm = normalize_pose_sequence(pose, min_conf=min_conf)
xy = norm[..., :2]
parts = [xy.reshape(xy.shape[0], -1)]
if use_confidence:
parts.append(norm[..., 2:3].reshape(norm.shape[0], -1))
if use_velocity:
vel = np.zeros_like(xy, dtype=np.float32)
vel[1:] = xy[1:] - xy[:-1]
parts.append(vel.reshape(vel.shape[0], -1))
return np.concatenate(parts, axis=1).astype(np.float32)