Detect falls and count reps with pose estimation

Run three apps on one YOLOv8n-pose engine on a Raspberry Pi 5 with the Sixfab AI HAT+: an arm-press rep counter, a fall detection demo and a Fruit Ninja-style pose game, at about 32 FPS on 1080p video.

Works with

AI HAT+Product overviewonRaspberry Pi 5

Do not rely on fall detection for safety

Fall detection is a demo, not a medical or emergency alert device. It shows an alert on screen and prints a line in the terminal; it sends nothing anywhere.

How it works

On the Sixfab AI HAT+ for Raspberry Pi 5 (DEEPX DX-M1M), the NPU runs YOLOv8n-pose; the Raspberry Pi 5 CPU decodes 17 keypoints per person and runs tracking and the app logic. An NPU (neural processing unit) is a processor built to run neural networks, so the CPU does not have to. Three OpenCV-window apps share one pose engine. Each reads a USB webcam or a video file, finds every person in frame and applies its own rule to their body joints (human pose estimation: finding the body joints of each person in an image). The project is part of the Raspberry Pi 5 AI projects series for the DEEPX NPU.

  1. A USB webcam or a video file supplies the frames.
  2. OpenCV captures each frame on the Raspberry Pi 5 CPU (open_source(), read_looping()).
  3. yolov8n-pose.dxnn runs on the DEEPX NPU and returns the raw (56, 8400) output.
  4. Python letterboxes the input, decodes the output and runs NMS on the CPU.
  5. The engine returns a list of poses, one per detected person, each with a box, a confidence and 17 keypoints.
  6. The tracker keeps an ID for each person across frames.
  7. The app logic (rep counter, fall detection or pose game) applies its rule and draws the OpenCV window, on the CPU.

Read the result in the app’s OpenCV window, which draws each person’s skeleton and the app’s labels; the rep counter and fall detection also print a line in the terminal for each rep or alert. The apps do not use Frigate NVR, RTSP or MQTT, and send output only to the screen and the terminal.

Requirements

Finish the AI HAT+ quickstart first.

Required

Hardware

  • Raspberry Pi 5Host computer.
  • Sixfab AI HAT+ (DEEPX DX-M1M)The NPU board.Shop
  • USB webcam or a video fileA webcam is opened by camera index (0 by default). A video file path also works, and the video loops.
  • DisplayThe apps open an OpenCV window, so run them in a desktop session on the Raspberry Pi 5.

Software

  • git, curl, sha256sumUsed by the install script.
  • opencv-python, numpyInstalled by the install script, or with pip in the manual install.
  • yolov8n-pose.dxnnReady-compiled model, downloaded from the project’s GitHub release into model/.

Install

Both methods end with the model downloaded and checked, OpenCV and NumPy installed next to dx_engine, and an app running. Run every command on the Raspberry Pi 5, in a desktop session.

Choose camera or video file

Pass a camera index for another camera, or a video file path instead of a camera; a video file loops. The project’s GitHub release has two sample clips: pilates.mp4 for the rep counter and fall.mp4 for fall detection. Download them into a demo/ folder in the project folder.

python fitness_coach.py 1
python fitness_coach.py demo/pilates.mp4
python fall_detection.py demo/fall.mp4

Only one app can use a camera at a time: press q in one app before you start another. All three windows share two keys:

KeyAction
qQuit
rReset rep counters, clear fall alerts, or restart the game after game over

