baseball-engine / docs /BATTING_2D_MEASUREMENTS.md
github-actions[bot]
Automated Deploy: 0f6712d462fa0d8a00c5bbc6cfffe99ab79b85d6
16459e8
|
Raw History Blame Contribute Delete
15.9 kB
# 2D batting measurement definitions
Version: `batting-2d-v6`. Scope: face-on batting, with fixed-camera requirements only for ground-foot events and head movement. This module uses GPU pose/person outputs and CPU arithmetic, with no SAM, temporal 3D fitting, OpenSim or coaching decisions.
## Pose checkpoint and foot points
The pinned pose artifact is `rtmw-dw-x-l_simcc-cocktail14_270e-384x288_20231122`. It replaces the September cocktail13 checkpoint, whose toe outputs suffered from the upstream [foot/head training-label bug](https://github.com/open-mmlab/mmpose/issues/2771). Both archive and extracted ONNX hashes are pinned. Existing Colab model caches are replaced when their source/hash differs.
Toe/heel predictions farther from their ankle than `max(30 px, 0.75 × projected knee-to-ankle length)` are unavailable. An unknown knee/ankle also withholds its foot points. The guard does not invent replacement points or move them to the ankle. Foot points are drawn in orange in the Colab previews so these errors can be inspected.
## Reliability
All event detections and non-null metric values are estimates pending independent validation. Synthetic numerical checks validate arithmetic and abstention rules; they do not demonstrate accuracy on baseball videos. The event confidence number is capped at 0.5 and bounded by the supporting pose scores; it is a heuristic score, not a calibrated probability. No `high`/`medium` metric label is emitted.
Raw points remain unchanged in `pose_track`. For calculations, only interior missing runs of at most three frames are interpolated. A three-frame median is applied to contiguous finite runs of hip-relative body geometry before restoring the image position. This prevents a translating camera from changing the filtering of relative-hand events. Longer gaps remain missing, and a detected event needs raw supporting joints at that frame. Fixed-camera nose paths use a separate absolute-image three-frame median; smoothing affects their value.
## Scale and direction
A caller can provide a known standing image height in upright pixels with a source description. Physical player height alone does not provide that pixel scale.
The fallback is the 90th percentile of `1.08 × (nose-to-midshoulder length + midshoulder-to-midhip length + mean hip-knee-ankle chain length)`. The 1.08 correction for missing head/foot extent is a declared heuristic, not a validated anthropometric calibration. This projected skeleton estimate can be biased by foreshortening and posture; percentage metrics remain `est` and carry a scale note.
For right-handed hitters the left arm/foot leads; for left-handed hitters the right arm/foot leads. Pitcher direction may be supplied as image left/right. Otherwise it is the sign of median lead-minus-back ankle x, only when separation exceeds 4% of estimated height and it agrees with the first strong sustained hand stroke. Contradictions leave direction unknown and produce a warning; the engine never silently changes handedness. A supplied direction is an input declaration. At plant/contact, lead-leg metrics are still withheld if the declared lead ankle lies behind the other ankle or their separation is ambiguous.
## Swings and events
Automatic splitting uses hand motion relative to the hip midpoint, independently of handedness and ankle ordering. The adaptive motion threshold uses median motion plus twice its median absolute deviation, with a 30%-of-90th-percentile floor. A generic burst requires a maximum excursion of at least 12% of height, including movements that travel out and back with little net displacement. Excursions separated by at most 0.5 seconds on the available analysis clock are grouped into one candidate; missing hand evidence cannot be bridged. Strong stroke direction helps exclude an isolated slower backwards load from the rep count; it does not establish camera view or handedness.
Inter-drive midpoints prevent overlap. Up to two seconds on the analysis clock are inspected before the drive for preparation involving hands or either ankle relative to the hips. Boundaries retain that preparation with a margin instead of starting after the step. Quiet intervals trim trailing footage only after the grouped follow-through. At most 100 candidates are analyzed, with a warning if more were found. These are candidate boundaries, not qualified repetition labels. Caller-declared single-swing/range options remain available. A declared range with several separate grouped swings is ambiguous and produces no forced events.
With an unknown view, only generic stance/hand-motion onset/finish candidates can be returned as frame indices. Technique measurements remain null and `capture` contains `view_uncertain`. Physical event times are never filled from playback time. With a known face-on view and a moving/unverified camera, relative-hand events and within-frame contact proxies remain eligible, while stride/ground-foot events are withheld. Finish needs settling after the whole grouped hand movement; a brief follow-through pause is insufficient.
Event selection is restricted to the primary hand excursion inside the selected swing group. The primary excursion is the first with peak hand displacement at least 65% of the strongest excursion in that group; slower loading and later returns cannot replace it through a separate pitcher-directed search over the whole rep. A directed stroke may refine onset only when its peak lies inside that excursion. Otherwise the onset is a generic primary-hand-motion estimate: image-plane hand travel around a swing arc need not continuously point toward the supplied pitcher direction.
The contact proxy searches from shortly before the primary hand-speed peak (up to 0.04 seconds on the available analysis clock, bounded by the event support window) through the primary excursion. The end is also bounded by the directed stroke plus its short support window when available. It requires a projected lead-arm angle of at least 140 degrees, hands forward by 4% of estimated height, and raw supporting joints. It takes the first eligible angle within five degrees of the maximum extension in this window. This plateau tolerance is an unvalidated noise heuristic, not an impact model. No extension from a later bat-lowering/reset movement can supply contact. When this evidence is absent, contact and its dependent measurements remain unavailable.
| Event | Evidence and limitation |
|---|---|
| `stance_set` | Last supported quiet hands, pelvis and ankles immediately before preparation; setup walking is excluded |
| `load_start` | Sustained backward hand excursion before forward motion, using a lower threshold than the faster drive |
| `stride` | Lead ankle departs a supported old position by >2.5% of height during the final preparation step |
| `foot_contact` | After a visible lift/descent, at least two supported sole landmarks return to or below their preparation levels; first physical contact is unconfirmed |
| `foot_plant` | Lead ankle and at least two sole landmarks settle at the new image position, with observed lift/return evidence; does **not** measure full body-weight loading |
| `swing_start` | Primary hand excursion, with forward onset refined only inside that movement; exact acceleration onset remains unvalidated |
| `contact` | Visible lead-arm extension plateau with hands forward during the primary swinging movement; always estimated, no ball/sensor confirmation |
| `finish` | Observed post-drive hand settling; clip end is never forced as finish |
Events must be inside their rep and follow their physical dependencies. Hand load and foot departure can occur in either order. Stride precedes foot return/plant; load and plant precede or coincide with onset; onset precedes contact. Conflicting candidates are omitted with a reason. Foot-plant timestamps after onset remain withheld. A short confirmation window may extend beyond onset, but stays before contact and inside the rep; the event is timestamped at the window's beginning. Capture timestamps are included only from the declared physical clock. `events_ms` uses milliseconds from the rep's start; playback time never becomes physical event time.
Foot detection looks back at most two seconds on the motion-analysis clock (capped at 600 frames). It uses quiet old positions, not a median across a moving preparation, and searches past held leg kicks. The final step is selected when there are multiple preparation steps. Settling requires at least three raw-supported frames spanning approximately 60 ms, with ankle/sole window diameter at most 1.2% of image stature. Lift/descent must each exceed 1.8%, and displacement must exceed 2.5%. These are scale-relative engineering gates, not calibrated ground-contact thresholds. A lower landing in the image is allowed; a clearly higher landing without scene geometry cannot be confirmed. Missing foot points, hovering, continued travel and no distinct step do not fabricate a plant event.
Stance uses a raw-supported window of at least five frames spanning approximately 150 ms. Hand, pelvis and ankle spans must stay within 1.2% of stature, with robust drift at most 3% of stature per analysis second. The window must end within 150 ms of preparation. Quiet hands on a walking body and old pauses followed by unrelated walking do not qualify. A walk-through may have no stationary stance, leaving head path unavailable instead of reporting its setup walking as swing movement. These gates are conservative evidence checks; they do not prove a complete biomechanical stance.
## Numbers
| Key | Formula | Additional gate |
|---|---|---|
| `stride_pct_height` | `100 × abs(lead_ankle_x - back_ankle_x) / image_height_scale` at estimated foot plant | Lead side, plant and scale |
| `com_drift_pct_height` | `100 × pitcher_direction × (hip_midpoint_x - lead_ankle_x) / scale` at estimated contact | Negative is behind; hip proxy, not whole-body center of mass; same-frame estimate eligible with a moving camera |
| `foot_plant_to_contact_ms` | Physical contact time minus physical plant time, ×1000 | Both events; documented nominal 30 FPS or higher capture cadence |
| `load_tempo_s` | Physical forward-onset time minus physical hand-load-start time | Both events; documented nominal 30 FPS or higher capture cadence |
| `load_launch_ratio` | Load duration / physical onset-to-contact duration | All events; positive denominator; documented nominal 30 FPS or higher capture cadence |
| `head_movement_pct_height` | Sum of consecutive analytical nose displacements from stance to estimated contact, /scale ×100 | Fixed camera, complete analytical path; reference-only |
| `lead_knee_angle_contact_deg` | Interior projected hip-knee-ankle angle at estimated contact | Reference-only; not anatomical 3D flexion; eligible with a moving camera |
| `lateral_trunk_tilt_contact_deg` | Null | Requested anatomical tilt not established by face-on 2D |
| `hip_shoulder_separation_foot_plant_deg` | Null | Image-plane segment angles do not measure axial twist |
The load-duration/ratio definitions above are explicit implementation conventions; their exact agreement with the friend's missing detailed `POSE_DATA_SPEC.md` must be confirmed. Invalid, missing, out-of-bounds or unsupported values are null with notes. No normal ranges, faults, priority or drills are computed.
## Capture checks
Quality is checked over the selected rep ranges, or the complete clip when no candidates exist. Only the friend's recognized capture reason keys are returned. Person counts include the tracked athlete and secondary proposals at least `max(15% image height, 35% athlete height)` tall. Tiny background detections do not automatically reject the recording. A second athlete-sized person in >10% of analyzed frames still rejects it. This is a geometric detector heuristic, not a verified census of distant background people.
A padded detection box touching an image boundary is insufficient to claim cropping. It must also have missing critical head/hand/ankle points or corresponding points near that boundary. The checks also flag a large adjacent-frame box jump, a small athlete, insufficient full core joints, darkness, blur, low physical FPS and uncertain view. Mild reasons may accompany `ok:true`; fatal reasons set `ok:false` and withhold that rep's numbers.
Blur is the existing uncalibrated `1/(1+Laplacian variance/100)` heuristic. Pose responses are clipped to 0–1 for export and are not calibrated probabilities; response scales can differ between checkpoints. Person counts/boxes do not establish athlete identity or visibility. Camera stability and view are caller declarations; the API does not silently claim a validated automatic angle/stability classifier. Unknown counts or recording timing are explained in full-result warnings. Moving/unverified cameras suppress ground-foot events and head paths, not every same-frame quantity.
## Run regression checks
`tests/fixtures/walkthrough_pose.json` contains only numeric observations from the corrected model on the supplied walkthrough recording. It has no reference accuracy labels or video pixels. Tests check that this example keeps its preparation/follow-through, avoids the two false capture failures, exports plausible foot locations, withholds conflicting lead-leg measurements, and keeps unknown physical timestamps null. Constructed multi-swing trajectories separately check rep counting and arithmetic. The subsequently supplied Colab ZIPs confirm execution with this checkpoint in the 2D GPU worker. Version 3 changes only the measurement arithmetic and was replayed locally on those GPU-produced observations; a new Colab run checks the complete updated worker.
`tests/fixtures/outdoor_swing_pose.json` contains numeric pose observations from the supplied 25-playback-FPS outdoor recording. Its Colab run used the corrected pose checkpoint. Broad visually reviewed frame windows catch the old failure: swing start/contact were assigned to bat lowering at frames 105/110 instead of the swinging movement around 75–82. Version 3 replays the saved points with onset at 75 and estimated extension/contact at 79; the walkthrough contact proxy moves from 76 to 75. These checks establish the regression repair, not independently measured contact accuracy. The outdoor lead feet overlap in projection at frame 79, so its at-contact hip/knee measurements are now withheld by the existing lead-leg ambiguity check instead of being calculated during the later reset. Tests also cover caller-declared ranges, unknown view, mirroring/camera translation, raw-point gaps, contradictory projected direction and extension available only during reset.
## Optional 3D and quality layer
The API applies `measurement-quality-v2` and optional RTMW3D/SAM event-window estimates after this 2D stage. See [NINE_MEASUREMENTS.md](NINE_MEASUREMENTS.md) for all nine definitions, camera assumptions, rejection gates and Colab/model choices. Version 6 retains support for documented nominal 30 FPS or higher physical timestamps, including variable cadence and 29.97 FPS. Every interval must be <= `1.01/30` seconds. The quality layer separately rejects poorly resolved durations/ratios under ±1-frame event shifts and records contributing frame counts and resolution status. Unknown clocks still withhold timing. This module itself does not infer 3D.
## Validation remaining
The exact external `ai_coach.validate` and schemas were not supplied. Engine tests check its own matching payload schema, units, supplied plausible bounds, known capture reasons, timing gates, null notes, numerical trajectories, abstention and HTTP delivery. Deployment still needs target-GPU execution and original-video checks. Real baseball point/event/metric errors and confidence calibration remain unmeasured; the separate coach should treat current values as estimates.