๐Ÿ’ช Muscle Mirror: 22 muscles, live, over your camera

Muscle Mirror turns your Mac's camera into an anatomical mirror. Apple Vision tracks your body and 22 color-coded muscle overlays move with you, so people who train, rehab or study anatomy can see each muscle and compare their left and right sides.

By Dennis Bruijn ยท ยท 9 min read ยท #projects #apple #macos #swift #swiftui #apple-vision

Anatomy books are great until you try to find your infraspinatus with your own eyes. So I built a mirror that knows the map: you step in front of the camera, raise an arm, and the deltoids, biceps and forearm flexors raise with it, each in its own color, with fiber lines and a little label. Turn around and the back set takes over. It all runs on your Mac, and there is no network code in the app.

The Muscle Mirror window with the sidebar controls on the left and a mannequin on the black mirror pane, covered in translucent color-coded front muscles, white fibers, pill labels and a green skeleton

Watch the 30-second Muscle Mirror explainer

The explainer runs 30 seconds: keypoints, the 22 muscles blooming by group, live tracking, the turn-around, calibration, left and right peaks and recording. Mockup rebuilt from source with Montage.

Vision body pose on every frame, with optical flow so the overlays slip less

Every camera frame goes through VNDetectHumanBodyPoseRequest. The app follows 15 joints (nose, neck, hip center, shoulders, elbows, wrists, hips, knees and ankles) and ignores any joint below 0.3 confidence. From those 15 points it draws 22 muscles in 5 regions, each one a translucent shape with an outline, fiber lines and a short label. The shapes live in body-relative coordinates, so they follow you instead of sticking to the screen.

Front view of a mannequin with all front muscles filled in color, white fiber lines, labels such as Pec major, Biceps, Obliques and Quads, the green skeleton and live values in the Compare left / right grid

Front view, all muscles. Mockup rebuilt from source with Montage.

The front view draws 11 muscles and the back view 13. The upper trapezius and middle deltoid are in both, which is how 11 + 13 adds up to 22 without anybody growing a spare shoulder.

RegionFront viewBack view
Shoulders & chestPectoralis major, anterior deltoid, middle deltoid, serratus anteriorMiddle deltoid, posterior deltoid
ArmsBiceps brachii, forearm flexorsTriceps brachii, forearm extensors
BackUpper trapeziusUpper trapezius, middle trapezius, lower trapezius, rhomboids, infraspinatus & teres, latissimus dorsi
CoreRectus abdominis, external oblique
LegsQuadriceps, adductorsGluteus maximus, hamstrings, gastrocnemius

How the mirror knows you turned around

There's no magic: on Auto, it checks whether Vision can see your nose or an eye. No face means you're showing your back. The trick is not flipping the moment you blink or tilt your head, so the facing signal is averaged and only switches above 0.7 or below 0.3. This is the actual code from Pose.swift:

// Hysteresis so the front/back view doesn't flicker when the face is briefly lost.
if let pose {
    frontness += ((pose.facesCamera ? 1 : 0) - frontness) * 0.15
    if frontness > 0.7 { facesCamera = true } else if frontness < 0.3 { facesCamera = false }
}

Here it is in a box, using the same numbers. One tick is one frame with a pose. Hide the face for a few frames and watch the bar dip without the view flipping; hide it for good and it switches to the back set.

