apopt.comCBE 493R Data-Driven Athletics

Course / Tutorials / Week 10 / CS-14

Case study CS-14 · Week 10 · about 60 min · Core

The arc of a shot or a throw

Track a ball frame by frame in two phone clips, find which one holds an arc, clean its clock, and measure a tennis toss's height, speed and angle with gravity and the ball's size as the only references.

  1. 1Gather (used)
  2. 2Statistics (used)
  3. 3Visualize (used)
  4. 4Cleanse (used)
  5. 5Features (used)
  6. 6Balance
  7. 7Scale
  8. 8Split
  9. 9Deploy
  1. Ask (this week)
  2. Collect (this week)
  3. Check (this week)
  4. Interpret (this week)
  5. Coach (this week)
  6. Reassess

6 of 7 cells run in this page. The rest need a model that does not run in the browser: run them in the notebook on your computer or in Colab (File → Upload notebook); their output from the course build is shown, and the files they write are published so the later cells still run here. Helpful first: Q-28 Height from flight time, with one frame of error, Q-29 Median and spread of ten trials, Q-30 Track a ball and fit its path.

The decision

A server wants to toss to the same height every time, and a coach wants a number for "the same height". Before practising against a number, decide which clips can give one at all, and which of the numbers you can read from a toss survive a clip whose clock is not what it says.

Predict first

A server tosses the ball for a serve. How high above the point where it leaves the hand region do you expect it to rise, in meters, and how fast is it moving there?

The raw data

Data dictionary
FieldMeaningUnitRangeMissing
frameframe number in the file from 0count0–136 (tennis), 0–122 (basketball)none
repeatthe picture is the same as the one before (mean change under 0.3 gray levels on a 108 × 192 copy)true/falsenone
x, ycenter of the ball's box; y grows downwardpixels0–1080, 0–1920empty when no ball was found
w, hwidth and height of the ball's boxpixels20–240empty when no ball was found
confthe detector's confidence for the ball0 to 10.1–0.9empty when no ball was found

What is wrong with it: both clips say 60 frames per second in their names and 30 in their headers; 26 of the tennis clip's 137 pictures repeat the one before, and around frame 69 a picture is missing and filled with copies. In the basketball clip the ball touches the top of the picture as it leaves the hands, so the shot's flight is not in the clip at all. The detector also finds a few objects that are not the ball in flight, and finds the ball in the hand before the toss at low confidence.

Step by step

Step 1 · Gather: ball positions from two clips

Two of the course's example clips show a ball leaving a hand: a basketball jump shot (hoops1_60fps.mp4) and a tennis serve toss (tennis1_60fps.mp4), both filmed on a phone in portrait. The cell below runs the YOLO detector on every frame of each and keeps the most confident "sports ball" (the same class the basketball app tracks). It also flags each frame whose picture is the same as the one before it, a check Chapter 8 recommends for every clip. It needs ultralytics and opencv, so it runs on your computer or in Colab. Both clips show a person, so they stay there: only the ball tables are published. Without the clips, start at Step 2, which reads the published tables.

Step 1 · Track the ball and flag repeated pictures

Runs in the notebook (needs a model that does not run in the browser). Output from the course build:

import os
import cv2
import numpy as np
import pandas as pd
from ultralytics import YOLO

