Sub topic 13
Running a Pretrained Pose Model
This chapter assumes you know basic Python and NumPy, can read a CNN-based detector's output (boxes and confidences), and have met the COCO 17-keypoint layout and heatmap decoding from earlier chapters. You will run a pretrained single-stage model, read its outputs, and check them before you build on them.
Why start from a pretrained model
Training a pose model needs tens of thousands of annotated people and many GPU hours. A pretrained model has already done that work on COCO Keypoints. For most applications, such as counting repetitions, checking posture or driving an animation, you run the model first. You train only if its accuracy on your data is not good enough.
The example here uses yolov8n-pose from the Ultralytics package. It is a single-stage model: one forward pass returns person boxes and their 17 keypoints together, so you need no separate detector and no grouping step. The same reading habits apply to top-down tools such as MMPose or other libraries. Their output is also a set of per-person arrays of coordinates and confidences.
Setup and first run
Install the package and a recent PyTorch, then run the model on one image.
from ultralytics import YOLO
model = YOLO("yolov8n-pose.pt")
results = model("person.jpg")
kp = results[0].keypoints
if kp is not None and len(kp.xy) > 0:
xy = kp.xy[0].cpu().numpy() # (17, 2) pixel coordinates of the first person
conf = kp.conf[0].cpu().numpy() # (17,) per-keypoint confidence
print(xy.shape, conf.shape)The weights file downloads on first use. Calling model(...) with a path returns a list with one Results object per image. results[0] is therefore the result for your single image.
What the output contains
For an image with N detected people, the keypoints object holds these arrays:
| Attribute | Shape | Meaning |
|---|---|---|
| `kp.xy` | (N, 17, 2) | Pixel x, y in the original image |
| `kp.xyn` | (N, 17, 2) | The same coordinates normalized to 0–1 |
| `kp.conf` | (N, 17) | Confidence for each keypoint |
| `results[0].boxes.conf` | (N,) | Confidence for each person box |
Three details matter in practice.
- Coordinates are in the original image. The package resizes and pads the image internally, then maps the points back. Unlike the raw heatmap decoder from the decoding chapter, you do not multiply by a stride yourself.
- Two kinds of confidence exist. The box confidence says how sure the model is that a person is there. Each keypoint confidence says how sure it is about that joint. A confident box can still contain weak keypoints.
- Order is fixed. Index 0 is the nose, 1 and 2 are the left and right eye, and so on in COCO order. "Left" means the person's own left, not the left side of the image.
Keypoints that the model cannot place often come back as (0, 0) with a low confidence. Always check the confidence before you use a point. Otherwise a joint at the image corner will pull your measurements toward zero.
Reading the result safely
The following script runs the model, drops weak keypoints and prints the named joints for each person. It also shows how to find the edges of the skeleton that you would draw.
import numpy as np
from ultralytics import YOLO
NAMES = ["nose", "left_eye", "right_eye", "left_ear", "right_ear",
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
"left_wrist", "right_wrist", "left_hip", "right_hip",
"left_knee", "right_knee", "left_ankle", "right_ankle"]
EDGES = [(5, 7), (7, 9), (6, 8), (8, 10), (5, 6), (5, 11), (6, 12),
(11, 12), (11, 13), (13, 15), (12, 14), (14, 16)]
def valid_keypoints(xy, conf, min_conf=0.5):
"""Return a boolean mask of keypoints that are trustworthy."""
return (conf >= min_conf) & ~np.all(xy == 0, axis=1)
model = YOLO("yolov8n-pose.pt")
result = model("person.jpg")[0]
if result.keypoints is None or len(result.keypoints.xy) == 0:
print("No person found")
else:
for person_id in range(len(result.keypoints.xy)):
xy = result.keypoints.xy[person_id].cpu().numpy()
conf = result.keypoints.conf[person_id].cpu().numpy()
ok = valid_keypoints(xy, conf)
print(f"person {person_id}: {ok.sum()} of 17 keypoints usable")
for i in np.flatnonzero(ok):
x, y = xy[i]
print(f" {NAMES[i]:15s} ({x:7.1f}, {y:7.1f}) conf={conf[i]:.2f}")
usable_edges = [(a, b) for a, b in EDGES if ok[a] and ok[b]]
print(" edges to draw:", usable_edges)An edge is drawn only when both of its end points pass the confidence test. This avoids lines that jump to a corner of the image.
The pipeline from image to keypoints
Non-maximum suppression (NMS) removes duplicate candidates for the same person. Its IoU threshold is one of the settings you may need to change in crowds.
Settings that change the result
You pass these as arguments to the call, for example model("person.jpg", conf=0.4, iou=0.6, imgsz=960).
confis the minimum box confidence. Lowering it finds more people, including false ones.iouis the NMS overlap threshold. A low value merges nearby people. A higher value keeps overlapping people but may produce duplicates.imgszis the network input size. People who are small in the frame, such as in a wide shot, are located much better at 960 or 1280 than at the default 640. Inference is slower.- Model size. The nano model (
n) is fast and the larger ones (s,m,l,x) are more accurate. On a CPU, start withnand move up only if the keypoints are too noisy.
Running on video
A video is a sequence of frames, and the model treats each frame on its own. Passing stream=True returns a generator, so frames are processed one at a time and memory use stays flat.
import numpy as np
from ultralytics import YOLO
model = YOLO("yolov8n-pose.pt")
tracks = [] # one (17, 2) array per frame for the first person, NaN where invalid
for r in model("clip.mp4", stream=True, verbose=False):
frame = np.full((17, 2), np.nan, dtype=np.float32)
if r.keypoints is not None and len(r.keypoints.xy) > 0:
xy = r.keypoints.xy[0].cpu().numpy()
conf = r.keypoints.conf[0].cpu().numpy()
good = (conf >= 0.5) & ~np.all(xy == 0, axis=1)
frame[good] = xy[good]
tracks.append(frame)
tracks = np.stack(tracks)
print(tracks.shape) # (num_frames, 17, 2)Using NaN for missing joints keeps gaps visible, which is better than filling them with zeros. Later steps such as smoothing and joint angles can then skip or interpolate them on purpose.
There is one trap. "The first person" in frame 10 is not necessarily the same person as "the first person" in frame 11, because the order of detections can change between frames. For one-person footage this is harmless. For several people, use model.track(...), which assigns a persistent ID to each person, and index the results by that ID.
Checking the output before you trust it
Run these checks on a few of your own images before you build anything on the output.
- Draw the skeleton on the image. A plot shows errors that numbers hide, such as a swapped left and right leg. The Ultralytics call
results[0].plot()returns an annotated image as a NumPy array. - Count usable keypoints. A person with 6 of 17 usable joints is a poor input for angle calculations.
- Compare against the box. Valid keypoints should mostly fall inside or near the person's box. Many points far outside it indicate a wrong association.
- Look at the low-confidence cases. Occluded, cropped and heavily blurred people are where confidence drops. Decide whether your application can tolerate the loss.
Common mistakes
- Using the image width as the stride. Output from the package is already in original pixels. Scaling it again moves every point.
- Reading
xywhen the list is empty. Without a guard,kp.xy[0]raises anIndexErroron images with no people. - Mixing up image left and body left. A mirrored webcam image makes the person's right hand appear on the left of the picture. The model still labels it
right_wrist. Flip the frame deliberately and not by accident. - Treating a zero coordinate as a real position. Filter it as shown above.
- Timing with the first call. The first inference includes model loading and warm-up. Time later calls.
Exercise
A script reads xy = kp.xy[0] and computes the elbow angle from the shoulder, elbow and wrist, but it never looks at kp.conf. On some frames the angle is exactly 0 or jumps wildly. Give two likely causes and the fix.
Show answer
When a keypoint is not found, the model can return it at (0, 0) with low confidence, so the angle is computed from a point in the image corner. The first person may also change between frames in a multi-person video, so the angle switches between people. Fix: compute the angle only when the shoulder, elbow and wrist all pass a confidence threshold and are not (0, 0), set the result to NaN otherwise, and use model.track to follow one person by ID.
Exercise
You run the model on a wide photo of a crowd and it misses people who are small and far away. Name two arguments you could change and the cost of each.
Show answer
Increase imgsz (for example to 1280), which helps small people but slows inference and raises memory use. Lower conf, which finds fainter detections but adds false people. Using a larger model size also helps accuracy at the cost of speed.