<style>
  body { margin: 0; padding: 16px; background: #000; color: #fff; font: 14px/1.4 system-ui, sans-serif; }
  .row { display: flex; gap: 8px; flex-wrap: wrap; }
  button { background: #111; color: #fff; border: 1px solid #333; border-radius: 8px; padding: 6px 12px; font: inherit; cursor: pointer; }
  button[aria-pressed="false"] { border-color: #f05138; }
  .bar { position: relative; height: 14px; margin: 16px 0 6px; border: 1px solid #333; border-radius: 7px; overflow: hidden; }
  .fill { position: absolute; inset: 0 auto 0 0; background: #3d85f2; }
  .tick { position: absolute; top: 0; bottom: 0; width: 2px; background: #fff; opacity: .6; }
  small { color: #888; }
  .view { margin: 14px 0 0; font-size: 20px; font-weight: 600; }
</style>
<div class="row">
  <button id="face" aria-pressed="true">Face visible</button>
  <button id="blink">Look away for 3 frames</button>
</div>
<div class="bar"><div class="fill" id="fill"></div><div class="tick" style="left:30%"></div><div class="tick" style="left:70%"></div></div>
<small>frontness <span id="val">1.00</span> ยท front above 0.7 ยท back below 0.3</small>
<p class="view">View: <span id="view">Auto (front)</span></p>
<script>
  const $ = (id) => document.getElementById(id);
  let frontness = 1, facesCamera = true, face = true, blink = 0;
  $('face').onclick = () => {
    face = !face;
    $('face').setAttribute('aria-pressed', String(face));
    $('face').textContent = face ? 'Face visible' : 'Face hidden';
  };
  $('blink').onclick = () => { blink = 3; };
  setInterval(() => {
    const seen = face && blink === 0;
    if (blink > 0) blink--;
    frontness += ((seen ? 1 : 0) - frontness) * 0.15;
    if (frontness > 0.7) facesCamera = true; else if (frontness < 0.3) facesCamera = false;
    $('fill').style.width = (frontness * 100) + '%';
    $('val').textContent = frontness.toFixed(2);
    $('view').textContent = facesCamera ? 'Auto (front)' : 'Auto (back)';
  }, 1000 / 30);
</script>

Three frames without a face only take the value from 1.00 down to about 0.61, so the view stays put. It takes eight frames in a row before it drops under 0.3 and the back muscles are drawn in:

The mannequin turns away from the camera, the front muscles fade out, View changes to Auto (back) and the back muscles are drawn in, then the mannequin turns back and the front set returns

Turning around and back again, 8 seconds. Mockup rebuilt from source with Montage.

Back view of the mannequin with the trapezius in purples, rhomboids in magenta, lats in green, glutes and hamstrings in warm tones and calves in green, with View set to Auto (back)

The back set, picked automatically. Mockup rebuilt from source with Montage.

If you'd rather not be second-guessed by your own nose, set View to Front or Back and it stays there.

Why the overlays don't wobble

Detections alone let the overlays slip, and a slipping pectoral is not a good look. So with Optical-flow tracking on, Vision also computes dense optical flow on a 384 px wide copy of each frame. Every joint first moves with the image motion, then goes 35% of the way toward the fresh detection:

/// How far each frame moves a flow-predicted joint toward its detection.
private let detectionGain: CGFloat = 0.35

track.point = predicted.lerp(to: detected, detectionGain)

A joint the detector misses is held for 1 second with flow, or 0.25 seconds without. Turn flow off and each joint goes through a One Euro filter instead.

Per-muscle calibration, saved per side

The muscle templates are averages, and nobody is average. So any single muscle can be fitted to you:

  1. Pick one muscle under Show (the sidebar then shows its origin and insertion).
  2. Press Space to freeze the frame.
  3. Turn on Adjust outline and drag the handles onto your own anatomy.

Calibration with Show set to Biceps brachii, Adjust outline on, the biceps outline drawn with drag handles, one handle being dragged and a Frozen badge in the corner

Dragging the biceps handles on a frozen frame. Mockup rebuilt from source with Montage.

The nice part is where the offsets live. They are stored per side, in the local space of the body part the muscle belongs to (neck, shoulder, a torso patch or a limb segment, scaled by shoulder width). That means the adjusted outline keeps following you after you unfreeze, instead of staying glued to where you dragged it. Reset Biceps brachii (the button is named after the muscle you picked) clears one, Reset All Muscles clears the lot.

Calibration is the only thing the app keeps between sessions, in UserDefaults under calibrationOffsets. Every other control starts at its default each time you open it.

Five joint metrics, left versus right, and โŒ˜R to record it

This is the bit for anyone who suspects one side is lazier than the other. The Compare left / right grid measures 5 metrics on each side, live (Now) and as the highest value since you last pressed Reset Peaks (Peak). The L โˆ’ R column shows the difference. Left and right are your own sides, not the sides of the image.

MetricWhat it measures
Arm elevationAngle between the upper arm and the trunk. 0ยฐ is the arm at your side, 180ยฐ is overhead.
Elbow flexionAngle at the elbow. 0ยฐ is a straight arm.
Shoulder heightShoulder height above the neck along the trunk, as a percentage of shoulder width. Shows shrugging and tilt.
Leg elevationAngle between the thigh and the trunk. 0ยฐ is standing straight.
Knee flexionAngle at the knee. 0ยฐ is a straight leg.

A lateral raise with joint-angle tags at the shoulders and elbows, the Compare left / right grid filled with Now and Peak values and a REC 00:42 badge in the corner of the mirror

A lateral raise with joint-angle tags and a recording in progress. Mockup rebuilt from source with Montage.

The math is pleasantly small. Comparison.swift takes two vectors, normalizes them and takes the arc cosine of their dot product. Arm elevation compares the trunk (neck to mid-hip) with the upper arm; elbow flexion compares the upper arm with the forearm. Drag the elbow or the wrist below, then hit Reset Peaks and do it again:

<style>
  body { margin: 0; padding: 12px; background: #000; color: #fff; font: 14px/1.4 system-ui, sans-serif; }
  canvas { display: block; width: 100%; max-width: 420px; height: auto; background: #050505; border: 1px solid #222; border-radius: 10px; touch-action: none; cursor: grab; }
  table { border-collapse: collapse; margin-top: 10px; font-variant-numeric: tabular-nums; }
  th, td { padding: 2px 14px 2px 0; text-align: left; }
  th { color: #888; font-weight: 400; }
  button { margin-top: 10px; background: #111; color: #fff; border: 1px solid #333; border-radius: 8px; padding: 6px 12px; font: inherit; cursor: pointer; }
</style>
<canvas id="c" width="420" height="320"></canvas>
<table>
  <tr><th></th><th>Now</th><th>Peak</th></tr>
  <tr><td>Arm elevation</td><td id="aNow"></td><td id="aPeak"></td></tr>
  <tr><td>Elbow flexion</td><td id="eNow"></td><td id="ePeak"></td></tr>
</table>
<button id="reset">Reset Peaks</button>
<script>
  const c = document.getElementById('c'), g = c.getContext('2d');
  const neck = { x: 150, y: 50 }, hip = { x: 150, y: 270 }, shoulder = { x: 200, y: 62 };
  const UPPER = 95, FORE = 85;
  let elbow = { x: 200, y: 62 + UPPER }, wrist = { x: 200, y: 62 + UPPER + FORE };
  let peakA = 0, peakE = 0, drag = null;
  const sub = (a, b) => ({ x: a.x - b.x, y: a.y - b.y });
  const len = (v) => Math.hypot(v.x, v.y);
  // Same idea as angle(_:_:) in Comparison.swift: acos of the dot of two unit vectors, in degrees.
  const angle = (a, b) => Math.acos(Math.max(-1, Math.min(1, (a.x * b.x + a.y * b.y) / (len(a) * len(b))))) * 180 / Math.PI;
  const toward = (from, to, r) => { const d = sub(to, from), l = len(d) || 1; return { x: from.x + d.x / l * r, y: from.y + d.y / l * r }; };
  const deg = (v) => Math.round(v) + 'ยฐ';
  function line(a, b, color, width) { g.strokeStyle = color; g.lineWidth = width; g.lineCap = 'round'; g.beginPath(); g.moveTo(a.x, a.y); g.lineTo(b.x, b.y); g.stroke(); }
  function dot(p) { g.fillStyle = '#2ea44f'; g.beginPath(); g.arc(p.x, p.y, 6, 0, Math.PI * 2); g.fill(); }
  function render() {
    const trunkDown = sub(hip, neck);
    const a = angle(trunkDown, sub(elbow, shoulder));
    const e = angle(sub(elbow, shoulder), sub(wrist, elbow));
    peakA = Math.max(peakA, a); peakE = Math.max(peakE, e);
    g.clearRect(0, 0, c.width, c.height);
    line(neck, hip, '#333', 3);
    line(neck, shoulder, '#2ea44f', 2);
    line(shoulder, elbow, 'rgba(61,133,242,.55)', 22);
    line(elbow, wrist, 'rgba(240,81,56,.45)', 16);
    line(shoulder, elbow, '#2ea44f', 2);
    line(elbow, wrist, '#2ea44f', 2);
    [neck, shoulder, elbow, wrist].forEach(dot);
    g.fillStyle = '#fff'; g.font = '13px system-ui, sans-serif';
    g.fillText(deg(e), elbow.x + 12, elbow.y - 8);
    g.fillText(deg(a), shoulder.x + 12, shoulder.y - 6);
    document.getElementById('aNow').textContent = deg(a);
    document.getElementById('eNow').textContent = deg(e);
    document.getElementById('aPeak').textContent = deg(peakA);
    document.getElementById('ePeak').textContent = deg(peakE);
  }
  function point(ev) { const r = c.getBoundingClientRect(); return { x: (ev.clientX - r.left) * c.width / r.width, y: (ev.clientY - r.top) * c.height / r.height }; }
  c.addEventListener('pointerdown', (ev) => {
    const p = point(ev);
    drag = len(sub(p, elbow)) < len(sub(p, wrist)) ? 'elbow' : 'wrist';
    c.setPointerCapture(ev.pointerId);
  });
  c.addEventListener('pointermove', (ev) => {
    if (!drag) return;
    const p = point(ev);
    if (drag === 'elbow') {
      const forearm = sub(wrist, elbow);
      elbow = toward(shoulder, p, UPPER);
      wrist = { x: elbow.x + forearm.x, y: elbow.y + forearm.y };
    } else {
      wrist = toward(elbow, p, FORE);
    }
    render();
  });
  c.addEventListener('pointerup', () => { drag = null; });
  document.getElementById('reset').onclick = () => { peakA = 0; peakE = 0; render(); };
  render();
</script>

Turn on Joint angles and the app draws arm elevation, elbow flexion and knee flexion right next to the joints on the video. A biceps curl reads from about 8ยฐ to about 138ยฐ and back:

Watch one biceps curl: the arm muscles bend with the forearms while the elbow-flexion tags and the left and right readouts count up and back down

One biceps curl with live elbow flexion on both sides, 6 seconds. Mockup rebuilt from source with Montage.

And when you want proof for later: โŒ˜R records the mirror exactly as you see it, overlays and all, to an H.264 .mov in ~/Movies. Press โŒ˜R again to stop, and Show in Finder takes you to the file. Each frame is re-rendered at camera resolution with ImageRenderer, minus the calibration handles, and appended to an AVAssetWriter. Nothing is written unless you press the shortcut.

Under the hood

Muscle Mirror is a single Swift package with one executable target, written in SwiftUI. It builds with a Swift 6 toolchain and runs on macOS 15 or later.

PieceWhat it does
AVFoundationCameraModel runs an AVCaptureSession at 1920ร—1080 when the camera supports it: the built-in camera, an external webcam or Continuity Camera.
Apple VisionBody pose on every frame, plus dense optical flow on a 384 px copy.
SwiftUI CanvasMirrorView draws the frame, fills, outlines, fibers, labels, skeleton, angle tags and calibration handles.
AVAssetWriterThe H.264 recording.
Swift Package ManagerThe build, wrapped into an app bundle by a script.

Here is the whole pipeline, camera to movie file:

Camera โ”€โ”€โ”ฌโ”€โ”€> Vision body pose โ”€โ”€โ”
         โ””โ”€โ”€> Optical flow โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€> PoseSmoother โ”€โ”€โ”ฌโ”€โ”€> MuscleTemplates โ”€โ”€> MirrorView (Canvas) โ”€โ”€> Recorder (.mov)
                                                     โ””โ”€โ”€> ComparisonModel (angles and peaks)

Each muscle in MuscleTemplates is a set of outline points in a local body space, scaled by shoulder width. Most limb muscles are spindles, widest at the belly, which is roughly how muscles feel about themselves too.

Sources/MuscleMirror/
โ”œโ”€โ”€ ContentView.swift    app entry, window, toolbar, sidebar and comparison grid
โ”œโ”€โ”€ MirrorView.swift     overlay style and the Canvas renderer
โ”œโ”€โ”€ Muscles.swift        the 22 muscles, regions, colors and front/back templates
โ”œโ”€โ”€ CameraModel.swift    AVFoundation capture and the frame processor
โ”œโ”€โ”€ Pose.swift           Vision pose detection, smoothing and the One Euro filter
โ”œโ”€โ”€ OpticalFlow.swift    downscaled Vision optical flow
โ”œโ”€โ”€ Calibration.swift    per-side outline offsets in UserDefaults
โ”œโ”€โ”€ Comparison.swift     2D joint-angle metrics and peaks
โ”œโ”€โ”€ Recorder.swift       H.264 recording to ~/Movies
โ””โ”€โ”€ Geometry.swift       point and vector helpers

One small gotcha worth knowing: swift run doesn't work. macOS only grants camera access to an app that has a camera usage description, so a script builds the binary, wraps it with Support/Info.plist into build/MuscleMirror.app and signs it ad hoc. Building from source looks like this:

scripts/build-app.sh release --open   # build, bundle as build/MuscleMirror.app, sign ad hoc and open
scripts/build-app.sh debug --open     # faster, unoptimized build

About those screenshots

You may have noticed nobody in this post has a face. That's on purpose: no image here is a camera capture. The window, the overlays and the readouts are rebuilt in Montage, my shared Remotion studio, from the app's Swift sources. The muscle geometry and angle math are ported from Muscles.swift, Geometry.swift and Comparison.swift, and the body is a synthetic, faceless mannequin posed from joint positions.

The Muscle Mirror icon: a silver mirror ellipse with a green skeleton and the pec, deltoid and biceps from the app's own templates, filled on the left half and outlined on the right

The icon comes from the same templates: a silver mirror ellipse, a green skeleton, and the pec, deltoid and biceps drawn by the app's own shapes, filled on one half and outlined on the other. Left versus right, even in the icon.

What's not there yet

Muscle Mirror is at v1.0.0. It's honest about what a webcam can and can't do:

  • Estimates only. Muscle positions come from 15 tracked joints and average templates. They're approximate, even after calibration.
  • 2D angles. Angles are measured in the image plane, so they're most accurate when you move parallel to the camera. Turning toward or away from it foreshortens the limbs.
  • No activation. A camera can't tell whether a muscle is working. The overlays show where a muscle is, not how hard it's contracting.
  • Front or back from your face. A side-on stance can show the wrong set. View set to Front or Back overrides it.
  • One person. Only the first person Vision detects is tracked.
  • Video only. Recordings have no audio track.
  • Ad-hoc signed. The build is signed for your own Mac and isn't notarized.

There are no automated tests yet either; changes are checked by standing in front of a camera and checking that the overlays follow, Auto flips when you turn away, and elbow and knee flexion read close to 0ยฐ when your arms and legs are straight. On the roadmap:

  • Unit tests for the angle metrics, the smoother and the template geometry
  • Move the package to Swift 6 language mode
  • Save the sidebar settings between sessions, the way calibration already is
  • Sign with a Developer ID and notarize, so the app can be shared

The other things I've built are on the projects page.

Curious about the source? It's private, but access can be granted to anyone interested in contributing. Get in touch.