# Q-7: The angle from three points

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

Web page: https://apopt.com/course/tutorials/q07-three-point-angle/ · Data: https://apopt.com/data/tutorials/q07-three-point-angle/

## The decision

A coach asks how far a runner's knee bends in the swing. The answer is an angle from three
keypoints in each frame, and it is only as good as the three points and the camera's view.

## The raw data

- `raw/form2_keypoints_yolo26s.csv`: a pose model's keypoint table for a side-view running clip, one row per frame (362 rows), x and y in pixels and a confidence for 17 keypoints Made for this tutorial with the YOLO26s pose model from the course's example clip `form2_60fps.mp4` (header 30 frames per second). The clip shows a person and is not published; the table shows no one.

### Three points make an angle

A joint angle needs three keypoints: one on each segment and one at the joint. For the knee,
take the hip A, the knee B and the ankle C. The two vectors that leave the knee, u = A − B and
w = C − B, meet at the **included angle** θ, and the dot product gives it (Section 3.2.2):

θ = arccos( u·w / (|u| |w|) )

A straight leg is 180°. Clinicians often report **flexion**, 180° − θ, which is 0° for a straight
leg. Check the function on the book's example first: in one frame of Jordan's jump the hip is at
(0.50, 0.40), the knee at (0.55, 0.60) and the ankle at (0.48, 0.80).

*Predict first:* Work Jordan's knee angle by hand first. Is it nearer 120°, 150° or 170°?

```python
import numpy as np

def angle(a, b, c):
    """Included angle at b, in degrees, between b->a and b->c (works on arrays of points too)."""
    u, w = np.asarray(a, float) - np.asarray(b, float), np.asarray(c, float) - np.asarray(b, float)
    cos = (u * w).sum(axis=-1) / (np.linalg.norm(u, axis=-1) * np.linalg.norm(w, axis=-1))
    return np.degrees(np.arccos(np.clip(cos, -1.0, 1.0)))   # clip: rounding can push |cos| past 1

k = angle((0.50, 0.40), (0.55, 0.60), (0.48, 0.80))
print(f"Jordan's knee: included {k:.1f} deg, flexion {180 - k:.1f} deg")
print(f"straight leg {angle((0, 0), (0, 1), (0, 2)):.1f} deg; right angle {angle((1, 0), (0, 0), (0, 1)):.1f} deg")
print(f"same points in pixels {angle((500, 400), (550, 600), (480, 800)):.1f} deg")
assert abs(k - 146.7) < 0.05
```

Output:

```
Jordan's knee: included 146.7 deg, flexion 33.3 deg
straight leg 180.0 deg; right angle 90.0 deg
same points in pixels 146.7 deg
```

146.7°, a flexion of 33.3°, as in Example "Jordan's knee angle by hand". The units of the points
do not matter, because the lengths divide out: the same frame in pixels gives the same angle.

### The same function on every frame of a clip

The file is a pose model's table for a running clip from the course's example set,
`form2_60fps.mp4`, filmed from the side: one row per frame, x and y in pixels for 17 keypoints,
and a confidence for each. The video is not published; the table shows no one. The function
works on whole columns at once.

*Predict first:* Over a running stride, what is the largest knee flexion you expect, in degrees?

```python
import pandas as pd

kp = pd.read_csv("raw/form2_keypoints_yolo26s.csv")
for side in ["l", "r"]:
    pts = [kp[[f"{side}_{j}_x", f"{side}_{j}_y"]].to_numpy() for j in ("hip", "knee", "ankle")]
    kp[f"{side}_knee_flex"] = 180 - angle(*pts)
    low = kp[[f"{side}_{j}_c" for j in ("hip", "knee", "ankle")]].min(axis=1) < 0.5
    print(f"{side} knee flexion: {kp[f'{side}_knee_flex'].min():.0f} to {kp[f'{side}_knee_flex'].max():.0f} deg; "
          f"{int(low.sum())} of {len(kp)} frames with a point below 0.5 confidence")
```

Output:

```
l knee flexion: 5 to 112 deg; 0 of 362 frames with a point below 0.5 confidence
r knee flexion: 3 to 100 deg; 0 of 362 frames with a point below 0.5 confidence
```

### One chart

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(9, 3.4))
ax.plot(kp["frame"], kp["l_knee_flex"], "k.-", ms=3, lw=1, label="left knee")
ax.plot(kp["frame"], kp["r_knee_flex"], "--", color="0.55", lw=1, label="right knee")
ax.set(xlabel="frame number", ylabel="knee flexion (deg)")
ax.legend(loc="upper right", ncol=2)
plt.tight_layout()
from scipy.signal import find_peaks
peaks, _ = find_peaks(kp["l_knee_flex"], height=60, distance=12)   # swings at least 12 frames apart
print(f"left knee: {len(peaks)} swing peaks, median {kp['l_knee_flex'].iloc[peaks].median():.0f} deg; "
      f"median of the 20% straightest frames {kp['l_knee_flex'].quantile(0.2):.0f} deg")
```

Output:

```
left knee: 16 swing peaks, median 100 deg; median of the 20% straightest frames 17 deg
```

![Knee flexion in degrees against frame number over 362 frames. The left knee (solid line with dots) rises and falls 16 times, from near 10 degrees to peaks of about 80 to 110 degrees; the right knee (dashed gray line) follows a similar rhythm half a stride later but is more jagged.](https://apopt.com/course/tutorials/q07-three-point-angle/c05-1.png)

The left knee bends and straightens once a stride, 16 times in the clip: nearly straight
(10 to 20°) around foot contact, folded to about 100° in the swing, when the foot comes up behind
the body. The right knee follows half a stride later, but its trace is more jagged. In a side
view one leg is always partly behind the other, and the model sometimes moves a point or swaps
the two legs' labels for a frame. And every angle here is measured in the image plane: if the leg
is not square to the camera, the true knee angle differs (Section 3.9.1).

**For the athlete:** "From the side, your knee folds to about 100 degrees in each swing and is
nearly straight when your foot lands; to compare sessions we'll film from the same side, square to
your path, every time."

## With your own data

Run a pose model on a side-view clip of your own (CS-10 shows how), or use the canvas app's
`angle(left_hip, left_knee, left_ankle)` on one frame, and check the app's number against this
function on the same three points.

## References

- *Data-Driven Athletics*, Chapter 3, The angle from three points (Section 3.2.2) and Image-plane angles are not joint angles (Section 3.9.1).

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