model = YOLO("yolo26n.pt")                                      # COCO class 32 is "sports ball"
os.makedirs("clean", exist_ok=True)
for clip in ["hoops1", "tennis1"]:
    cap, rows, prev = cv2.VideoCapture(f"{clip}_60fps.mp4"), [], None
    print(f"{clip}: header {cap.get(cv2.CAP_PROP_FPS):.0f} fps, {int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))} x "
          f"{int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))} px", end="; ")
    while (got := cap.read())[0]:
        small = cv2.resize(got[1], (108, 192)).astype(float)
        repeat = prev is not None and np.abs(small - prev).mean() < 0.3   # same picture again
        r = model(got[1], verbose=False, device="cpu", classes=[32], conf=0.1)[0]
        ball = [np.nan] * 5
        if len(r.boxes):
            x1, y1, x2, y2 = r.boxes.xyxy[int(r.boxes.conf.argmax())].tolist()
            ball = [(x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1, float(r.boxes.conf.max())]
        rows.append([len(rows), repeat] + ball)
        prev = small
    t = pd.DataFrame(rows, columns=["frame", "repeat", "x", "y", "w", "h", "conf"]).round(2)
    t.to_csv(f"clean/ball_{clip}.csv", index=False)
    print(f"{len(t)} frames; ball in {t['x'].notna().sum()}; repeated pictures: {int(t['repeat'].sum())}")
hoops1: header 30 fps, 1080 x 1920 px; 123 frames; ball in 49; repeated pictures: 2
tennis1: header 30 fps, 1080 x 1920 px; 137 frames; ball in 50; repeated pictures: 26

Step 2 · Statistics: what is in each table?

From here on everything runs in this page from the two published tables. Profile each one: the runs of frames with a ball (gaps of up to three frames allowed), the ball's size in pixels, whether the ball's box touches the top edge of the picture, and how often a picture repeats.

PythonStep 2 · Profile the two ball tables

Show the expected result without running
hoops1: ball in 49 of 123 frames; runs ['2-31', '35-49', '79-85']; size median 194 px; touches the top edge at [47, 48]; repeated pictures 2
tennis1: ball in 50 of 137 frames; runs ['16-16', '20-20', '28-77']; size median 28 px; touches the top edge at []; repeated pictures 26

Step 3 · Visualize: is there an arc to fit?

Plot the ball's height in the picture against frame number for both clips, with the repeated pictures marked.

PythonStep 3 · Ball height in both clips

Show the expected result without runningTwo panels of ball image height against frame. Basketball: the ball comes in from the top, drops to the hands, then rises and leaves the top of the picture near frame 48. Tennis: the ball rises from the hand, peaks near frame 57 and falls, a full arc, with repeated pictures marked as open squares.

The basketball clip has no arc to fit. The ball arrives as a pass (frames 2 to 31), sits in the hands, rises with them (35 to 49) and touches the top of the picture (the dashed line) at frames 47 and 48, about when it leaves the hands; the few later detections are not the ball in flight. A portrait phone close to the shooter films the shot, not the ball's flight. That is the first finding, and it is about filming: to measure an arc, the whole flight has to be in the frame. The tennis toss has a full arc, up and down, so the rest of this study uses it. A toss is a throw, and its height and consistency are what a server practises.

Step 4 · Cleanse: one clock for the toss

Q-30 fitted a parabola to this toss against the file's frame number and found that neither 30 nor 60 frames per second gave gravity back. The repeated pictures are why. A file that shows the same picture twice has not moved forward in real time between them, so a frame number is not a clock. The rules: keep the longest run of the toss; drop the repeated pictures; count time in distinct pictures. Then compare the fit with both clocks.

PythonStep 4 · File frames against distinct pictures as the clock

Show the expected result without running
clock = frame: residual SD 8.3 px, largest 37.2 px at frame 69
clock = k    : residual SD 10.1 px, largest 25.8 px at frame 68
{'detections in the run': 48, 'repeated pictures dropped': 9}

Neither clock fits the whole run: with either one, the worst misfit sits at frames 68 and 69. Look at the table there. Between frames 68 and 69 the ball moves about twice its usual step, and frames 69, 70 and 71 hold the same picture: the file dropped a picture and filled the gap with copies. Times across that break are unknown, so the last rule is to fit only the part before it, with distinct pictures as the clock.

PythonStep 4 · Fit before the break, and check it

Show the expected result without running
fit on frames 28-68 (33 distinct pictures): residual SD 1.5 px, largest 4.9 px (with file frames as the clock: 5.2 px)
curvature 2.061 px per picture²; x -2.17 px per picture; apex at picture 46.2

Before the break, with distinct pictures as the clock, the residual SD falls to 1.5 pixels, small next to a 28-pixel ball: the path is now a clean parabola, good enough to measure from. Fitted against file frames, the same points leave 5.2 pixels, and Q-30's 9.3 also included the break.

Step 5 · Features: gravity gives the clock, the ball gives the scale

Two things are known without the video: the ball is 6.54 to 6.86 cm across (ITF Rules of Tennis, Appendix I) and gravity is 9.81 m/s². The ball's size turns pixels into meters. Gravity then turns pictures into seconds, because the curvature must equal g. And some quantities need no clock at all: the height of the toss, and the angle of the path, are pure geometry. The speed at the first tracked point follows from the height alone, v_up = √(2 g h), the flight-height relation of Section 3.4 run backward.

PythonStep 5 · Release speed, angle and height, with no clock from the file

Type a prediction to enable Run.

Show the expected result without running
small ball 6.54 cm: rise 1.43 m, speed 5.31 m/s at 87.5° above horizontal; clock 44.8 pictures/s
6.70 cm: rise 1.47 m, speed 5.37 m/s at 87.5° above horizontal; clock 44.2 pictures/s
large ball 6.86 cm: rise 1.51 m, speed 5.44 m/s at 87.5° above horizontal; clock 43.7 pictures/s
the same speed computed with the file's 30 or 60 fps would be off by a factor 0.69 or 1.37

From the first point where the detector found the ball, the toss rises 1.47 m, at 5.37 m/s, 87.5° above the horizontal: nearly straight up, drifting slightly sideways in the picture. The legal range of ball sizes moves the rise from 1.43 to 1.51 m and the speed from 5.31 to 5.44 m/s, a few percent. None of these numbers used the file's clock. The clock gravity finds, about 44 distinct pictures a real second, is the surprise: neither the header's 30 nor the name's 60. A speed worked out with 30 would be 31% too low, with 60 37% too high.

Two limits. The first tracked point is not the release: the hand lets go a little earlier and lower, so the true release speed is a little higher than 5.37 m/s. And one toss says nothing about consistency, or about good tosses against bad ones; that needs many tosses, filmed the same way (the challenge).

Finally, draw the toss as measured beside the parabola, in meters, with the real time from the clock that gravity found.

PythonThe toss in meters and seconds

Show the expected result without running
apex 1.47 m at 0.54 s; tracked for 0.75 s
The tossed ball's height above the first tracked point against time in seconds, from the cleaned detections, with the fitted parabola; the apex is 1.47 m up at 0.54 s.

How good is the number?

The fit: with distinct pictures as the clock and the frames before the break, the parabola leaves a residual SD of 1.5 pixels on a 28-pixel ball (5.2 pixels with file frames as the clock). The scale: legal tennis balls are 6.54 to 6.86 cm across (ITF Rules of Tennis, Appendix I), so the rise is 1.43 to 1.51 m and the speed 5.31 to 5.44 m/s; motion blur, which stretches the box along the path, would make the ball look larger and the toss smaller. The clock: gravity puts it at 43.7 to 44.8 distinct pictures a second; a speed computed with the header's 30 would be 31% low, with the name's 60 37% high. What is not measured: the first tracked point is not the release, so the true release speed is a little higher; one camera sees only the motion across the picture; and one toss gives no spread.

Action card

Action card
Finding
This toss rose 1.47 m above the first tracked point, at 5.37 m/s, nearly straight up.
Evidence
A clean parabola (1.5 px residual) scaled by the ball's legal size and timed by gravity; the file's own clock was wrong.
How sure
Moderate for this toss (±3% from the ball's size); nothing yet about consistency, with one toss.
Action
Film ten tosses from the same spot, phone still and the whole toss in the frame, and practise toward a smaller spread in toss height, not toward a target number.
Test again
Repeat the ten tosses next week and compare the median height and its spread.

Track it

One row per session: date, test=serve-toss, metric=toss_rise_median_m, value, unit=m, trial=10, and a second row for the spread (toss_rise_mad_m), with the phone and frame rate in device and the camera spot in protocol_version.

Open your athlete record

With your own data

Put your own clip next to the notebook as tennis1_60fps.mp4 (or change the name in Step 1), run Step 1, then the rest. Keep the clip on your computer; publish only the ball table.

Check the AI

Asked for "the toss speed from this clip", an assistant wrote:

> The ball's vertical speed between frames 28 and 29 is 50.5 px per frame. At 60 fps that is > 3,030 px/s, and with 410 px per meter, 7.4 m/s. A 7.4 m/s toss is very fast; the player > should toss more gently.

What is wrong with it?

It trusted the file name's 60 frames per second. Gravity says the clip holds about 44 distinct pictures a second, and some frames repeat, so a speed from two neighboring file frames is wrong by a third or more (and is zero across a repeated picture). The height-based speed, which needs no clock, is 5.37 m/s at the first tracked point. The advice also does not follow: the decision was about consistency, not speed.

Check yourself

  1. Why does the basketball clip give no shot arc?

  2. Why does the fit improve when time is counted in distinct pictures?

  3. The ball rises 1.47 m above the first tracked point. With g = 9.81 m/s², how fast was it going upward there?

    m/s

  4. Which of these needs the file's frame rate to be right?

0 of 4 answered · 0 right the first time

Challenge: Ten tosses, or ten shots, filmed for the arc

Film ten serve tosses (or ten jump shots from a side view far enough back that the whole flight is in the frame), phone still, at a frame rate you set and write down. Record by hand which ones you liked (or which shots went in).

  1. Track the ball in every clip with the Step 1 cell and check each for repeated pictures and gaps.
  2. Fit each flight, and check that gravity gives back your frame rate within a few percent; if it does not, find out why before going on.
  3. Compute the rise and speed of each toss (or release speed and angle of each shot) and report the median and the robust spread (1.4826 × MAD), as in Q-29.
  4. Compare good against bad tosses (or made against missed shots) with the probability of superiority and a bootstrap interval, as in Section 10.6, and say whether ten is enough.

Hand in

How it is judged

Hints

    The solution unlocks after you make an attempt. Comparing your own attempt with it is where the learning happens.

    The same method in another field

    Gravity as a free calibration is used whenever a camera measures motion: a dropped steel ball checks a high-speed camera's frame rate, and a falling droplet checks a lab's length scale. The Data-Driven Engineering page on object detection runs the same kind of detector.

    Acknowledgements

    Course example clips tennis1_60fps.mp4 and hoops1_60fps.mp4 (not published). Detection uses Ultralytics YOLO (AGPL-3.0).

    References

    Built 2026-11-30 with Python packages numpy 2.5.5, pandas 3.1.1, matplotlib 3.11.2, ultralytics 8.4.219, cv2 5.1.0. In the browser the same code runs on Pyodide, so the last digit can differ.