Verify

  1. Check NPU

    Run the DEEPX runtime’s status command before you start an app:

    dxrt-cli -s
    Device 0: M1M
    …

    The output lists the NPU; on the test unit it was Device 0: M1M. If it is missing, see Troubleshooting.

  2. Start app and step into frame

    Each app prints a ready line in the terminal and opens a window with the camera image (mirrored for a webcam), skeleton overlays and an FPS readout at top right. With no person detected, the window shows No pose detected - step into frame.

    AppTerminal lineWhat the window shows
    fitness_coach.pyPilates Coach ready. Make sure shoulders, elbows and wrists are visible - works for multiple people at once.A #<id> Reps: <n> label above each person, and “People tracked”
    fall_detection.pyFall Detection ready. Works for multiple people at once.A green box per person with a #<id> angle=<deg> label, and “People tracked”. When an alert fires, that person’s box turns red with a FALL! label, and a FALL DETECTED banner appears
    fruit_ninja_pose.pyFruit Ninja (pose edition) ready. Everyone in frame can slice - multiplayer!Score, Lives and Players, with fruit launching from the bottom

    The rep counter also prints one line per counted rep with the person ID, the feedback and the smallest elbow angle reached, such as Person #4 - REP 1: Nice control! (67 deg).

  3. Check that normal movement raises no fall alert

    With fall_detection.py running (window title “Fall Detection (q=quit r=clear alerts)”), stand, sit down slowly and crouch in front of the camera. The rule is designed not to flag these. If an alert appears, note the angle on the label and see Troubleshooting.

  4. Check fall alert

    Play a fall video file such as demo/fall.mp4, or stage a fall onto a crash mat by a consenting adult. When the torso goes above 70° within 2 seconds of a fast drop, the window gets a red tint with “FALL DETECTED” at the top, the person’s box turns red with a FALL! label, and the terminal prints:

    Person #<id>: FALL DETECTED (angle=<deg> deg, speed=<x> frame heights/s)

    The angle is the torso angle when the alert fires. The speed is the hip drop speed in that frame, which can be low because the app remembers the fast drop for 2 seconds. Each person gets one alert per fall and must stand upright again for a new one; press r to clear the alerts and re-arm everyone.

Results

Tested on November 10, 2026: Raspberry Pi 5 Model B Rev 1.1 (8 GB, 4 cores), Sixfab AI HAT+ (DEEPX DX-M1M), Raspberry Pi OS Trixie (Debian GNU/Linux 13), kernel 6.18.50+rpt-rpi-2712, Python 3.13.5, DX-RT v3.5.0, RT driver v2.7.0, PCIe driver v2.7.0, firmware v2.7.6 and yolov8n-pose.dxnn, from video files with no live camera, a load average of about 0.0 and nothing else on the NPU.

ClipResolution, source ratePoses per frame (mean, max)infer() per frame, meaninfer() p95Read + infer + tracking, meanFull loop
demo/pilates.mp41920 × 1080, 25 fps3.90, 527.3 to 27.4 ms28.1 to 28.3 ms31.0 to 31.2 ms32.1 to 32.3 FPS
demo/fall.mp4898 × 506, 50 fps1.00, 225.4 to 26.5 ms26.9 to 27.0 ms26.6 to 27.8 ms36.0 to 37.6 FPS

Each cell is the range over three runs. infer() is PoseEngine.infer(): preprocessing, the NPU run, decoding the raw output and NMS. p95 is the 95th-percentile time per frame. The full loop adds reading the frame and updating the tracker. At these rates the headless loop keeps up with 25 fps video, not with 50 fps.

benchmark.py reads 30 warm-up frames, then times 300 frames per clip with time.perf_counter, looping the clip if it is shorter. It runs headless: no window, no drawing and no camera capture. The FPS counter in the app windows also counts drawing and display, so it reads lower.

Not measured: the NPU time on its own (infer() includes preprocessing and NMS on the CPU), a live USB camera on the Raspberry Pi 5, a CPU-only baseline, power, temperature and more than three runs. Rep counts were not checked against a hand count; the accuracy of rep counts, fall alerts and the game is not measured.

On the sample class clip, the rep counter window showed 5 tracked people with a counter each. Fall detection was tried only on one two-person sample clip (14 s): it flagged the person who fell once per loop and did not flag the caregiver. The fall thresholds were set on that clip and have not been checked against other falls, sit-downs or crouches; no staged fall trials or multi-person fall trials are recorded, so the page makes no accuracy claim.

For a board-level benchmark, see the Sixfab AI HAT+ benchmark on Raspberry Pi 5.

Run benchmark

Run it from the repository’s project folder, with nothing else using the NPU:

python benchmark.py demo/pilates.mp4 demo/fall.mp4

It prints one block per clip: the source resolution and frame rate, the infer() mean, median and p95, the full-loop mean and FPS, and the poses per frame.

Details

Apps

