swingpositions 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- swingpositions/__init__.py +16 -0
- swingpositions/__main__.py +3 -0
- swingpositions/analyzer.py +452 -0
- swingpositions/cli.py +302 -0
- swingpositions/data/default_accuracy.json +302 -0
- swingpositions/data/default_params.json +32 -0
- swingpositions/demo.py +289 -0
- swingpositions/evaluate.py +93 -0
- swingpositions/features.py +97 -0
- swingpositions/fit.py +152 -0
- swingpositions/models.py +91 -0
- swingpositions/report.py +86 -0
- swingpositions/synthetic.py +229 -0
- swingpositions/tracking.py +202 -0
- swingpositions/video.py +100 -0
- swingpositions/viewer.py +587 -0
- swingpositions/viewer_static/app.css +375 -0
- swingpositions/viewer_static/fonts/Barlow-Medium.woff2 +0 -0
- swingpositions/viewer_static/fonts/Barlow-Regular.woff2 +0 -0
- swingpositions/viewer_static/fonts/Barlow-SemiBold.woff2 +0 -0
- swingpositions/viewer_static/fonts/OFL.txt +93 -0
- swingpositions/viewer_static/icon.svg +1 -0
- swingpositions/viewer_static/index.html +40 -0
- swingpositions/viewer_static/js/app.mjs +114 -0
- swingpositions/viewer_static/js/core.mjs +350 -0
- swingpositions/viewer_static/js/dom.mjs +62 -0
- swingpositions/viewer_static/js/player.mjs +184 -0
- swingpositions/viewer_static/js/reading.mjs +80 -0
- swingpositions/viewer_static/js/store.mjs +100 -0
- swingpositions/viewer_static/js/views/about.mjs +80 -0
- swingpositions/viewer_static/js/views/compare.mjs +149 -0
- swingpositions/viewer_static/js/views/corrections.mjs +76 -0
- swingpositions/viewer_static/js/views/gallery.mjs +53 -0
- swingpositions/viewer_static/js/views/list.mjs +88 -0
- swingpositions/viewer_static/js/views/swing.mjs +222 -0
- swingpositions/viewer_static/js/views/tempo.mjs +153 -0
- swingpositions-0.1.0.dist-info/METADATA +317 -0
- swingpositions-0.1.0.dist-info/RECORD +42 -0
- swingpositions-0.1.0.dist-info/WHEEL +4 -0
- swingpositions-0.1.0.dist-info/entry_points.txt +2 -0
- swingpositions-0.1.0.dist-info/licenses/LICENSE +202 -0
- swingpositions-0.1.0.dist-info/licenses/NOTICE +22 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""swingpositions: golf swing P1-P10 positions and tempo from a down-the-line video."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .analyzer import analyze_track, analyze_video_track, load_default_params, load_params # noqa: E402
|
|
6
|
+
from .features import LABELS, SHORT # noqa: E402
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"__version__",
|
|
10
|
+
"LABELS",
|
|
11
|
+
"SHORT",
|
|
12
|
+
"analyze_track",
|
|
13
|
+
"analyze_video_track",
|
|
14
|
+
"load_default_params",
|
|
15
|
+
"load_params",
|
|
16
|
+
]
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"""P1-P10 analyzer for down-the-line swing video (right-handed golfer).
|
|
2
|
+
|
|
3
|
+
Input: a track (see tracking.py) for one video. Output: ten events per swing, each with a frame index,
|
|
4
|
+
the cue that placed it and a confidence, plus tempo in real seconds.
|
|
5
|
+
|
|
6
|
+
Event definitions (down-the-line camera):
|
|
7
|
+
P1 Address: last still frame before the club starts back (takeaway onset).
|
|
8
|
+
P2 Shaft parallel, backswing: the clubhead passes the height of the hands on the way up.
|
|
9
|
+
P3 Lead arm parallel to the ground, backswing.
|
|
10
|
+
P4 Top: the club's change of direction.
|
|
11
|
+
P5 Lead arm parallel, downswing.
|
|
12
|
+
P6 Shaft parallel, downswing: clubhead passes hand height on the way down.
|
|
13
|
+
P7 Impact.
|
|
14
|
+
P8 Shaft parallel, follow-through: clubhead passes hand height after impact.
|
|
15
|
+
P9 Trail arm parallel, follow-through.
|
|
16
|
+
P10 Finish: the body and club come to rest.
|
|
17
|
+
|
|
18
|
+
Every frame window below is written for 120 fps capture and scaled by capture_fps/120. Thresholds are in
|
|
19
|
+
torso lengths, so they do not depend on frame rate or camera distance; every *_bias parameter is in
|
|
20
|
+
120 fps frames and is scaled the same way.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
from importlib import resources
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
|
|
30
|
+
from .features import LABELS, SHORT, clip_features, smooth
|
|
31
|
+
from .video import classify_capture_fps, frame_time, slowmo_factor
|
|
32
|
+
|
|
33
|
+
SWING_MAX_DOWN_S = 0.45 # a real downswing (top -> lowest hands) takes less real time than this
|
|
34
|
+
SWING_MIN_GAP_S = 3.0 # two separate swings have impacts at least this far apart (real seconds)
|
|
35
|
+
SLICE_PAD_S = 3.0 # multi-swing videos: analyse impact +/- this many real seconds per swing
|
|
36
|
+
MIN_POSE_COVERAGE = 0.2 # fraction of frames that must have a detected golfer
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_default_params():
|
|
40
|
+
"""The fitted default parameters shipped with the package."""
|
|
41
|
+
with resources.files("swingpositions").joinpath("data/default_params.json").open() as f:
|
|
42
|
+
return json.load(f)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load_params(path=None):
|
|
46
|
+
if path is None:
|
|
47
|
+
return load_default_params()
|
|
48
|
+
with open(path) as f:
|
|
49
|
+
P = json.load(f)
|
|
50
|
+
base = load_default_params()
|
|
51
|
+
base.update(P)
|
|
52
|
+
return base
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ---------------------------------------------------------------------------------------------- helpers
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def crossing(y, a, b, thr, direction, last=False):
|
|
59
|
+
"""Fractional index where y crosses thr inside [a, b). direction +1 upward, -1 downward.
|
|
60
|
+
|
|
61
|
+
Returns the first crossing (or the last one with last=True), linearly interpolated between the two
|
|
62
|
+
samples that straddle the threshold, or None.
|
|
63
|
+
"""
|
|
64
|
+
a = max(int(a), 1)
|
|
65
|
+
b = min(int(b), len(y))
|
|
66
|
+
rng = range(b - 1, a - 1, -1) if last else range(a, b)
|
|
67
|
+
for i in rng:
|
|
68
|
+
y0, y1 = y[i - 1], y[i]
|
|
69
|
+
if direction > 0 and y0 < thr <= y1:
|
|
70
|
+
return i - 1 + (thr - y0) / (y1 - y0)
|
|
71
|
+
if direction < 0 and y0 > thr >= y1:
|
|
72
|
+
return i - 1 + (y0 - thr) / (y0 - y1)
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def club_up(track):
|
|
77
|
+
"""+1 when the visible shaft points up from the grip, -1 when down, 0 unknown (per frame)."""
|
|
78
|
+
ang = track["club"][:, 0]
|
|
79
|
+
n = track["club"][:, 1]
|
|
80
|
+
return np.where(np.isnan(ang) | (n < 40), 0, np.sign(np.sin(np.radians(np.nan_to_num(ang)))))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def flip(sign, a, b, frm, to, min_run):
|
|
84
|
+
"""First index in [a, b) where a sign series changes from `frm` to `to` and holds for min_run frames.
|
|
85
|
+
|
|
86
|
+
Returns (boundary, gap): the midpoint between the last `frm` frame and the first `to` frame, and the
|
|
87
|
+
number of unknown frames in between. (None, None) if there is no such flip.
|
|
88
|
+
"""
|
|
89
|
+
a = max(int(a), 0)
|
|
90
|
+
b = min(int(b), len(sign))
|
|
91
|
+
last_frm = None
|
|
92
|
+
i = a
|
|
93
|
+
while i < b:
|
|
94
|
+
if sign[i] == frm:
|
|
95
|
+
last_frm = i
|
|
96
|
+
elif sign[i] == to and last_frm is not None:
|
|
97
|
+
j = i
|
|
98
|
+
run = 0
|
|
99
|
+
while j < len(sign) and sign[j] == to and run < min_run:
|
|
100
|
+
run += 1
|
|
101
|
+
j += 1
|
|
102
|
+
if run >= min_run:
|
|
103
|
+
return (last_frm + i) / 2.0, i - last_frm - 1
|
|
104
|
+
i += 1
|
|
105
|
+
return None, None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def find_swings(F, max_down=60):
|
|
109
|
+
"""Candidate swings: a high hand position followed within `max_down` frames by a low one.
|
|
110
|
+
|
|
111
|
+
Returns [(drop, top, low)] sorted by drop (largest first); candidates sharing a top are merged.
|
|
112
|
+
"""
|
|
113
|
+
y = F["hand_y"]
|
|
114
|
+
T = len(y)
|
|
115
|
+
cands = []
|
|
116
|
+
for low in range(1, T):
|
|
117
|
+
a = max(0, low - max_down)
|
|
118
|
+
top = a + int(np.argmax(y[a : low + 1]))
|
|
119
|
+
drop = y[top] - y[low]
|
|
120
|
+
if y[low] < 0.35 and y[top] > 1.2 and drop > 1.0:
|
|
121
|
+
lo_ok = (low == T - 1 or y[low] <= y[low + 1]) and y[low] <= y[low - 1]
|
|
122
|
+
if lo_ok:
|
|
123
|
+
cands.append((float(drop), top, low))
|
|
124
|
+
best = {}
|
|
125
|
+
for d, t, l in cands:
|
|
126
|
+
if t not in best or d > best[t][0]:
|
|
127
|
+
best[t] = (d, t, l)
|
|
128
|
+
return sorted(best.values(), reverse=True)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def downswing(F, max_down=60):
|
|
132
|
+
"""(top, low) of the main swing: highest hands within `max_down` frames before the lowest point."""
|
|
133
|
+
sw = find_swings(F, max_down)
|
|
134
|
+
y = F["hand_y"]
|
|
135
|
+
if sw:
|
|
136
|
+
_, top, low = sw[0]
|
|
137
|
+
else:
|
|
138
|
+
pk = int(np.argmax(F["hand_speed"]))
|
|
139
|
+
top = int(np.argmax(y[: pk + 1]))
|
|
140
|
+
low = top + int(np.argmin(y[top : top + max_down]))
|
|
141
|
+
a = max(0, low - max_down)
|
|
142
|
+
top = a + int(np.argmax(y[a : low + 1]))
|
|
143
|
+
low = top + int(np.argmin(y[top : top + max_down]))
|
|
144
|
+
return top, low
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _check_pose(track):
|
|
148
|
+
lm = np.asarray(track["lm"])
|
|
149
|
+
if lm.ndim != 3 or len(lm) < 10:
|
|
150
|
+
raise ValueError("track too short to analyse (need at least 10 frames)")
|
|
151
|
+
seen = ~np.isnan(lm[:, 11, 0])
|
|
152
|
+
if seen.mean() < MIN_POSE_COVERAGE:
|
|
153
|
+
raise ValueError(f"golfer detected in only {seen.mean():.0%} of frames; film the whole body from down the line")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def decide_capture_fps(track, capture_fps=None, stored_fps=None):
|
|
157
|
+
"""(capture_fps, source) for a track: explicit override, high-fps container, or inferred."""
|
|
158
|
+
stored = float(stored_fps or track.get("fps", 30.0) or 30.0)
|
|
159
|
+
if capture_fps:
|
|
160
|
+
return int(capture_fps), "override"
|
|
161
|
+
F, _ = clip_features(track["lm"], track["size"])
|
|
162
|
+
top, low = downswing(F)
|
|
163
|
+
fps = classify_capture_fps(low - top, stored)
|
|
164
|
+
return fps, ("container" if stored >= 100 else "downswing-length")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ---------------------------------------------------------------------------------------------- analysis
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def analyze_track(track, params=None, capture_fps=None, stored_fps=None):
|
|
171
|
+
"""Analyse one swing. `track` needs lm (T,33,4), size (W,H), club (T,5); optional fps (stored)."""
|
|
172
|
+
_check_pose(track)
|
|
173
|
+
P = params or load_default_params()
|
|
174
|
+
stored = float(stored_fps or track.get("fps", 30.0) or 30.0)
|
|
175
|
+
F, T0 = clip_features(track["lm"], track["size"])
|
|
176
|
+
top0, low0 = downswing(F)
|
|
177
|
+
if capture_fps:
|
|
178
|
+
fps, fps_source = int(capture_fps), "override"
|
|
179
|
+
else:
|
|
180
|
+
fps = classify_capture_fps(low0 - top0, stored)
|
|
181
|
+
fps_source = "container" if stored >= 100 else "downswing-length"
|
|
182
|
+
if fps < 100: # real-time footage: lighter smoothing so 1-frame events survive
|
|
183
|
+
F, T0 = clip_features(track["lm"], track["size"], win=5)
|
|
184
|
+
htop, _ = downswing(F)
|
|
185
|
+
elif fps > 120: # 240 fps: the downswing is longer than the 120 fps search window
|
|
186
|
+
htop, _ = downswing(F, max_down=int(60 * fps / 120))
|
|
187
|
+
else:
|
|
188
|
+
htop = top0
|
|
189
|
+
k = fps / 120.0
|
|
190
|
+
pm = {key: (v * k if ("bias" in key) else v) for key, v in P.items()}
|
|
191
|
+
y = F["hand_y"]
|
|
192
|
+
T = len(y)
|
|
193
|
+
ev, cue, conf = {}, {}, {}
|
|
194
|
+
|
|
195
|
+
# --- P7 impact: lowest hands after the top (sub-frame parabola), nudged by the fitted bias
|
|
196
|
+
win = max(4, int(60 * k))
|
|
197
|
+
low = htop + int(np.argmin(y[htop : htop + win]))
|
|
198
|
+
seg = y[max(low - 1, 0) : low + 2]
|
|
199
|
+
sub = 0.0
|
|
200
|
+
if len(seg) == 3:
|
|
201
|
+
den = seg[0] - 2 * seg[1] + seg[2]
|
|
202
|
+
if den > 1e-9:
|
|
203
|
+
sub = 0.5 * (seg[0] - seg[2]) / den
|
|
204
|
+
ev["P7"] = low + sub + pm["p7_bias"]
|
|
205
|
+
cue["P7"] = "hands lowest point"
|
|
206
|
+
conf["P7"] = 0.9
|
|
207
|
+
|
|
208
|
+
# --- P4 top: middle of the plateau of highest hands, plus the club's own lag (fitted)
|
|
209
|
+
wtop = int(40 * k) + 1
|
|
210
|
+
seg_idx = np.arange(max(0, htop - wtop), min(T, htop + wtop))
|
|
211
|
+
plateau = seg_idx[y[seg_idx] >= y[htop] - pm["p4_plateau"]]
|
|
212
|
+
ev["P4"] = float(plateau.mean()) + pm["p4_bias"]
|
|
213
|
+
cue["P4"] = "middle of the pause at the top"
|
|
214
|
+
conf["P4"] = 0.8
|
|
215
|
+
|
|
216
|
+
def hc(name, a, b, direction, last=False):
|
|
217
|
+
return crossing(y, a, b, pm["thr_" + name], direction, last)
|
|
218
|
+
|
|
219
|
+
W_, H_ = track["size"]
|
|
220
|
+
Pp = np.asarray(track["lm"])[:, :, :2].astype(float) * [W_, H_]
|
|
221
|
+
sw = 9 if fps >= 100 else 5
|
|
222
|
+
lead_rel = (smooth(Pp[:, 11, 1], sw) - smooth(Pp[:, 15, 1], sw)) / T0 # lead wrist above lead shoulder
|
|
223
|
+
trail_rel = (smooth(Pp[:, 12, 1], sw) - smooth(Pp[:, 16, 1], sw)) / T0
|
|
224
|
+
|
|
225
|
+
# --- P5: hands drop through lead-arm-parallel height; P3: lead wrist reaches lead-shoulder height
|
|
226
|
+
p5 = hc("P5", htop, low + 1, -1)
|
|
227
|
+
ev["P5"] = (p5 if p5 is not None else (htop + low) / 2) + pm.get("bias_P5", 0)
|
|
228
|
+
cue["P5"] = "hands drop through lead-arm-parallel height"
|
|
229
|
+
conf["P5"] = 0.85
|
|
230
|
+
p3 = crossing(lead_rel, 0, htop + 1, pm["thr_P3_lead"], +1, last=True)
|
|
231
|
+
ev["P3"] = (p3 if p3 is not None else htop - 30 * k) + pm.get("bias_P3", 0)
|
|
232
|
+
cue["P3"] = "lead wrist rises to lead-shoulder height"
|
|
233
|
+
conf["P3"] = 0.75
|
|
234
|
+
|
|
235
|
+
# --- P2 / P6 / P8: the clubhead passes the height of the hands (shaft parallel to the ground).
|
|
236
|
+
# From down the line the shaft can be end-on and invisible for a few frames, so short gaps in the
|
|
237
|
+
# clubhead track are bridged linearly. Fallback: hand height crossing.
|
|
238
|
+
tip = np.asarray(track["club"])[:, 4].astype(float).copy()
|
|
239
|
+
reach = np.asarray(track["club"])[:, 2].astype(float)
|
|
240
|
+
tip[~(reach >= pm["tip_min_reach"])] = np.nan # short rays are hands/sleeves, not the clubhead
|
|
241
|
+
good = ~np.isnan(tip)
|
|
242
|
+
gi = np.nonzero(good)[0]
|
|
243
|
+
|
|
244
|
+
def tip_cross(center, direction, half):
|
|
245
|
+
if good.sum() < 10:
|
|
246
|
+
return None
|
|
247
|
+
a = max(1, int(center - half))
|
|
248
|
+
b = min(T - 1, int(center + half))
|
|
249
|
+
best = None
|
|
250
|
+
for u, v in zip(gi[:-1], gi[1:]):
|
|
251
|
+
if v < a or u > b or v - u > max(2, int(10 * k)):
|
|
252
|
+
continue
|
|
253
|
+
t0, t1 = tip[u], tip[v]
|
|
254
|
+
if (direction > 0 and t0 < 0 <= t1) or (direction < 0 and t0 > 0 >= t1):
|
|
255
|
+
# require a clear sign on both sides nearby
|
|
256
|
+
lo = tip[max(0, u - int(6 * k) - 1) : u + 1]
|
|
257
|
+
hi = tip[v : v + int(6 * k) + 2]
|
|
258
|
+
lo = lo[~np.isnan(lo)]
|
|
259
|
+
hi = hi[~np.isnan(hi)]
|
|
260
|
+
if len(lo) == 0 or len(hi) == 0:
|
|
261
|
+
continue
|
|
262
|
+
if direction > 0 and not (lo.min() < -0.2 and hi.max() > 0.2):
|
|
263
|
+
continue
|
|
264
|
+
if direction < 0 and not (lo.max() > 0.2 and hi.min() < -0.2):
|
|
265
|
+
continue
|
|
266
|
+
x = u + (0 - t0) / (t1 - t0) * (v - u)
|
|
267
|
+
if best is None or abs(x - center) < abs(best[0] - center):
|
|
268
|
+
best = (x, v - u - 1)
|
|
269
|
+
return best
|
|
270
|
+
|
|
271
|
+
for name, direction, hlo, hhi, hdir, fallback in (
|
|
272
|
+
("P2", +1, 0, ev["P3"] + 1, +1, ev["P3"] - 15 * k),
|
|
273
|
+
("P6", -1, ev["P5"], low + 1, -1, (ev["P5"] + ev["P7"]) / 2),
|
|
274
|
+
("P8", +1, low, low + int(60 * k) + 1, +1, ev["P7"] + 8 * k),
|
|
275
|
+
):
|
|
276
|
+
h = hc(name, hlo, hhi, hdir, last=(name == "P2"))
|
|
277
|
+
h = (h if h is not None else fallback) + pm.get("bias_" + name, 0)
|
|
278
|
+
c = tip_cross(h, direction, pm["tip_win"] * k)
|
|
279
|
+
if c is not None:
|
|
280
|
+
ev[name] = c[0] + pm["tip_bias_" + name]
|
|
281
|
+
cue[name] = "clubhead passes hand height" + (" (shaft end-on, bridged)" if c[1] > 0 else "")
|
|
282
|
+
conf[name] = 0.85 if c[1] <= 2 else 0.75
|
|
283
|
+
else:
|
|
284
|
+
ev[name] = h
|
|
285
|
+
cue[name] = "hand height (club not trackable)"
|
|
286
|
+
conf[name] = 0.6
|
|
287
|
+
|
|
288
|
+
# --- P9: trail arm parallel. From down the line the arms are hidden behind the body here, so the
|
|
289
|
+
# cue is the club: with the trail arm parallel and the wrists re-hinged the shaft points well up,
|
|
290
|
+
# clubhead about thr_P9_tip torso lengths above the hands. Fallback: trail wrist height.
|
|
291
|
+
p9 = None
|
|
292
|
+
a9, b9 = ev["P8"] + 1, ev["P8"] + int(50 * k) + 1
|
|
293
|
+
for u, v in zip(gi[:-1], gi[1:]):
|
|
294
|
+
if v < a9 or u > b9 or v - u > max(2, int(10 * k)):
|
|
295
|
+
continue
|
|
296
|
+
if tip[u] < pm["thr_P9_tip"] <= tip[v]:
|
|
297
|
+
p9 = u + (pm["thr_P9_tip"] - tip[u]) / (tip[v] - tip[u]) * (v - u)
|
|
298
|
+
break
|
|
299
|
+
if p9 is not None:
|
|
300
|
+
ev["P9"] = p9 + pm.get("tip_bias_P9", 0)
|
|
301
|
+
cue["P9"] = "shaft points up in the follow-through"
|
|
302
|
+
conf["P9"] = 0.75
|
|
303
|
+
else:
|
|
304
|
+
p9 = crossing(trail_rel, ev["P8"], ev["P8"] + int(60 * k) + 1, pm["thr_P9_trail"], +1)
|
|
305
|
+
ev["P9"] = (p9 if p9 is not None else ev["P8"] + 14 * k) + pm.get("bias_P9", 0)
|
|
306
|
+
cue["P9"] = "trail wrist rises to trail-shoulder height"
|
|
307
|
+
conf["P9"] = 0.6
|
|
308
|
+
|
|
309
|
+
# --- P1 takeaway onset: walk back from P2 while the hands are still moving toward their P2 spot;
|
|
310
|
+
# address is where that distance stops growing (hands at rest).
|
|
311
|
+
hx, hy = F["hand_x"], F["hand_y"]
|
|
312
|
+
i2 = int(round(min(max(ev["P2"], 0), T - 1)))
|
|
313
|
+
d = np.hypot(hx - hx[i2], hy - hy[i2])
|
|
314
|
+
w = max(2, int(pm["p1_win"] * k))
|
|
315
|
+
p1 = None
|
|
316
|
+
for t in range(i2 - w, w, -1):
|
|
317
|
+
if d[t - w] - d[t] < pm["p1_eps"]:
|
|
318
|
+
p1 = t
|
|
319
|
+
break
|
|
320
|
+
left_censored = p1 is None or p1 <= w + 1
|
|
321
|
+
if p1 is None:
|
|
322
|
+
p1 = 0
|
|
323
|
+
ev["P1"] = p1 + pm["p1_bias"]
|
|
324
|
+
cue["P1"] = "hands at rest just before the takeaway"
|
|
325
|
+
conf["P1"] = 0.7
|
|
326
|
+
|
|
327
|
+
# --- P10 finish: hands come to rest after the follow-through
|
|
328
|
+
sp = F["hand_speed"]
|
|
329
|
+
peak = float(np.max(sp))
|
|
330
|
+
start = int(ev["P9"] + 10 * k)
|
|
331
|
+
hold = max(3, int(pm["p10_hold"] * k))
|
|
332
|
+
p10 = None
|
|
333
|
+
for i in range(start, T - hold):
|
|
334
|
+
if np.all(sp[i : i + hold] < pm["p10_speed"] * peak):
|
|
335
|
+
p10 = i
|
|
336
|
+
break
|
|
337
|
+
right_censored = p10 is None
|
|
338
|
+
ev["P10"] = (p10 if p10 is not None else T - 1) + pm["p10_bias"]
|
|
339
|
+
cue["P10"] = "body and club come to rest" if p10 is not None else "clip ends before the finish settles"
|
|
340
|
+
conf["P10"] = 0.7 if p10 is not None else 0.4
|
|
341
|
+
|
|
342
|
+
# --- order + clamp
|
|
343
|
+
events = []
|
|
344
|
+
prev = -1
|
|
345
|
+
for name in SHORT:
|
|
346
|
+
f = int(round(min(max(ev[name], 0), T - 1)))
|
|
347
|
+
f = max(f, prev + (1 if prev >= 0 else 0))
|
|
348
|
+
f = min(f, T - 1)
|
|
349
|
+
prev = f
|
|
350
|
+
events.append(
|
|
351
|
+
{
|
|
352
|
+
"p": name,
|
|
353
|
+
"name": LABELS[name],
|
|
354
|
+
"frame": f,
|
|
355
|
+
"time_s": frame_time(f, fps),
|
|
356
|
+
"video_time_s": frame_time(f, stored),
|
|
357
|
+
"cue": cue[name],
|
|
358
|
+
"confidence": round(conf[name], 2),
|
|
359
|
+
}
|
|
360
|
+
)
|
|
361
|
+
return {
|
|
362
|
+
"capture_fps": fps,
|
|
363
|
+
"capture_fps_source": fps_source,
|
|
364
|
+
"stored_fps": stored,
|
|
365
|
+
"slowmo_factor": slowmo_factor(fps, stored),
|
|
366
|
+
"mode": "slow-motion" if fps > 1.5 * stored else "real-time",
|
|
367
|
+
"frames_total": T,
|
|
368
|
+
"events": events,
|
|
369
|
+
"tempo": tempo([e["frame"] for e in events], fps),
|
|
370
|
+
"flags": {"address_before_clip": bool(left_censored), "finish_after_clip": bool(right_censored)},
|
|
371
|
+
"torso_px": round(float(T0), 1),
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def tempo(frames, fps):
|
|
376
|
+
"""Tempo from the ten event frames, in real seconds (ratio = backswing / downswing)."""
|
|
377
|
+
|
|
378
|
+
def sec(a, b):
|
|
379
|
+
return round((frames[b] - frames[a]) / fps, 4)
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
"backswing_s": sec(0, 3), # P1 -> P4
|
|
383
|
+
"downswing_s": sec(3, 6), # P4 -> P7
|
|
384
|
+
"ratio": round((frames[3] - frames[0]) / max(1, frames[6] - frames[3]), 2),
|
|
385
|
+
"takeaway_s": sec(0, 1), # P1 -> P2
|
|
386
|
+
"transition_s": sec(3, 4), # P4 -> P5
|
|
387
|
+
"delivery_s": sec(4, 6), # P5 -> P7
|
|
388
|
+
"release_s": sec(6, 9), # P7 -> P10
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ---------------------------------------------------------------------------------------------- videos
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def select_swings(F, fps, max_down=60):
|
|
396
|
+
"""Separate swings in one track: [(top, low)] sorted in time.
|
|
397
|
+
|
|
398
|
+
Keeps the biggest candidate, plus every other candidate whose drop is fast (a real downswing) and whose
|
|
399
|
+
lowest point is at least SWING_MIN_GAP_S real seconds from every swing already kept. This rejects the
|
|
400
|
+
hands coming down after the finish, which is a slow drop right after a real swing.
|
|
401
|
+
"""
|
|
402
|
+
cands = find_swings(F, max_down)
|
|
403
|
+
kept = []
|
|
404
|
+
for _drop, top, low in cands:
|
|
405
|
+
if kept:
|
|
406
|
+
if (low - top) / fps > SWING_MAX_DOWN_S:
|
|
407
|
+
continue
|
|
408
|
+
if any(abs(low - l) < SWING_MIN_GAP_S * fps for _, l in kept):
|
|
409
|
+
continue
|
|
410
|
+
kept.append((top, low))
|
|
411
|
+
return sorted(kept, key=lambda tl: tl[1])
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _slice_track(track, a, b):
|
|
415
|
+
out = dict(track)
|
|
416
|
+
out["lm"] = np.asarray(track["lm"])[a:b]
|
|
417
|
+
out["club"] = np.asarray(track["club"])[a:b]
|
|
418
|
+
return out
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def analyze_video_track(track, params=None, capture_fps=None, stored_fps=None):
|
|
422
|
+
"""Analyse every swing in a track. Returns (capture_fps, fps_source, [swing results])."""
|
|
423
|
+
_check_pose(track)
|
|
424
|
+
stored = float(stored_fps or track.get("fps", 30.0) or 30.0)
|
|
425
|
+
fps, source = decide_capture_fps(track, capture_fps, stored)
|
|
426
|
+
T = len(track["lm"])
|
|
427
|
+
F, _ = clip_features(track["lm"], track["size"], win=9 if fps >= 100 else 5)
|
|
428
|
+
swings = select_swings(F, fps, max_down=max(60, int(60 * fps / 120)))
|
|
429
|
+
if len(swings) <= 1:
|
|
430
|
+
r = analyze_track(track, params, capture_fps=fps, stored_fps=stored)
|
|
431
|
+
r["capture_fps_source"] = source
|
|
432
|
+
r["frame_range"] = [0, T - 1]
|
|
433
|
+
return fps, source, [r]
|
|
434
|
+
results = []
|
|
435
|
+
pad = int(SLICE_PAD_S * fps)
|
|
436
|
+
for i, (top, low) in enumerate(swings):
|
|
437
|
+
lo_bound = 0 if i == 0 else (swings[i - 1][1] + top) // 2
|
|
438
|
+
hi_bound = T if i == len(swings) - 1 else (low + swings[i + 1][0]) // 2
|
|
439
|
+
a = max(lo_bound, low - pad)
|
|
440
|
+
b = min(hi_bound, low + pad)
|
|
441
|
+
try:
|
|
442
|
+
r = analyze_track(_slice_track(track, a, b), params, capture_fps=fps, stored_fps=stored)
|
|
443
|
+
except ValueError:
|
|
444
|
+
continue
|
|
445
|
+
r["capture_fps_source"] = source
|
|
446
|
+
for e in r["events"]:
|
|
447
|
+
e["frame"] += a
|
|
448
|
+
e["time_s"] = frame_time(e["frame"], fps)
|
|
449
|
+
e["video_time_s"] = frame_time(e["frame"], stored)
|
|
450
|
+
r["frame_range"] = [a, b - 1]
|
|
451
|
+
results.append(r)
|
|
452
|
+
return fps, source, results
|