37. Reading people and things
On this page
- A pose as a skeleton: BodyTracker
- The person as pixels: PersonSegmenter and SubjectSegmenter
- Hands as joints: HandTracker
- Putting it together: a chronophotograph
- More of a person: a head's pose and the body in space
- Which way a head is turned: FaceTracker
- A body in meters: BodyTracker3D
- Reading outlines and print: contours, rectangles, text, and codes
- A frame as vector shapes: ContourDetector
- Paper and screens: RectangleDetector
- Words off a page: TextRecognizer
- Codes a phone can make: BarcodeScanner
- Following things from frame to frame: @Steadied, ObjectTracker, and TrajectoryTracker
- The same things in the next frame: @Steadied
- A patch you point at: ObjectTracker
- Things that fly: TrajectoryTracker
- Models of your own
- A click cuts it loose: PointSegmenter
- Bringing your own model: ModelTracker
- Depth that holds still: DepthTracker
- A clip read whole for an export: DepthClip
- How far, in meters: MetricDepthTracker
- Words as numbers: ConceptTracker
- Where this comes from
- Go deeper
A tracker can find the people in a picture. It hands back a body as a skeleton of named joints, and a hand down to its fingertips. It also lifts a person out of the frame as a silhouette. The steps read all three from a film that ships with Ollin, so nothing here needs a camera. They end on the chronophotograph above, a dancer's poses laid over one another on one dark plate. Beyond it, trackers read a head's pose, a body in space, outlines, and print. They follow one thing across frames, and they run models you bring.
A pose as a skeleton: BodyTracker
Chapter 36 attached a tracker to a feed and read its results in draw(). BodyTracker attaches the same way, and what it finds is people. Each one comes back as a Body, a pose of up to 19 named joints. They are the nose, eyes, and ears, the neck, and then the shoulders, elbows, wrists, hips, knees, and ankles. The feed here is the bundled dance film, so the sketch has someone to read on any Mac:
import Ollin
import OllinSamplePhotos
import OllinVideo
import OllinVision
final class Skeleton: Sketch {
let film = try! VideoPlayer(url: SampleClip.dance.url) // the bundled clip is always there
lazy var bodies = BodyTracker(film)
override func setup() {
film.loops = true
film.play()
}
override func draw() {
background(.black)
guard let rect = drawFrame(film) else { return }
stroke(.orange); strokeWeight(4)
for body in bodies.bodies {
for (a, b) in body.bones(in: rect) { drawLine(a, b) }
}
}
}Run it and an orange stick figure dances on top of the dancer. bodies.bodies is the list of people found in the newest frame. body gives one skeleton as pairs of canvas points, a pair for each bone. They are already mapped into the rectangle the frame was drawn in, by the same in: helpers Chapter 36 used for a face.
The figure shows three frames of the film with what the tracker found. Joints it can't see, or is unsure of, are left out, often the legs of someone at a desk. A bone is drawn only when both of its ends were found. So the skeleton you get is what the camera saw. Each body also carries a confidence, a number from 0 to 1 for how sure the tracker is.
Every joint has a name, and body asks for one as a canvas point. It answers nil when that joint was not found. Gestures come from arithmetic on a few joints:
// in draw(), with `rect` from drawFrame:
if let body = bodies.bodies.first,
let wrist = body.point(.rightWrist, in: rect),
let shoulder = body.point(.rightShoulder, in: rect),
wrist.y < shoulder.y {
drawText("arm up", 40, 60) // y grows downward, so smaller is higher
}A hand and a face have named parts too. The figure shows the parts of all three, and this chapter reads the hand two steps on and the face after the finished sketch:
The body tracker is one of the heavier trackers, so it wants Apple silicon. Where it cannot run, bodies says why, as Chapter 36 showed for every tracker.
The person as pixels: PersonSegmenter and SubjectSegmenter
The joints reduce a person to a few points. Sometimes you want the person's pixels instead, to cut them out, glow them, or stamp them. Splitting a picture into its subject and the rest is called segmentation. PersonSegmenter finds the people in the frame. SubjectSegmenter finds whatever stands out, whether or not it's a person. Both hand back the same two pictures:
lazy var people = PersonSegmenter(film)
override func draw() {
background(.black) // or anything: this is the new backdrop
guard let rect = film.fittedRectangle(in: bounds) else { return }
if let cutout = people.cutout { drawImage(cutout, in: rect) }
}The block never draws the frame, since that would cover the new backdrop. film answers where drawFrame would have put it, so the cutout lands in the same place.
matte is a soft white silhouette, and its alpha says how much each pixel belongs to the subject. tint(_:) then turns it into a shadow, a glow, or a flat colored figure. cutout is the frame's own pixels with the background gone, ready to draw over whatever your sketch has already drawn. Both come back as ordinary Images, so draw them into the same rectangle as the frame and they land on the picture.
Stamp the matte every frame without clearing and you have a trail of yourself. It is Chapter 19's noClear, with a person as the brush. PersonSegmenter takes a quality: that trades edge detail for speed. On a feed it starts at .balanced, and .accurate draws a cleaner edge for more work on each frame. SubjectSegmenter adds a count of how many separate subjects it found. While nothing in the picture stands out, count is 0 and matte and cutout are nil. Both need Apple silicon, like the body tracker.
Hands as joints: HandTracker
A body's wrist says where a hand is. HandTracker says what the hand is doing. It finds up to two hands, and maxHandCount: asks for more. Each is a Hand of 21 joints, the wrist plus four joints per finger, base to tip.
The figure reads two pictures. On the left are two palms held close, with all 21 joints of each. On the right is the dancer, whose hands are a small part of the frame. Hands that small are still found, though not in every frame.
lazy var hands = HandTracker(film)
// in draw(), after `guard let rect = drawFrame(film) else { return }`
stroke(.orange); strokeWeight(3)
for hand in hands.hands {
for (a, b) in hand.bones(in: rect) { drawLine(a, b) }
if let tip = hand.point(.indexTip, in: rect) { drawCircle(tip.x, tip.y, 8) }
}hand is a fingertip as a canvas point. finger( gives one finger as a polyline, and bones(in: rect) the whole skeleton as line segments. HandJoint.tips lists the five fingertips, for a loop over all of them. Gestures come from arithmetic on a few joints, as they did for the body. Five spread tips are an open hand. The index tip alone is a cursor that needs no mouse. Thumb tip near index tip is a pinch:
if let thumb = hand.point(.thumbTip, in: rect),
let index = hand.point(.indexTip, in: rect),
let wrist = hand.point(.wrist, in: rect),
let knuckle = hand.point(.indexMCP, in: rect),
thumb.distance(to: index) < wrist.distance(to: knuckle) * 0.3 {
drawText("pinch", 40, 60)
}The block measures the gap against the hand's own size, from the wrist to the first knuckle of the index finger. So a pinch reads the same near the camera and far from it.
Putting it together: a chronophotograph
The finished sketch is the picture at the top. A chronophotograph is a photograph that holds several moments of one motion on a single plate. This one takes an exposure of the dancer twice a second. Each exposure is the silhouette, in a color that turns with time, with the skeleton over it. Between exposures, every fingertip leaves a spark. Make MySketches/:
import Ollin
import OllinSamplePhotos
import OllinVideo
import OllinVision
final class Chronophotograph: Sketch {
override var canvasSize: CanvasSize { .size(1620, 1080) }
let film = try! VideoPlayer(url: SampleClip.dance.url)
lazy var bodies = BodyTracker(film)
lazy var people = PersonSegmenter(film, quality: .accurate)
lazy var hands = HandTracker(film)
let plate = Color(hex: 0x07080C)
override func setup() {
film.loops = true
film.play()
noClear()
background(plate)
}
override func draw() {
// A faint veil each frame, so old exposures sink into the plate.
blendMode(.normal)
noStroke()
fill(plate.withAlpha(0.009))
drawRect(0, 0, width, height)
// The plate slides: one pass from left to right takes eight seconds.
let pass = (time / 8).truncatingRemainder(dividingBy: 1)
let side = height * 0.92
let frame = Rectangle(x: lerp(-side * 0.22, width - side * 0.78, pass),
y: (height - side) / 2, width: side, height: side)
blendMode(.add) // light adds up on a plate
// Every frame, a spark at each fingertip: the hands leave paths of light.
fill(Color(hex: 0xFFE2A8, alpha: 0.6))
for hand in hands.hands {
for tip in HandJoint.tips {
if let p = hand.point(tip, in: frame) { drawCircle(p.x, p.y, 2 * scale) }
}
}
// Twice a second, one exposure of the whole figure.
guard frameCount % 30 == 0 else { return }
if let matte = people.matte {
tint(Color(hue: 0.55 + pass * 0.4, saturation: 0.75, brightness: 1).withAlpha(0.32))
drawImage(matte, in: frame)
noTint()
}
noFill()
stroke(Color(white: 1, alpha: 0.7))
strokeWeight(1.8 * scale)
if let body = bodies.bodies.first {
for (a, b) in body.bones(in: frame) { drawLine(a, b) }
}
}
}The sketch uses the skeleton, the person as pixels, and the fingertips, on a canvas that keeps its marks. noClear() and the veil are the motion brush's, from Chapter 36. Each frame lays a rectangle of the plate's color over everything, at an alpha of 0.009. So an exposure takes a few seconds to sink away.
A real plate holds still while a walker crosses it. The dancer stays near the middle of the film, so the sketch slides the plate instead. pass runs from 0 to 1 every eight seconds, and lerp turns it into the left edge of a square that travels across the canvas. That square is where the film's frame lands. Every in: frame helper maps into it, and the film itself is never drawn.
blendMode(.add) makes the marks add their light, as exposures do on a plate. Where two silhouettes overlap, the overlap is brighter than either. The veil is drawn first, under .normal, because it has to darken.
The sparks are drawn on every frame. Each is a small circle on one of HandJoint.tips, and a hand the tracker lost leaves none. The plate keeps sliding under them. So a hand that holds still draws a level dotted line, and a hand that swings draws a curve.
The guard lets the rest of draw() run on one frame in thirty, which is twice a second. The matte is tinted with a hue that follows pass, so the color of a silhouette says when it was taken. The segmenter is made with quality: .accurate, which gives the silhouettes their clean edge. bodies.bodies.first is the one dancer, and an exposure with no body found is a silhouette alone.
Then make it yours:
- Draw only the bones, in one pale color, with no silhouette under them. The plate then holds a figure reduced to lines, as the first plates of this kind did.
- Take an exposure every six frames, not every thirty, and slow the plate. The figures crowd into a comb, the way a runner's legs do in a photograph of this kind.
- Stamp
people.cutoutwhere the sketch stamps the tinted matte, under.normal. The plate then fills with the dancer's own pixels.
To stand on the plate yourself, hand the trackers a camera, with the film as its stand-in. Replace the film property with Chapter 36's Camera.or, and take the two film lines out of setup():
let film = Camera.or {
let clip = try! VideoPlayer(url: SampleClip.dance.url)
clip.loops = true
clip.play()
return clip
}Rehearsed on the film, the sketch exports. An export hands the trackers each frame of the film before it draws the frame that shows it, so every run reads the same frames:
swift run OllinLive MySketches/Chronophotograph.swift --export-video dance.mp4 --seconds 16Sixteen seconds is two passes of the plate. A live take is kept by recording the window, as Chapter 36 said of the brush.
More of a person: a head's pose and the body in space
The chronophotograph read a body as points on the picture. Two more trackers read a person. One reads a face and which way the head is turned, and the other places a body's joints in space.
Which way a head is turned: FaceTracker
Chapter 36 drew a box and a jaw line from FaceTracker. It finds every face with 76 landmark points and a head pose. It is for a sketch that answers a look. A scene can swing as a head turns, and a mask can sit on a face. Finding the landmarks of a face is a long-standing job of computer vision, and Apple's Vision framework does it here.
The points come in named regions: .faceContour, the brows, the eyes, .nose, the lips, and the pupils. Each region comes back ready to drawPolyline, so a face overlay is a short loop. The head pose is three angles in radians. roll tips the head toward a shoulder, yaw turns it left or right, and pitch nods it up or down. The figure prints them in degrees. The first face looks almost straight at the camera, and the second is turned 77 degrees away.
lazy var faces = FaceTracker(film)
// in draw(), after `guard let rect = drawFrame(film) else { return }`
if let face = faces.faces.first {
noFill(); stroke(.orange); strokeWeight(2)
drawPolyline(face.landmarks(.outerLips, in: rect))
let turn = face.yaw / (.pi / 2) // 0 facing the camera, 1 or -1 in full profile
drawCircle(width / 2 + turn * 300, 80, 20) // a dot the head steers
}A quarter turn is .pi / 2 radians, so dividing yaw by it gives a value from -1 to 1 to steer by. FaceTracking draws every region, and FaceAlign turns the picture so the face holds still. The reference lists the regions.
A body in meters: BodyTracker3D
BodyTracker3D reads a person as positions in space. From the same flat picture it places 17 joints in meters. It is for a sketch that needs to know how far away someone stands, or what a pose looks like from the side. Placing a pose in space from one picture is the work of a trained model, and Apple's Vision framework runs it.
You read it in whichever of three spaces suits what you're drawing. point(_:in:) and bones(in:) behave like the flat tracker's, for an overlay on the feed. position(_:) and the no-argument bones() give meters with the pelvis at the origin. Plotting (z, y) then draws the person from the side and (x, z) from above, views no camera was at. And cameraRelativePosition( gives meters from the lens, which makes a joint's z its distance. body.distance is the shortcut for the whole person's.
lazy var pose = BodyTracker3D(film)
// in draw(), with `rect` from drawFrame and `side` a spot to draw the side view:
if let body = pose.body {
for (a, b) in body.bones(in: rect) { drawLine(a, b) } // over the feed
for (a, b) in body.bones() { // seen from the side
drawLine(side + Vector2(a.z, -a.y) * 200, side + Vector2(b.z, -b.y) * 200)
}
}Examples/ draws that side view in an inset beside the feed. The 3D tracker differs from the flat one in two ways. It follows only one person, so body is a single optional rather than a list. It also places the whole skeleton every time, guessing at the joints it can't see, rather than leaving them out. There's also body.height, an estimate of how tall the person is. heightEstimation says whether that came from real depth data or from scaling the skeleton to a standard height. Scaling is all a plain webcam can offer.
Reading outlines and print: contours, rectangles, text, and codes
The chronophotograph read a person in motion. Much of what a camera sees is not a person, and it holds still. It may be a hand held up to it, a page, a card, or a code on a phone. These trackers read the flat, high-contrast things in a picture, and they read them in a still frame as well as a moving one.
The blocks from here on name their source feed. It stands for any feed: this chapter's film, a camera, or Chapter 36's Camera.or, which gives whichever there is.
A frame as vector shapes: ContourDetector
ContourDetector traces the boundaries between dark and light into closed vector outlines. It hands them back as Chapter 15's Shapes, holes and all. It is for turning a camera into a live vectorizer, with every shape ready for a boolean, a hatch, or a plotter. Following the border of a light region pixel by pixel is a classic of computer vision. It comes from Satoshi Suzuki and Keiichi Abe's border following of 1985. Apple's Vision framework does the tracing here.
The picture on the left is one of the bundled photographs, two palms lit against a black ground. A tracer wants that, one clear boundary between light and dark. On the right are the shapes the detector traced. The creases of each palm come back as holes inside the hand, and the finger joints break the fingers into pieces.
lazy var outlines = ContourDetector(feed, detectsDarkOnLight: false)
// in draw(), after `guard let rect = drawFrame(feed) else { return }`
noFill(); stroke(.orange)
for shape in outlines.shapes(in: rect) { drawShape(shape) }The subject here is the light half of the picture, so the block asks for detectsDarkOnLight:. Get that backwards and you trace the room instead of the hands. Once a camera frame is a list of Shapes, everything from Chapter 15 applies. Boolean it, offset it, hatch it, warp it, or export it as SVG for a plotter.
Paper and screens: RectangleDetector
RectangleDetector finds rectangular things, a sheet of paper, a screen, a card on a desk, and reports each one's four corners. It works on them at an angle, so the corners come back in perspective rather than as an upright box. A document scanner needs that to flatten a page. It is classical computer vision, with no trained model, so it needs no Apple silicon, and Apple's Vision framework does the work.
The figure reads a photograph of a desk from above. Look at what counts as a rectangle. The trackpad and the notebook do, and so does the rim of the coffee cup, which is round.
lazy var cards = RectangleDetector(feed)
// in draw(), after `guard let rect = drawFrame(feed) else { return }`
noFill(); stroke(.green)
for card in cards.rectangles { drawPolygon(card.corners(in: rect)) }A DetectedRectangle also offers center(in:), bounds(in:) for the upright box around those corners, and a confidence. The initializer takes limits on aspect, size and confidence, for when you want to be fussy about what counts as one.
Words off a page: TextRecognizer
TextRecognizer reads text off the feed with Apple's on-device text recognition. It is for a sketch that answers what is written in front of it, a sign, a page, a note held up to the camera. It runs on a model every Mac already has. The boxes on the notebook's cover in the figure above are its five lines.
lazy var reader = TextRecognizer(feed, quality: .accurate)
// in draw(), after `guard let rect = drawFrame(feed) else { return }`
noFill(); stroke(.green)
for line in reader.lines { drawRect(line.bounds(in: rect)) }reader.lines is one DetectedText per line, each carrying its text and its bounds(in:), and reader.text joins every line into a single string. The quality: argument trades speed for thoroughness. .fast keeps up with a live feed and is the default there, but it can miss small print. So the block asks for .accurate. .accurate reads more and is the default for a still image.
Codes a phone can make: BarcodeScanner
BarcodeScanner decodes barcodes and QR codes. The QR code was designed in 1994 at Denso Wave, then a division of the Japanese company Denso, to track parts in manufacturing. Now anyone can make one on a phone. That makes it a friendly way to hand a running installation some input. A DetectedBarcode gives you the decoded payload, the symbology that says which kind of code it was, and corners(in:) for where it sits. Like the rectangle detector, it needs no trained model.
lazy var codes = BarcodeScanner(feed)
// in draw():
if let text = codes.barcodes.first?.payload { drawText(text, 40, 60) }Following things from frame to frame: @Steadied, ObjectTracker, and TrajectoryTracker
A detector looks at each frame fresh and finds whatever it has a model for. It does not know that the box it found is the one it found a frame ago. Three tools carry a thing from one frame to the next. @Steadied holds a detector's findings steady, ObjectTracker follows one patch you hand it, and TrajectoryTracker finds things that fly.
The same things in the next frame: @Steadied
What a detector hands back shakes. Each frame is analyzed on its own, so a box moves a few pixels between two frames of a scene where nothing moved. A thing the detector is unsure of blinks in and out. @Steadied holds found things steady. It is for anything a sketch draws on top of a detection. That may be a frame around a face, a label on an object, or an outline on a sheet of paper. The method is called tracking by detection, and this one follows the SORT tracker of Alex Bewley and colleagues, from 2016.
The top row of the figure is the desk as the rectangle detector read it on six frames. Nothing on the desk moved between them. The notebook keeps its rectangles. The ones around the cup change on every frame, and one on the trackpad comes and goes. The bottom row is the same six frames through @Steadied, and only the notebook's rectangles are showing.
@Steadied var sheets: [DetectedRectangle] = []
lazy var detector = RectangleDetector(feed)
// in draw(), after `guard let rect = drawFrame(feed) else { return }`
sheets = detector.rectangles // as found
for sheet in sheets { drawPolygon(sheet.corners(in: rect)) } // steadyYou assign what was found every frame, and read the same things back. Each thing is matched to the one before it and smoothed. A new one shows once it has been found for a moment. One that goes missing stays for a moment, so a frame the detector misses is not a blink. A plain box waits a tenth of a second to show and stays for three tenths. A rectangle from this detector has to hold its place for a quarter of a second, and that keeps the cup's out.
It steadies any list of boxes as well, such as faces, and the labeled boxes a model of your own finds. $sheets.things gives each thing a number that stays with it for as long as it lasts. That is how a sketch keeps one color on one face. ObjectDetection and RectangleScan draw through it, and the reference has its settings.
A patch you point at: ObjectTracker
ObjectTracker follows a patch of picture from frame to frame. You give it a box, and it keeps the box on that patch as it moves. It is for following something no recognizer has heard of, the thing you clicked. Following a patch this way is called visual object tracking, a long-standing job in computer vision, and Apple's Vision framework does the work.
lazy var tracker = ObjectTracker(feed)
var view = Rectangle(x: 0, y: 0, width: 1, height: 1)
override func draw() {
guard let rect = drawFrame(feed) else { return }
view = rect
if let object = tracker.trackedObject {
noFill(); stroke(.green)
drawRect(object.bounds(in: view))
}
}
override func mousePressed() {
tracker.track(centeredAt: Vector2(mouseX, mouseY), size: 160, in: view)
}Click something and the sketch follows it. track( hands the tracker a square 160 points across around the click, mapped through view, the rectangle the frame landed in. Alongside its box, trackedObject carries a confidence that falls as the patch is hidden, leaves the frame, or moves too fast to keep up with. Fade an overlay by it, or give up below a threshold and ask for a new box.
A detector's box seeds it as well as a click does: pass a face's bounds(in: view) to track(_:in:). The ObjectTracking example does that with the bundled dance film, where nobody is there to click. One lock from the face follows the dancer's head through the turns of the dance. The face detector is asked again only when the confidence says the patch is lost.
Things that fly: TrajectoryTracker
TrajectoryTracker waits for things that fly. It is for a sketch that answers a throw, a catch, or a bounce. Rather than being pointed at something, it watches for the curve of a thrown thing. A ball tossed or a pebble bouncing then arrives on its own as a DetectedTrajectory, a run of sightings with a parabola fitted through them. Galileo showed in 1638 that a thrown thing follows a parabola, and that shape is what the tracker looks for.
The dashed line runs past the last sighting. equationCoefficients is the fitted parabola in normalized coordinates, its three numbers packed as one value, so with c holding it, y = c. Nothing stops you sampling it further, which is a guess about where the thing is going:
lazy var flights = TrajectoryTracker(feed)
// in draw(), with `view` the rectangle the frame landed in:
for arc in flights.trajectories {
drawPolyline(arc.projectedPoints(in: view)) // the path so far
let c = arc.equationCoefficients
drawPolyline(stride(from: 0.5, through: 1, by: 0.02).map { x in
VisionSpace.point(x, c.x * x * x + c.y * x + c.z, in: view)
}) // where it's headed
}VisionSpace maps a normalized point into the frame's rectangle, the same flip and scale the in: helpers do. The block samples the right half of the frame, x from 0.5 to 1, which suits a flight moving right. For your own, start from the last sighting and step the way it is moving.
The clip in the figure shows the ball only on its way up. The pale rings are where it went in the frames the tracker never saw, and the dashed curve runs through them. A parabola has only three numbers in it, so a handful of sightings is enough to follow the rest of the flight.
It asks two things of you. Hold the camera still, because a moving camera turns the whole scene into motion. And be patient, because an arc is reported only once its object has been seen minObservationCount times, ten by default. Call reset() after the scene jumps, like a clip looping back to its start, so the jump isn't read as something flying. Each arc keeps a stable id as more of it comes into view, so you can gather sightings into trails that outlive any single frame. detectedPoints(in:) gives the raw sightings, and projectedPoints( puts them on the fitted curve. The projected ones are smoother, and usually the ones to draw.
Models of your own
Every tracker so far runs on what the Mac already has. The entries below run trained models you download, whose learned numbers are called weights, and Ollin ships none. Scripts/ fetches every file they need into Models/, and the reference says how a sketch kept elsewhere finds that folder with sketchResource. Some models are worth knowing and are never fetched, for their license or their size, and the reference keeps a short list of them.
A click cuts it loose: PointSegmenter
The segmenters in the person as pixels decide for themselves what the subject is. PointSegmenter hands that decision to you. Click a thing, any thing, and it comes loose from the picture. The pick is the same matte and cutout pair, with a confidence and a bounds(in:) box. A shift-click names a point the matte must not cover, which drops a shadow the pick took along. It runs SAM 2.1, the small version of Nikhila Ravi and colleagues' 2024 model for segmenting whatever a point asks for.
lazy var picker = PointSegmenter(feed,
imageEncoderAt: encoderURL, promptEncoderAt: promptURL, maskDecoderAt: decoderURL)
picker.pick(at: Vector2(mouseX, mouseY), in: rect) // in mousePressed()
if let pick = picker.pick { drawImage(pick.cutout, in: rect) } // in draw()The three files behind encoderURL, promptURL, and decoderURL, the frozen frame that makes refining cheap, and include(_:in:) are in the reference, and PointLift runs that loop, clicks and all.
Bringing your own model: ModelTracker
When the built-ins run out, ModelTracker runs a Core ML model of your own over the same frames, with the same attach-and-read shape. Core ML is Apple's format for trained models, and most published models convert to it. It fills whichever read surfaces match what the model puts out. A classifier gives classifications, a detector objects, an image-to-image model map and image, and a semantic segmenter classMask. The model in the block is Depth Anything V2, by Lihe Yang and colleagues, from 2024.
lazy var depth = ModelTracker(feed, modelAt: URL(fileURLWithPath:
"Models/DepthAnythingV2SmallF16.mlpackage"))
if let map = depth.map { drawImage(map, in: rect) } // in draw()
let near = depth.value(at: Vector2(mouseX, mouseY), in: rect) // 0 far … 1 nearThe four surfaces, loading, and availability are in the reference, and DepthRelief, ObjectDetection, DigitReader, PaintByClass, and StyleMirror each read one of them.
Depth that holds still: DepthTracker
A single-image depth model decides each frame on its own, so a still room's depth shimmers, and DepthRelief's disks with it. DepthTracker runs a video depth model instead. It keeps what it saw over the last second and reads each new frame against that, so the map moves only when the scene does. The surface is the one ModelTracker gives a depth model, map and value(at:in:), and the depth is relative, anchored on its first frame. The model is Video Depth Anything, by Sili Chen and colleagues, from 2025.
lazy var depth = DepthTracker(feed, modelAt: URL(fileURLWithPath:
"Models/VideoDepthAnythingSmallF16.mlpackage"))
if let map = depth.map { drawImage(map, in: rect) } // in draw()
if key == "r" { depth.reset() } // a new scene: anchor againThe anchor and reset(), the slow range, and the build step the model needs are in the reference. DepthContours draws the depth as contour lines, with a parameter that swaps in the single-image model.
A clip read whole for an export: DepthClip
A recording can be read whole instead of as it plays. A DepthTracker over a playing clip reads it a frame at a time, an export's frames included, and settles over its first second. DepthClip takes a VideoPlayer and runs its file through the video depth model once, in the 32-frame windows it was trained on. So an export has every frame's map from its first frame. Each window is fitted to the one before, so the clip sits on one scale. The pass is kept on disk, and then map and value(at:in:) answer for the frame under the playhead, the tracker's own calls.
var depth: DepthClip?
depth = DepthClip(player, modelAt: URL(fileURLWithPath: // in setup(), never lazily
"Models/VideoDepthAnythingSmallClipF16.mlpackage"))
if let map = depth?.map { drawImage(map, in: rect) } // in draw(), under the playheadThe export rule, the cache, and range are in the reference, and FootageDepth draws the bundled Voladores de Papantla clip's depth as contour lines.
How far, in meters: MetricDepthTracker
Both depth trackers answer nearer or farther, with no unit. MetricDepthTracker answers in meters, from the same webcam or clip. It runs a model trained to judge real distance. The one it was written for is Depth Pro 2, by Peiyun Hu and colleagues at Apple, from 2026. That model's license allows research use only, so nothing fetches it. You download it yourself after reading the license, and the tracker takes its path.
lazy var depth = MetricDepthTracker(feed, modelAt: URL(fileURLWithPath:
"Models/DepthPro2/depthpro2-s_w4.mlpackage"))
let meters = depth.meters(at: Vector2(mouseX, mouseY), in: rect) // in draw(); nil until a frame is read
if let frame = depth.frame { drawPointCloud(frame.pointCloud(depthRange: 0.2...8)) }frame is the value a depth camera fills: color, with a distance for every pixel. So Chapter 38's point clouds and surfaces take a webcam as they take a phone. Meters depend on the lens. The reference says how to state yours or let the model estimate it, and gives the speeds measured on one Mac.
Words as numbers: ConceptTracker
Chapter 36's classifier answers confidence( only for the 1,300 words it was trained on. ConceptTracker answers for any phrase you can type. Give it a few phrases in plain language and it scores each one against the picture, every frame. The scores are shares across your phrase set and sum to 1, so give it contrasts, the thing and its opposite. It runs MobileCLIP, Apple's small model from 2024, by Pavan Kumar Anasosalu Vasu and colleagues. The scores follow the recipe of CLIP, by Alec Radford and colleagues, from 2021.
lazy var ideas = ConceptTracker(feed,
imageModelAt: URL(fileURLWithPath: "Models/mobileclip_s0_image.mlpackage"),
textModelAt: URL(fileURLWithPath: "Models/mobileclip_s0_text.mlpackage"),
vocabularyAt: URL(fileURLWithPath: "Models/bpe_simple_vocab_16e6.txt"),
concepts: ["a spooky scene", "a cheerful scene"])
let spooky = ideas.share(of: "a spooky scene") // 0…1, every frame, in draw()The two encoders, similarity(of:), and live phrase changes are in the reference, and TugOfWords wires two phrase parameters to a tug-of-war rope.
Where this comes from
Étienne-Jules Marey, a French physiologist, showed his fixed-plate camera in July 1882. It laid several exposures of one moving subject on a single plate, and the method is called chronophotography. In 1883 he dressed his subject in black, with white stripes along the limbs and spots on the joints. The plate then kept only lines and points. That geometric chronophotography is what the body tracker's bones redraw. From 1913, Frank and Lillian Gilbreth fixed a small electric light to a worker's finger and photographed its path. They called the picture a cyclegraph, and the fingertip sparks follow it. Norman McLaren's film Pas de deux came out of the National Film Board of Canada in 1968. It printed each shot of two dancers over itself up to eleven times, each pass a few frames late. Camera art that answers a body is older than these trackers, and Chapter 36 names its first works. The perception is Apple's Vision framework and Core ML, running on the machine, and the entries after the sketch name their own sources. Full credits are in the project's attribution notes.
Go deeper
- Vision: every tracker in detail, coordinate mapping, still images, availability.
- Found things held steady:
@Steadiedin full, with its settings, each thing's number, what was measured on the detectors, and how to steady a type of your own. - Video: the film as a feed, and how an export steps it so a tracker reads the same frames on every run.
- Appendix B draws the mapping from a tracker's point to the canvas: Where things are.
- Worked examples, people first:
FaceTracking,HandTracking,BodyPose,BodyPose3D,Lift. - Then print and things:
ContourTrace,RectangleScan,TextScan,BarcodeReader,ObjectTracking,TrajectoryTracking. - Models of your own:
DepthRelief,DepthContoursfor depth that holds still,ObjectDetection,PaintByClass,TugOfWordsfor phrase scoring,StyleMirror, andDigitReader, which points a model at the sketch's own pixels with no camera anywhere. The rest live inExamples/Vision/.