AppBody signalRuleMulti-person designCommand
Pilates rep counterElbow angle, averaged across both arms when visibleEXTENDED, BENT, EXTENDED is one repA counter above each person’s boxpython fitness_coach.py
Fall detectionTorso angle from vertical plus a fast hip drop in the last 2 sTorso above 70° within 2 s of a fast drop: red “FALL DETECTED” for 5 sOwn history and alert state per personpython fall_detection.py
Fruit Ninja-style pose gameBoth wrists as blades+1 per slice; 3 misses end itColor-coded blades per personpython fruit_ninja_pose.py

Keypoints

Keypoints follow COCO order, 0 (nose) to 16 (right ankle). COCO is the public dataset whose 17-keypoint body layout YOLOv8 pose uses. The elbow angle uses shoulder, elbow and wrist; the torso line runs from the shoulder midpoint to the hip midpoint.

IndexKeypointsUsed by
0 to 4Nose; left and right eye; left and right earSkeleton drawing only
5 to 6Left and right shoulderPilates elbow angle; fall torso line
7 to 8Left and right elbowPilates elbow angle
9 to 10Left and right wristPilates elbow angle; game blades
11 to 12Left and right hipFall torso line and hip drop
13 to 16Left and right knee; left and right ankleSkeleton drawing only

Pose pipeline

The shared engine is pose_engine.py, imported by all three apps. It loads yolov8n-pose.dxnn (YOLOv8n-pose compiled to DEEPX’s .dxnn format) through dx_engine, DEEPX’s Python package for running models on the NPU, and returns one Pose per detected person, each with a bounding box, a confidence and 17 keypoints. Only inference runs on the NPU. The cpp_examples/pose_estimation folder of the same repository has a separate pose demo built for other models.

Raw (56, 8400) output and decoding

The compiled model returns one undecoded row of 56 values for each of 8,400 anchors, the candidate detections it scores in every frame. This model has no post-processing unit (PPU), the on-NPU step that decodes the boxes and runs non-maximum suppression (NMS), which removes duplicate boxes for the same person. The Python code does both. See DX-COM PPU settings.

Values per anchorMeaning
4Box: center x, center y, width, height
1Confidence
51 (17 × 3)Keypoints: x, y, visibility, for each of 17 COCO keypoints

PoseEngine.infer decodes in this order:

  1. Convert the BGR frame to RGB and letterbox it to the model’s square input, padding with value 114.
  2. Run the model, reshape the output to (56, 8400) and transpose it so each row is one anchor.
  3. Keep anchors with confidence above 0.4.
  4. Convert boxes from center format to corner format and run cv2.dnn.NMSBoxes with an NMS threshold of 0.45.
  5. Map boxes and keypoints back through the letterbox scale and padding to original frame coordinates.
  6. Drop weak duplicate poses: any pose with confidence below 0.6 whose box lies at least 70% inside a stronger pose’s box. NMS can keep such a copy of one person, most often when someone lies down and the box is wide and flat. A confident second person is kept.

A keypoint counts as visible only when its visibility value is above 0.5.

Tracking across frames

A nearest-centroid tracker gives each detected person a stable ID. update_pose_tracks() compares every track with every detection, sorts the pairs by the distance between bounding-box centers and assigns pairs from the closest up. It accepts a pair only if the centers are under 150 pixels apart; the fall detection app passes 0.3 of the frame width instead, because a falling body’s box center jumps far. A detection that no track claims starts a new track with a new ID.

A track that gets no detection ages by one frame; tracks older than 40 frames are dropped. The 40-frame lifetime covers the frames where two overlapping people return one merged skeleton, so each person’s track survives until it gets its own detection back. There is no re-identification: a person who moves farther than the match distance between frames starts a new track.

Each track carries a free-form .data dictionary where each app keeps its per-person state: rep counts, fall history and alert time, or blade trails. The apps draw only tracks that matched a detection on the current frame.

Pilates rep counter

The counter tracks the elbow angle (shoulder, elbow, wrist), averaged across both arms when both are visible. Each person gets their own counter, drawn above their bounding box as #<id> Reps: <n>; the number of people tracked shows at top left.

StateEntered whenWhat happens
EXTENDEDStart state; elbow angle back above 150 degreesWaits for a bend
BENTElbow angle below 110 degreesRecords the smallest angle reached
EXTENDED againAngle back above 150 degrees+1 rep; feedback appears for 2.5 seconds

