Sub topic 14
Using the output: joint angles and smoothing
A pose model returns a (K, 2) array of pixel coordinates and a (K,) array of confidences for each person in each frame. Those numbers are raw detections. They are rarely the final product. This chapter covers two common steps that turn them into something usable: measuring joint angles, and smoothing keypoints over time.
This chapter assumes you can run a pretrained model and read its xy and conf outputs, as in the previous chapter. It also assumes basic NumPy and the COCO 17-keypoint order.
From keypoints to measurements
Most applications ask questions such as "how far is the elbow bent?", "is the person squatting?" or "did the wrist cross the shoulder line?". Each question is a function of a few keypoints. A reliable pipeline has four stages: gate by confidence, smooth, compute features, then apply any rules or thresholds.
Joint angles
The angle at a joint is the angle between two limb segments that meet there. For the elbow, the segments run from the elbow to the shoulder and from the elbow to the wrist. Take the two vectors, then use the dot product formula cos θ = (v1 · v2) / (|v1| |v2|).
The function below is the one from the chapter's code examples. It adds a wrapper that skips an angle when any of its three keypoints has low confidence.
import numpy as np
# COCO 17-keypoint indices used in this chapter
KP = {"l_shoulder": 5, "r_shoulder": 6, "l_elbow": 7, "r_elbow": 8,
"l_wrist": 9, "r_wrist": 10, "l_hip": 11, "r_hip": 12,
"l_knee": 13, "r_knee": 14, "l_ankle": 15, "r_ankle": 16}
def joint_angle(a, b, c):
"""Angle in degrees at point b formed by points a-b-c, each an (x, y) array."""
v1 = np.asarray(a, dtype=float) - np.asarray(b, dtype=float)
v2 = np.asarray(c, dtype=float) - np.asarray(b, dtype=float)
cos = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + 1e-9)
return float(np.degrees(np.arccos(np.clip(cos, -1.0, 1.0))))
def angle_or_none(xy, conf, names, min_conf=0.5):
"""Return the angle at the middle keypoint, or None if any keypoint is unreliable."""
ids = [KP[n] for n in names]
if np.any(conf[ids] < min_conf):
return None
a, b, c = (xy[i] for i in ids)
return joint_angle(a, b, c)
xy = np.zeros((17, 2))
conf = np.ones(17)
xy[KP["l_shoulder"]] = (0, 0)
xy[KP["l_elbow"]] = (1, 0)
xy[KP["l_wrist"]] = (1, 1)
print(angle_or_none(xy, conf, ("l_shoulder", "l_elbow", "l_wrist"))) # 90.0The 1e-9 term prevents division by zero when two keypoints coincide. The np.clip call prevents arccos from returning NaN when rounding pushes the cosine slightly past ±1.
Limits of 2D angles
A 2D angle is the angle of the limb as projected onto the image plane. It is not the true joint angle in 3D. A fully bent elbow pointing at the camera can look almost straight in the image, because the forearm is foreshortened. Three consequences follow:
- Angles are most trustworthy when the movement happens in a plane parallel to the image, such as a side view of a squat.
- Camera position matters. Compare angles only between recordings taken from similar viewpoints.
- When you need true joint angles, you need 3D lifting or multiple cameras, as the last chapter discusses.
Why raw output jitters
A pose model processes each frame independently. Small changes in pixel noise, motion blur or the detector's crop box shift the heatmap peak by a pixel or two. Heatmap decoding adds quantization on top of that, because the peak is snapped to the heatmap grid and then multiplied by the stride. The result is keypoints that vibrate even when the person stands still.
Jitter hurts derived features more than it hurts a drawn skeleton. A 2-pixel error on a short forearm changes the elbow angle by several degrees. A threshold rule such as "angle below 90 degrees counts as a rep" then fires several times as the angle noise crosses the line.
Confidence gating
Before smoothing, decide which keypoints to trust. Each keypoint has its own confidence, so gate keypoints individually and not whole people. A typical starting threshold is 0.3 for smoothing and 0.5 for computing angles. Tune both on your own footage, because confidence scores differ between models and are not calibrated probabilities.
Temporal smoothing
Smoothing combines the current measurement with past estimates. The simplest choice is an exponential moving average (EMA): s_t = α·x_t + (1 − α)·s_{t−1}. A small α smooths strongly but lags behind real motion. A large α follows motion closely but leaves more jitter.
import numpy as np
class KeypointEMA:
"""Exponential moving average over (K, 2) keypoints, skipping low-confidence points."""
def __init__(self, alpha=0.5, min_conf=0.3):
self.alpha = alpha
self.min_conf = min_conf
self.state = None
def update(self, xy, conf):
xy = np.asarray(xy, dtype=float)
conf = np.asarray(conf, dtype=float)
if self.state is None:
self.state = xy.copy()
return self.state.copy()
ok = conf >= self.min_conf
self.state[ok] = self.alpha * xy[ok] + (1 - self.alpha) * self.state[ok]
return self.state.copy()When a keypoint falls below the confidence gate, the filter holds its last smoothed position. This avoids a sudden jump to a bad detection. It also means the keypoint can freeze in place if it stays occluded for a long time. For a robust system, count how many frames each keypoint has been held and mark it as missing after a limit.
Adaptive smoothing with the One Euro filter
A fixed α forces a trade-off: strong smoothing for a still person, or low lag for a fast one. The One Euro filter adapts. It estimates speed and raises its cutoff frequency as the speed increases, so it smooths hard when the keypoint is slow and follows quickly when it moves.
import numpy as np
class OneEuro:
"""One Euro filter for arrays. freq is the frame rate in Hz."""
def __init__(self, freq, min_cutoff=1.0, beta=0.01, d_cutoff=1.0):
self.freq = freq
self.min_cutoff = min_cutoff
self.beta = beta
self.d_cutoff = d_cutoff
self.x_prev = None
self.dx_prev = None
def _alpha(self, cutoff):
tau = 1.0 / (2 * np.pi * cutoff)
return 1.0 / (1.0 + tau * self.freq)
def __call__(self, x):
x = np.asarray(x, dtype=float)
if self.x_prev is None:
self.x_prev = x
self.dx_prev = np.zeros_like(x)
return x
dx = (x - self.x_prev) * self.freq
a_d = self._alpha(self.d_cutoff)
dx_hat = a_d * dx + (1 - a_d) * self.dx_prev
cutoff = self.min_cutoff + self.beta * np.abs(dx_hat)
a = self._alpha(cutoff)
x_hat = a * x + (1 - a) * self.x_prev
self.x_prev, self.dx_prev = x_hat, dx_hat
return x_hat
rng = np.random.default_rng(0)
f = OneEuro(freq=30.0, min_cutoff=1.0, beta=0.05)
t = np.arange(90) / 30.0
raw = 100 + 40 * np.sin(2 * np.pi * 0.5 * t) + rng.normal(0, 2, size=t.size)
smooth = np.array([f(v) for v in raw])
print(round(np.std(np.diff(raw)), 2), round(np.std(np.diff(smooth)), 2))The final line prints the frame-to-frame step size before and after filtering. The filtered value should be clearly smaller. Tune min_cutoff first, to remove jitter while the person is still. Then raise beta until fast movements stop lagging. Use one filter instance per keypoint coordinate for each tracked person, because the state is not shared.
Smooth keypoints or smooth angles?
You can filter either one:
| Approach | Advantage | Drawback |
|---|---|---|
| Smooth keypoints, then compute angles | The skeleton drawing is also stable. One filter serves every feature. | Errors in one keypoint still reach several angles after filtering. |
| Smooth each angle signal | You can tune the smoothing per feature. | The drawn skeleton still jitters. A dropped keypoint gives a gap in the angle signal. |
Smoothing keypoints is the usual default. Add angle smoothing only for a feature that needs a different trade-off between lag and noise.
Edge cases to handle
- Identity across frames. A filter only makes sense if it follows the same person. Multi-person output has no stable order, so assign IDs with a tracker or by matching boxes between frames. Without that, filters blend two people when their order swaps.
- Left-right swaps. A single-frame swap of the left and right limb produces a large jump that smoothing spreads over several frames. Detect it by checking the distance between each keypoint and its previous position, and reject jumps larger than a physical limit.
- Frame rate. The α of an EMA is tied to the frame rate. Doubling the frame rate with the same α makes the filter respond twice as fast in real time. The One Euro filter takes the frame rate as an argument for this reason.
- Scale. A pixel threshold that works for a person filling the frame fails for a distant person. Normalize distances by a body measure, such as shoulder width or torso length, before you compare them to a threshold. Angles do not need this.
- Missing data. Leave gaps as
NoneorNaNin feature signals. Do not fill them with zero, which looks like a real measurement.
Exercise
A rep counter counts a rep each time the knee angle goes below 100 degrees. With raw model output it counts 14 reps for a person who did 8. You add an EMA with α = 0.1 and the count drops to 8 but the counter now misses the bottom of fast reps. Name two changes that would reduce both problems.
Show answer
Raw jitter makes the angle cross the threshold several times per rep, which explains the extra counts. A very small α removes the jitter but lags so much that a fast rep never reaches the threshold in the smoothed signal. One fix is to replace the EMA with a One Euro filter, which smooths a slow signal strongly and follows a fast one with less lag. A second fix is to use hysteresis, with a lower threshold (for example 100 degrees) to enter the down state and a higher one (for example 130 degrees) to leave it, so noise near a single threshold cannot create extra reps. Gating on keypoint confidence also helps.
Exercise
Why can the angle from joint_angle differ greatly from the real elbow angle when the person points their forearm at the camera?
Show answer
The function measures the angle between the projected 2D segments. When the forearm points toward the camera it is foreshortened, so the wrist lands near the elbow in the image and the 2D angle no longer matches the real 3D angle. Use a camera view where the motion lies in the image plane, or lift the pose to 3D.