# Q-30: Track a ball and fit its path

Data-Driven Athletics tutorial · Week 10 · Chapter 10 · about 20 min · workflow steps: Gather, Features

Web page: https://apopt.com/course/tutorials/q30-ball-path/ · Data: https://apopt.com/data/tutorials/q30-ball-path/

## The decision

A player wants to know how high and how consistently they toss the ball on the serve. Before
measuring the toss, check that the clip's clock is right; the ball's own fall is the check.

## The raw data

- `clean/tennis1_ball.csv`: the ball's center, box size and confidence in each frame where the detector found it (50 rows), written by the first cell Made from the course example clip `tennis1_60fps.mp4` (1080 × 1920, 137 frames, header 30 frames per second), which is not published because it shows a person.

Once a ball leaves the hand it follows the projectile equations of Chapter 3: its horizontal
position changes at a steady rate and its vertical position follows a parabola set by gravity.
The apps find the ball as an object, the "sports ball" class of the YOLO detector, and track
its center frame by frame (Section 10.5). Here you do the same on a tennis serve toss from the
course's example clips, `tennis1_60fps.mp4`.

The first cell needs `ultralytics` and `opencv`, so it runs on your computer or in Colab. The
clip shows a person, so it stays there; only the table of ball positions is published.

```python
import os
import cv2
import pandas as pd
from ultralytics import YOLO

model = YOLO("yolo26n.pt")                      # COCO class 32 is "sports ball"
cap = cv2.VideoCapture("tennis1_60fps.mp4")
print(f"header: {cap.get(cv2.CAP_PROP_FPS):.0f} fps, {int(cap.get(cv2.CAP_PROP_FRAME_COUNT))} frames")
rows, i = [], 0
while True:
    ok, frame = cap.read()
    if not ok:
        break
    r = model(frame, verbose=False, device="cpu", classes=[32], conf=0.1)[0]
    if len(r.boxes):
        k = int(r.boxes.conf.argmax())              # the most confident ball
        x1, y1, x2, y2 = r.boxes.xyxy[k].tolist()
        rows.append([i, (x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1, float(r.boxes.conf[k])])
    i += 1
os.makedirs("clean", exist_ok=True)
track = pd.DataFrame(rows, columns=["frame", "x", "y", "w", "h", "conf"]).round(2)
track.to_csv("clean/tennis1_ball.csv", index=False)
print(f"ball found in {len(track)} of {i} frames, from frame {track.frame.min()} to {track.frame.max()}")
```

Output:

```
header: 30 fps, 137 frames
ball found in 50 of 137 frames, from frame 16 to 77
```

### Fit the path

From here on everything runs in this page from the table. Keep the frames of the toss itself:
the longest run of detections with no gap over three frames. Fit a straight line to x and a
parabola to y, both against frame number.

*Predict first:* Image y grows downward. Will the fitted parabola's x² coefficient be positive or negative?

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

track = pd.read_csv("clean/tennis1_ball.csv")
run = (track["frame"].diff() > 3).cumsum()                     # a new run after a gap
toss = track[run == run.value_counts().idxmax()]
n = toss["frame"].to_numpy()
px = np.polyfit(n, toss["x"], 1)
py = np.polyfit(n, toss["y"], 2)
res = toss["y"] - np.polyval(py, n)
print(f"toss: frames {n.min()} to {n.max()} ({len(toss)} detections)")
print(f"x: {px[0]:+.2f} px per frame; y: curvature {2 * py[0]:.3f} px per frame squared; "
      f"apex at frame {-py[1] / (2 * py[0]):.1f}; residual SD {res.std():.1f} px")
```

Output:

```
toss: frames 28 to 77 (48 detections)
x: -1.74 px per frame; y: curvature 1.425 px per frame squared; apex at frame 57.1; residual SD 9.3 px
```

### Gravity as a check on the clock

The curvature is an acceleration in pixels per frame squared. Turn pixels into meters with the
ball itself: a tennis ball is 6.54 to 6.86 cm across (ITF Rules of Tennis, Appendix I), so use
6.7 cm and the median box size. Turn frames into seconds with a frame rate. Gravity is known,
9.81 m/s², so the right frame rate is the one that gives it back.

```python
import matplotlib.pyplot as plt

px_per_m = np.median((toss["w"] + toss["h"]) / 2) / 0.067
a = 2 * py[0] / px_per_m                                       # m per frame squared
for fps in (30, 60):
    print(f"at {fps} fps: gravity comes out {a * fps ** 2:.2f} m/s²")
print(f"ball scale {px_per_m:.0f} px/m; frame rate that gives 9.81 m/s²: {np.sqrt(9.80665 / a):.1f} fps")

fig, ax = plt.subplots(2, 1, figsize=(6.4, 4.2), sharex=True, gridspec_kw={"height_ratios": [3, 1]})
ax[0].plot(n, toss["y"], "o", ms=4, color="black", label="ball center")
ax[0].plot(n, np.polyval(py, n), "-", color="gray", label="fitted parabola")
ax[0].invert_yaxis(); ax[0].set(ylabel="y (px, up is up)"); ax[0].legend(fontsize=8)
ax[1].axhline(0, color="gray", lw=1); ax[1].plot(n, res, "o", ms=3, color="black")
ax[1].set(xlabel="frame in the file", ylabel="residual (px)")
plt.tight_layout()
```

Output:

```
at 30 fps: gravity comes out 3.10 m/s²
at 60 fps: gravity comes out 12.41 m/s²
ball scale 413 px/m; frame rate that gives 9.81 m/s²: 53.3 fps
```

![The ball's image height against frame number, axis turned over so up is up, with the fitted parabola through the points and the residuals in a small lower panel.](https://apopt.com/course/tutorials/q30-ball-path/c05-1.png)

The path is a parabola (the apex at frame 57.1), and the curvature is positive because image y
grows downward. But neither frame rate on offer gives gravity back: the header's 30 gives
3.10 m/s², the 60 in the file name 12.41 m/s², and the rate that fits is 53.3 frames per
second. Something in the clip's clock is not what either label says. Look at the points, too:
every sixth or so comes in a pair at the same height (frames 30 and 31, 42 and 43, ...), where
the file shows the same picture twice, and the path jumps at frame 69. The residual SD, 9.3 px,
comes mostly from those places, not from the detector. CS-14 finds the cause and what it means
for a release speed.

**For the athlete:** a ball's path checks the video before the video measures the ball; film
your toss with a known frame rate and the whole flight in the frame.

## With your own data

Film your own toss with the phone still and the whole flight in the frame, at a frame rate you
set and write down. Run the first cell on your clip; the gravity check should come out within a
few percent of 9.81 m/s².

## The same method in another field

A falling object is a free calibration: engineers check a high-speed camera's frame rate or a
scale with a dropped ball for the same reason. The Data-Driven Engineering page on
[object detection](https://apmonitor.com/dde/index.php/Main/ObjectDetection) runs an earlier
YOLO detector on a photo and a video.

## Acknowledgements

Course example clip `tennis1_60fps.mp4` (not published). Detection uses Ultralytics YOLO (AGPL-3.0).

## References

- International Tennis Federation. *ITF Rules of Tennis 2026*, Appendix I, The Ball (size 6.54–6.86 cm for type 1 and 2 balls). [PDF](https://www.world.tennis/media/7221/2026-rules-of-tennis-english.pdf).
- Chapter 10 of *Data-Driven Athletics*: Balls in Flight.

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