The smallest angle reached while bent sets the feedback, drawn as a yellow line: at 100 degrees or lower, Nice control! with the angle; above 100 degrees, “Pull in further” with the angle. Press r to reset all rep counters.

The counter counts arm presses, not squats, because most Pilates work (ring press, chest press, arm circles) is driven by controlled arm extension and flexion. A squat counter built on the hip, knee and ankle angle never fired on a Pilates reformer class video, which showed a static wide-lunge stance with the repeated motion in the arms.

Fall detection

Every frame, the app draws a line from the middle of the shoulders to the middle of the hips and measures how far it leans from vertical. It also tracks how quickly the hips moved down over the last 0.6 seconds. The rule assumes that a fall is fast and ends with the line near horizontal, and that sitting down is slow, so a slow sit-down is designed not to be flagged.

SignalMeasured fromTreated as normalFall pattern
Torso angle from verticalLine from the shoulder midpoint to the hip midpointUpright, about 0°Above 70°; lying flat is about 90°
Fast hip dropHip-midpoint drop over the last 0.6 s, as a fraction of the frame height per secondA slow drop, as when sittingAbove 0.55 frame heights per second
RuleA fast drop in the last 2 seconds, and the torso above 70°Either missing: no alertRed “FALL DETECTED” for 5 s, then one alert per fall until the person is upright again (below 40°), or until r

The torso line uses keypoints 5 and 6 (shoulders) and 11 and 12 (hips). The app averages each pair when both sides are visible and uses one side if only one is.

The thresholds are constants in fall_detection.py: FALL_ANGLE_DEG = 70.0, FALL_SPEED_FRAC_PER_SEC = 0.55, FALL_DROP_MEMORY_SEC = 2.0, REARM_ANGLE_DEG = 40.0. The speed is a fraction of the frame height, so it does not change with the camera’s resolution, but it depends on how far the person is from the camera. At a 720p frame height, 0.55 frame heights per second is about 400 pixels per second. For a video file, time comes from the video’s own clock (frame number divided by frame rate); for a camera, from the wall clock.

The rule remembers a fast drop for 2 seconds because a person often drops while the torso is still upright and turns horizontal only after the drop ends. In the sample clip the hips fell first and the torso reached horizontal afterward, so a rule that needed both at the same moment never fired. Deliberate sitting or crouching is slow and does not turn the torso that far; the trade-off is that a slow collapse or slide passes too.

Each tracked person has their own hip-height history and alert state, kept in their track, and the label shows #<id> with the current torso angle. One person’s alert does not set another person’s.

When the rule triggers, that person’s box turns red with a FALL! label and a FALL DETECTED banner tints the frame; other people keep a green box.

Fruit Ninja-style pose game

Both wrists act as blades: swipe through a fruit with either wrist to slice it for +1 point. Each wrist shows a solid colored circle at its position and a short trail while it moves. Fruit launches from the bottom of the frame and arcs up and down under gravity. When 3 fruits fall past the bottom uncut, the game ends; press r to play again.

Every person in frame gets their own pair of blades in a color assigned by person ID, so several players slice at once. The colors come from a list of four, so a fifth player reuses a color. Leave clear space around each player. Score, Lives and Players show at top left.

Use engine in your own Python app

Create a PoseEngine, open a source, call engine.infer(frame) for a list of poses, read keypoints by COCO index and call angle() on three points. This excerpt from fitness_coach.py shows the pattern; the full app adds drawing, rep logic and the q key.

import sys

import cv2

from pose_engine import (
    FpsCounter, PoseEngine, angle, draw_text, open_source, read_looping,
    update_pose_tracks, L_SHOULDER, L_ELBOW, L_WRIST, R_SHOULDER, R_ELBOW, R_WRIST,
)

SOURCE = sys.argv[1] if len(sys.argv) > 1 else "0"

engine = PoseEngine()
cap, is_camera = open_source(SOURCE)

tracks = []

while True:
    ok, frame = read_looping(cap, is_camera)
    if not ok:
        break
    if is_camera:
        frame = cv2.flip(frame, 1)

    poses = engine.infer(frame)
    tracks = update_pose_tracks(tracks, poses)

    for t in tracks:
        if t.age > 0:
            continue  # not matched this frame, don't draw/update stale data
        pose = t.pose
        engine.draw_skeleton(frame, pose)

        left = angle(pose.kp(L_SHOULDER), pose.kp(L_ELBOW), pose.kp(L_WRIST))
        right = angle(pose.kp(R_SHOULDER), pose.kp(R_ELBOW), pose.kp(R_WRIST))

