Spaces:
Running on T4
Running on T4
File size: 5,732 Bytes
35e80ff | 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 | """Per-pitch 2D (virtual open-side camera) pitching metrics from OBP landmarks.
Usage (run with python -I):
python -I compute_pitching_metrics.py LANDMARKS_CSV POI_CSV METADATA_CSV OUT_CSV
Writes one row per pitch x camera config (yaw_deg, tilt_deg).
Frame: OBP lab x = toward home plate, y = toward first base, z = up.
Left-handers are mirrored (y -> -y) so the throwing side is always the same.
Virtual camera: orthographic, optical axis horizontal and along +/-y (perpendicular to the
pitcher-to-plate line) for yaw=0. Image u = right axis (here toward plate = +x), v = up.
yaw rotates the camera about the vertical axis, tilt pitches it about its own right axis.
"""
import sys
import numpy as np
import pandas as pd
CONFIGS = [(0, 0), (10, 0), (-10, 0), (20, 0), (-20, 0), (0, 3)]
def basis(yaw, tilt):
a, t = np.radians(yaw), np.radians(tilt)
r = np.array([np.cos(a), np.sin(a), 0.0]) # image right
d = np.array([-np.sin(a), np.cos(a), 0.0]) # view axis (horizontal)
up = np.array([0, 0, 1.0]) * np.cos(t) + d * np.sin(t)
return r, up
def proj(P, r, up):
return np.stack([P @ r, P @ up], axis=-1) # (...,2)
def vec_angle_deg(a, b):
na, nb = np.linalg.norm(a, axis=-1), np.linalg.norm(b, axis=-1)
c = np.sum(a * b, axis=-1) / np.maximum(na * nb, 1e-9)
return np.degrees(np.arccos(np.clip(c, -1, 1)))
def line_tilt(pt_from, pt_to):
"""Tilt from horizontal of the line from->to in image (deg, in [-90,90]); + = 'to' end higher."""
d = pt_to - pt_from
return np.sign(d[..., 1]) * np.degrees(np.arctan2(np.abs(d[..., 1]), np.abs(d[..., 0])))
def main(lm_path, poi_path, meta_path, out_path):
lm = pd.read_csv(lm_path)
poi = pd.read_csv(poi_path)[['session_pitch', 'p_throws', 'stride_length', 'torso_anterior_tilt_br',
'torso_lateral_tilt_br', 'arm_slot', 'rotation_hip_shoulder_separation_fp',
'lead_knee_extension_from_fp_to_br']]
meta = pd.read_csv(meta_path)[['session_pitch', 'user', 'playing_level', 'session_height_m', 'pitch_speed_mph']]
hand = poi.set_index('session_pitch')['p_throws']
meta = meta.set_index('session_pitch')
cols = ['rear_ankle_jc', 'lead_ankle_jc', 'lead_hip', 'rear_hip', 'lead_knee_jc', 'shoulder_jc',
'glove_shoulder_jc', 'wrist_jc', 'thorax_prox']
rows = []
for sp, g in lm.groupby('session_pitch', sort=False):
if sp not in meta.index or sp not in hand.index:
continue
g = g.sort_values('time')
t = g['time'].values
fp_t, br_t, pkh_t = g['fp_100_time'].iloc[0], g['BR_time'].iloc[0], g['pkh_time'].iloc[0]
if not np.isfinite([fp_t, br_t]).all():
continue
sgn = -1.0 if hand[sp] == 'L' else 1.0
P = {}
for c in cols:
xyz = g[[c + '_x', c + '_y', c + '_z']].values.astype(float)
xyz[:, 1] *= sgn
P[c] = xyz
ifp, ibr = int(np.argmin(np.abs(t - fp_t))), int(np.argmin(np.abs(t - br_t)))
# own peak leg lift: max lead-knee height before foot plant (3D z is vertical, camera-independent for tilt 0)
ipk = int(np.argmax(P['lead_knee_jc'][:ifp + 1, 2]))
ipk_obp = int(np.argmin(np.abs(t - pkh_t))) if np.isfinite(pkh_t) else ipk
H = meta.loc[sp, 'session_height_m']
for yaw, tilt in CONFIGS:
r, up = basis(yaw, tilt)
Q = {c: proj(P[c], r, up) for c in cols}
hipmid = (Q['lead_hip'] + Q['rear_hip']) / 2
shmid = (Q['shoulder_jc'] + Q['glove_shoulder_jc']) / 2
trunk = shmid - hipmid
# forward tilt: angle from vertical, + toward plate (u>0)
tf = np.degrees(np.arctan2(trunk[:, 0], trunk[:, 1]))
kn = 180 - vec_angle_deg(Q['lead_hip'] - Q['lead_knee_jc'], Q['lead_ankle_jc'] - Q['lead_knee_jc'])
sh_tilt = line_tilt(Q['shoulder_jc'], Q['glove_shoulder_jc'])
hp_tilt = line_tilt(Q['rear_hip'], Q['lead_hip'])
sep = sh_tilt - hp_tilt
sep = (sep + 90) % 180 - 90
arm = Q['wrist_jc'] - Q['shoulder_jc']
slot = np.degrees(np.arctan2(arm[:, 1], arm[:, 0])) # from image horizontal toward plate; 90 = vertical up
head = Q['thorax_prox']
seg = slice(ipk, ibr + 1)
path = np.sum(np.linalg.norm(np.diff(head[seg], axis=0), axis=1))
hrng_v = np.ptp(head[seg, 1])
net = np.linalg.norm(head[ibr] - head[ipk])
rows.append(dict(
session_pitch=sp, yaw_deg=yaw, tilt_deg=tilt,
stride_pct_height=100 * abs(Q['lead_ankle_jc'][ifp, 0] - Q['rear_ankle_jc'][ifp, 0]) / H,
lead_knee_flexion_fp_deg=kn[ifp], lead_knee_flexion_release_deg=kn[ibr],
lead_knee_block_deg=kn[ifp] - kn[ibr],
trunk_forward_tilt_release_deg=tf[ibr],
trunk_lateral_tilt_release_deg=sh_tilt[ibr],
arm_slot_deg=slot[ibr],
leg_lift_to_fp_ms=1000 * (t[ifp] - t[ipk]),
fp_to_release_ms=1000 * (t[ibr] - t[ifp]),
head_stability_pct_height=100 * path / H,
head_net_displacement_pct_height=100 * net / H,
head_vertical_range_pct_height=100 * hrng_v / H,
hip_shoulder_sep_fp=sep[ifp],
leg_lift_to_fp_ms_obp_pkh=1000 * (t[ifp] - t[ipk_obp]),
))
out = pd.DataFrame(rows)
out = out.merge(meta.reset_index(), on='session_pitch').merge(poi, on='session_pitch')
out.to_csv(out_path, index=False)
print('pitches', out.session_pitch.nunique(), 'rows', len(out))
if __name__ == '__main__':
main(*sys.argv[1:5])
|