# CS-14: The arc of a shot or a throw

Data-Driven Athletics tutorial · Week 10 · Chapter 10 · about 60 min · workflow steps: Gather, Statistics, Visualize, Cleanse, Features

Web page: https://apopt.com/course/tutorials/cs14-throw-arc/ · Data: https://apopt.com/data/tutorials/cs14-throw-arc/

## 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

- `clean/ball_tennis1.csv`: the most confident ball detection and a repeated-picture flag for each of the 137 frames of a tennis serve toss, written by the Step 1 cell Made from the course example clip `tennis1_60fps.mp4`, which is not published because it shows a person.
- `clean/ball_hoops1.csv`: the same for the 123 frames of a basketball jump shot Made from the course example clip `hoops1_60fps.mp4`, not published for the same reason.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| frame | frame number in the file from 0 | count | 0–136 (tennis), 0–122 (basketball) | none |
| repeat | the picture is the same as the one before (mean change under 0.3 gray levels on a 108 × 192 copy) | true/false |  | none |
| x, y | center of the ball's box; y grows downward | pixels | 0–1080, 0–1920 | empty when no ball was found |
| w, h | width and height of the ball's box | pixels | 20–240 | empty when no ball was found |
| conf | the detector's confidence for the ball | 0 to 1 | 0.1–0.9 | empty 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 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.

*Predict first:* Both file names say 60 fps. What frame rate do you expect the file headers to give?

```python
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())}")
```

Output:

```
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.

```python
import numpy as np
import pandas as pd

def longest_run(t):
    seen = t[t["x"].notna()]
    run = (seen["frame"].diff() > 3).cumsum()
    return seen[run == run.value_counts().idxmax()]

tabs = {c: pd.read_csv(f"clean/ball_{c}.csv") for c in ["hoops1", "tennis1"]}
for c, t in tabs.items():
    seen = t[t["x"].notna()]
    runs = seen.groupby((seen["frame"].diff() > 3).cumsum())["frame"].agg(["min", "max"])
    edge = seen[seen["y"] - seen["h"] / 2 <= 1]["frame"].tolist()          # box touches the top
    print(f"{c}: ball in {len(seen)} of {len(t)} frames; runs {[f'{a}-{b}' for a, b in runs.values]}; "
          f"size median {np.median((seen['w'] + seen['h']) / 2):.0f} px; touches the top edge at {edge}; "
          f"repeated pictures {int(t['repeat'].sum())}")
```

Output:

```
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.

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 2, figsize=(9, 3.4), sharey=True)
for a, (c, t) in zip(ax, tabs.items()):
    a.plot(t["frame"], t["y"], "o", ms=3, color="black", label="ball center")
    rep = t[t["repeat"] & t["y"].notna()]
    a.plot(rep["frame"], rep["y"], "s", ms=8, mfc="none", color="gray", label="repeated picture")
    a.axhline(0, color="gray", lw=1, ls="--")
    a.set(title=c, xlabel="frame in the file")
ax[0].set(ylabel="y (px, up is up)"); ax[0].invert_yaxis(); ax[1].legend(fontsize=8)
plt.tight_layout()
```

![Two 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.](https://apopt.com/course/tutorials/cs14-throw-arc/c05-1.png)

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.

```python
toss = longest_run(tabs["tennis1"])
distinct = (~tabs["tennis1"]["repeat"]).cumsum() - 1           # index of each distinct picture
toss = toss.assign(k=distinct[toss.index].to_numpy())
log = {"detections in the run": len(toss), "repeated pictures dropped": int(toss["repeat"].sum())}
toss = toss[~toss["repeat"]]

def fit(t, clock):
    p = np.polyfit(t[clock], t["y"], 2)
    return p, t["y"] - np.polyval(p, t[clock])

for clock in ["frame", "k"]:
    _, res = fit(toss, clock)
    print(f"clock = {clock:5s}: residual SD {res.std():.1f} px, largest {res.abs().max():.1f} px "
          f"at frame {int(toss.loc[res.abs().idxmax(), 'frame'])}")