pose.kp(index) returns (x, y) in original frame coordinates, or None when the keypoint is not confidently visible. angle(a, b, c) returns the angle at point b in degrees, or None if any point is missing. The keypoint constants in pose_engine.py follow COCO order.

Limitations

  • Results apply only to the test setup in Results. A USB camera on the Raspberry Pi 5 was not tested.
  • Frigate has no pose estimation support, so this project is a Python pipeline.
  • Use one app per camera. A USB webcam or a video file is documented.
  • The rep counter reads the elbow angle only. It does not count squats or leg work, and its feedback is one angle check, not coaching or injury advice. It counts any elbow bend-and-extend cycle, so other arm movement can add reps.
  • The fall alert is on screen, plus one line in the terminal; there is no notification. It stays for 5 seconds, or until you press r.
  • Fall detection can miss a slow collapse or slide, because the rule needs a fast hip drop: see Fall detection.
  • Fall detection cannot flag a person whose shoulders or hips are not visible to the camera, such as a person hidden by furniture or outside the frame.
  • Fall detection can miss a fall that leaves the torso at 70° or less from vertical, such as a fall toward or away from the camera.
  • The fall speed is relative to the frame height, so it depends on how far the person is from the camera: see Fall detection.
  • Tracking has no re-identification: see Tracking across frames. When two people overlap heavily, YOLOv8n-pose can return one merged skeleton for a few frames (about 0.3 seconds in the sample clip). The tracker keeps IDs stable across it, but the merged skeleton’s joints belong to two people, and its torso angle has no meaning.
  • All thresholds are constants in the scripts, not command-line options.

Privacy

The three scripts process each frame in memory and show the result on screen. They do not write video or images to disk and do not import a networking library. The rep counter and fall detection also print lines to the terminal.

Get consent from everyone who appears in frame. Use your own footage. Stage falls only onto a crash mat with consenting adults, or use a video file instead.

Troubleshooting

The runtime does not see the NPU, so the apps cannot load the model. Check the NPU from the runtime side first, then see AI HAT+ troubleshooting.

The apps draw with cv2.imshow, which needs a display. Run them from a terminal in the Raspberry Pi 5 desktop session.

The app cannot open that camera. Check that the webcam is connected, that the index is right and that no other app holds it. Only one app can use a camera at a time, so press q in the running app first.

Pass the camera index: python fitness_coach.py 1.

The path you passed is not a camera index and not a readable video file. Check the path.

The apps ask for a 1280 × 720 OpenCV window, which can extend past the edge of the Raspberry Pi 5 desktop. Drag the window by its title bar, or resize it from a corner.

By design, the alert holds for 5 seconds, and the person cannot raise another alert until they stand upright again, so it does not repeat while they are still on the ground. Press r to clear it sooner.

Check that the person’s shoulders and hips are visible to the camera and that the fall is fast enough for the rule in Fall detection.

Each person raises one alert per fall and has to stand upright again (torso below 40°) before the app can flag another fall for them. Press r to re-arm everyone.

When two people overlap heavily, the model can return one merged skeleton for a few frames; the IDs return to the right people afterward. Wait a moment, or give the people more space in frame.

Video files loop by design.

Frequently asked questions

No. The apps load a .dxnn model through dx_engine, so they need a DEEPX NPU, such as the one on the Sixfab AI HAT+ (DEEPX DX-M1M). The Raspberry Pi AI HAT+ is a different product with a different NPU.

Next steps

License and credits

  • The code is licensed under the MIT License. The model is the stock Ultralytics YOLOv8n-pose, trained on COCO, under AGPL-3.0. Each model file’s license and details are in the release notes at https://github.com/sixfab/sixfab-dx-examples/releases/tag/pose-estimation-v1.0.0.
  • Keypoints use the COCO keypoint format. Keypoint order follows the Ultralytics pose docs.
  • “Fruit Ninja” is a third-party game name. This project’s game is Fruit Ninja-style, not affiliated with it.