# Q-25: Find foot contacts in an ankle trace

Data-Driven Athletics tutorial · Week 9 · Chapter 9 · about 15 min · workflow steps: Visualize, Cleanse, Features

Web page: https://apopt.com/course/tutorials/q25-foot-contacts/ · Data: https://apopt.com/data/tutorials/q25-foot-contacts/

## The decision

Every timing measure of running, cadence, contact time and flight time, starts from a list of
foot contacts. Is the list right: one contact per foot plant, none doubled, none missed?

## The raw data

- `raw/form1_ankles.csv`: both ankles' image position and confidence in every frame of a treadmill run filmed from behind at 30 frames per second (464 rows) Chapter 9's example table, also published with the book's data (`book/ch09-gait`).

Chapter 9's running example is a runner on a treadmill, filmed from behind at 30 frames per
second for 15.5 s. A pose model found both ankles in every frame, and the table keeps their
image position and confidence. A foot on the belt is at its lowest point in the picture,
which in image coordinates is its **largest** y. So a contact is a peak of y.

*Predict first:* In 15.5 s of running at about 170 steps a minute, how many contacts should each foot make?

```python
import numpy as np
import pandas as pd
from scipy.signal import find_peaks

FPS = 30
df = pd.read_csv("raw/form1_ankles.csv")
print(df.shape, f"{len(df) / FPS:.1f} s; median ankle confidence "
      f"{df[['l_ankle_c', 'r_ankle_c']].median().min():.2f}")
naive, _ = find_peaks(df["l_ankle_y"])                 # every local peak, no guards
print(f"left ankle, every local peak: {len(naive)} 'contacts'")
```

Output:

```
(464, 8) 15.5 s; median ankle confidence 0.99
left ankle, every local peak: 107 'contacts'
```

A runner at 170 steps a minute makes 85 contacts a minute on each foot, about 22 in 15.5 s.
Every local peak gives 107, five times too many: a noisy trace has small bumps, and each bump is a
peak. The running app adds three guards (checked in its source, `form/src/lib/metrics.ts`):
smooth the trace over about 0.08 s (3 frames at 30 per second); accept only peaks in the
bottom 15% of the foot's range, above the 85th percentile of y; and keep peaks at least
0.2 s apart.

```python
def contacts(y, fps=FPS):
    s = pd.Series(y).rolling(3, center=True, min_periods=1).mean().to_numpy()   # about 0.08 s
    peaks, _ = find_peaks(s, height=np.percentile(s, 85), distance=int(0.2 * fps))
    return peaks

found = {side: contacts(df[f"{side}_ankle_y"].to_numpy()) for side in "lr"}
for side, p in found.items():
    gaps = np.diff(p) / FPS
    print(f"{side}: {len(p)} contacts; same-foot interval median {np.median(gaps):.3f} s, "
          f"range {gaps.min():.3f} to {gaps.max():.3f} s")
```

Output:

```
l: 22 contacts; same-foot interval median 0.700 s, range 0.667 to 0.733 s
r: 22 contacts; same-foot interval median 0.700 s, range 0.667 to 0.733 s
```

```python
import matplotlib.pyplot as plt

first = df["t"] < 4
fig, ax = plt.subplots(figsize=(7, 3.2))
for side, style, mark in (("l", "-", "o"), ("r", "--", "s")):
    ax.plot(df["t"][first], df[f"{side}_ankle_y"][first], style, lw=1.2, label=f"{side} ankle")
    p = [i for i in found[side] if df["t"][i] < 4]
    ax.plot(df["t"][p], df[f"{side}_ankle_y"][p], mark, mfc="none", ms=8, color="black")
ax.invert_yaxis()
ax.set(xlabel="time (s)", ylabel="ankle y (pixels, down is down)")
ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.0), ncol=2, fontsize=8, frameon=False)
plt.tight_layout()
```

![Left and right ankle image height for the first four seconds, axis turned over so the belt is at the bottom, with each detected contact marked at the lowest point of each stance.](https://apopt.com/course/tutorials/q25-foot-contacts/c04-1.png)

With the guards, each foot gives 22 contacts, one per stride, and the same-foot interval
stays between about 0.67 and 0.73 s, 20 to 22 frames. That narrow range is the check that
no contact was doubled or missed: a doubled contact would show as an interval near half a
stride, a missed one as an interval near a whole extra stride. Notice that the intervals can
only be whole frames, 33 ms apart; Q-26 shows what that does to a cadence.

**For the athlete:** a phone can find every foot contact in a steady run, as long as the
whole foot stays in the frame.

## With your own data

Build the same two-ankle table from your own clip (Chapter 9's first listing, or CS-10's local
cells) and run this page on it. Film 15 s or more of steady running with the feet always in
the frame.

## The same method in another field

Finding events in a repeating signal with a level and a minimum spacing is how heartbeats
are found in an ECG (Q-13) and how cycles are counted in a machine's vibration record.

## Acknowledgements

Ankle table from Chapter 9 of *Data-Driven Athletics*, made with Ultralytics YOLO26 (AGPL-3.0).

## References

- Chapter 9 of *Data-Driven Athletics*: Cycles and Events; Running: Contact and Flight.

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