print(log)
```

Output:

```
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.

```python
before = toss[toss["frame"] < 69]
py, res = fit(before, "k")
px = np.polyfit(before["k"], before["x"], 1)
print(f"fit on frames {before['frame'].min()}-{before['frame'].max()} ({len(before)} distinct pictures): "
      f"residual SD {res.std():.1f} px, largest {res.abs().max():.1f} px "
      f"(with file frames as the clock: {fit(before, 'frame')[1].std():.1f} px)")
print(f"curvature {2 * py[0]:.3f} px per picture²; x {px[0]:+.2f} px per picture; "
      f"apex at picture {-py[1] / (2 * py[0]):.1f}")
before.to_csv("clean/toss_clean.csv", index=False)
```

Output:

```
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.

*Predict first:* How high above the first tracked point does the ball rise, in meters?

```python
G = 9.80665
size_px = np.median((before["w"] + before["h"]) / 2)
k0, k_apex = before["k"].iloc[0], -py[1] / (2 * py[0])
rise_px = np.polyval(py, k0) - np.polyval(py, k_apex)           # image y grows downward
for label, d in (("small ball 6.54 cm", 0.0654), ("6.70 cm", 0.067), ("large ball 6.86 cm", 0.0686)):
    m_per_px = d / size_px
    rise = rise_px * m_per_px
    v_up = np.sqrt(2 * G * rise)
    v_side = v_up * abs(px[0]) / abs(2 * py[0] * (k_apex - k0))  # same ratio as the path's slope
    rate = np.sqrt(G / (2 * py[0] * m_per_px))                  # pictures per real second
    print(f"{label}: rise {rise:.2f} m, speed {np.hypot(v_up, v_side):.2f} m/s at "
          f"{np.degrees(np.arctan2(v_up, v_side)):.1f}° above horizontal; clock {rate:.1f} pictures/s")
print(f"the same speed computed with the file's 30 or 60 fps would be off by a factor "
      f"{30 / rate:.2f} or {60 / rate:.2f}")
```

Output:

```
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.

```python
m_per_px = 0.067 / size_px
rate = np.sqrt(G / (2 * py[0] * m_per_px))
t = (before["k"] - k0) / rate
h = (np.polyval(py, k0) - before["y"]) * m_per_px
kk = np.linspace(k0, before["k"].iloc[-1], 100)
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.plot(t, h, "o", ms=4, color="black", label="ball, cleaned detections")
ax.plot((kk - k0) / rate, (np.polyval(py, k0) - np.polyval(py, kk)) * m_per_px, "-", color="gray",
        label=f"parabola, g = 9.81 m/s² at {rate:.1f} pictures/s")
ax.set(xlabel="time from the first tracked point (s)", ylabel="height above it (m)")
ax.legend(fontsize=8, loc="lower center")
plt.tight_layout()
print(f"apex {h.max():.2f} m at {t[h.idxmax()]:.2f} s; tracked for {t.iloc[-1]:.2f} s")
```

Output:

```
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.](https://apopt.com/course/tutorials/cs14-throw-arc/c13-1.png)

## 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.

## 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`.

## 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.

## 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](https://apmonitor.com/dde/index.php/Main/ObjectDetection) 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).

## 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.
- **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.
- **Retest:** Repeat the ten tosses next week and compare the median height and its spread.

## 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.

Deliverables:

- the ball tables and a notebook that runs top to bottom from them
- a table of the ten tosses or shots with the median and spread
- a five-line action card

## References

- International Tennis Federation. *ITF Rules of Tennis 2026*, Appendix I, The Ball. [PDF](https://www.world.tennis/media/7221/2026-rules-of-tennis-english.pdf).
- Chapter 10 of *Data-Driven Athletics*: Balls in Flight; Many Trials.
- Chapter 8 of *Data-Driven Athletics*: Two clocks: the stored rate and the capture rate.

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
