#### <sup>[Ollin](../index.md) → [Guide](index.md) → Chapter 36</sup>

---

# 36. Seeing

<img src="Images/36-Seeing/MotionBrush.jpg" alt="A dark canvas with thousands of short colored strokes in greens, magentas, cyans, blues, purples, reds and yellows, gathered into one large tangle across the middle where the picture moved, with the edges mostly empty" width="560">

A camera gives a sketch someone to answer, as a picture and through trackers that turn each frame into values you read in `draw()`. The steps end on optical flow, the picture's motion read on the Mac with nothing sent away, and the brush above paints with it. Beyond it, two trackers say what a picture shows and where an eye would go. The camera's frame lights a 3D scene, the screen becomes a source, and a history of frames bends time. [Chapter 37](37-readingpeopleandthings.md) reads the people and things in the picture.

## The webcam is an image

Everything starts with `OllinVision`'s `Camera`, a source of frames you start once and then draw like any image.

```swift
import Ollin
import OllinVision

final class Mirror: Sketch {
    let camera = Camera()

    override func setup() { try? camera.start() }

    override func draw() {
        background(.black)
        drawFrame(camera)
    }
}
```

Run it and your camera's picture fills the canvas. `drawFrame(camera)` draws the latest frame letterboxed into the canvas, fitted without stretching like a photo in a mat. Until the first frame arrives, it shows a standard "Waiting for camera…" notice and returns `nil`. After that it returns the rectangle the picture landed in. Keep that rectangle, because the trackers below use it to place what they find. Using the camera needs permission, and macOS asks once, the first time `start()` runs. `Camera(.continuity)` uses a nearby iPhone as the camera, and `.external` a USB webcam.

### When there is no camera: stills and footage

Not every Mac has a camera, and a sketch may not have permission to use the one there is. `Camera.orStill(_:)` gives back a running camera where there is one, and a still picture where there is not. It takes the place of `let camera = Camera()` as a stored property:

```swift
import OllinSamplePhotos

let feed = Camera.orStill(SamplePhoto.reaching.load())
```

It starts the camera itself, so a sketch that uses it has no `start()` to call. What comes back is a **feed**, anything that hands out frames, the way a camera does. `drawFrame` and every tracker take a feed, so `drawFrame(feed)` draws it, and a tracker attaches to it as it attaches to a camera. On the first run the system asks whether the sketch may use the camera. The still stands in while it asks, and the camera takes over when you allow it.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="Images/36-Seeing/StandingIn-dark.jpg">
  <img src="Images/36-Seeing/StandingIn.jpg" alt="Two black panels side by side: the left one empty but for the words Waiting for camera, the right one holding a bundled photograph of a dancer reaching upward, letterboxed into the same rectangle" width="680">
</picture>

Without that line, a Mac with no camera shows the notice on the left for as long as you leave it running. With it, the picture on the right arrives instead, drawn by the same `drawFrame` call, and the sketch never learns which one it got.

Ollin bundles [twenty pictures and a short film](../docs/drawing/samplephotos.md) for this. There are four faces, four whole figures, two tables from above, four streets, two landscapes, a page, a pair of hands and two surfaces. So a sketch that reads people has people to read, and the vision examples run on a machine with nothing plugged in. `--photo` on launch takes the picture even where a camera would have worked. That holds a sketch that is normally live on one still frame, so a screenshot of its window shows the same picture every time.

The film is a feed too. `VideoPlayer` plays a video file. `SampleClip.dance` is the bundled clip, a man dancing on a plain ground in front of a camera that never moves:

```swift
import OllinSamplePhotos
import OllinVideo

let film = try! VideoPlayer(url: SampleClip.dance.url)   // the bundled clip is always there

override func setup() {
    film.loops = true
    film.play()
}

override func draw() {
    drawFrame(film)
}
```

`try!` is safe here because the clip ships with Ollin, and a property has no `setup()` to throw from; a clip loaded inside `setup()` takes a bare `try` instead. For a file of your own, `VideoPlayer(path:)` takes its path. Declare `var film: VideoPlayer?` and set it with `try?` inside `setup()`, and a missing file leaves it `nil` instead of stopping the sketch. The frames arrive on the GPU, so drawing them costs almost nothing, and `drawFrame` letterboxes them the same way.

While you build a sketch that reads people, rehearse it on footage. Standing in front of the camera for every change is tiring, and no two takes move the same way. A clip moves the same way every run, so the change you just made is the only thing that changed. Swap the camera back in once the sketch reads the film well. A tracker reads a clip in an export too. Each frame under the playhead is read before the frame that shows it is drawn, so every run reads the same frames.

### The camera or the film: Camera.or

`Camera.or` puts the two together: the camera where there is one, and the film where there is not.

```swift
let feed = Camera.or {
    let film = try! VideoPlayer(url: SampleClip.dance.url)
    film.loops = true
    film.play()
    return film
}
```

It is `Camera.orStill` with a feed of any kind standing in, and it behaves the same way. `--photo` takes the film, and on a first run the film plays while the system asks about the camera. `feed.isLive` says which one a frame is reading: `true` for the camera, `false` for the film. A sketch asks when it treats the two differently. [`ObjectTracking`](../examples/vision/objecttracking.md) waits for a click on the camera and lets a face detector choose what to follow in the film, where nobody is there to click.

## Trackers: attach, then read

Seeing more than pixels is the job of the **trackers**. Each one attaches to a feed and runs one kind of perception over its frames, publishing typed results your sketch reads every frame:

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="Images/36-Seeing/TrackerFlow-dark.jpg">
  <img src="Images/36-Seeing/TrackerFlow.jpg" alt="A diagram of three boxes: Camera producing frames, FaceTracker analyzing in the background, and typed results read in draw. Below, two panels show a normalized lower-left-origin point mapping into the drawn frame's rectangle" width="680">
</picture>

Here a `FaceTracker` finds faces. A face comes back with its **landmarks**, named points along its outline, brows, eyes, nose and lips:

```swift
import Ollin
import OllinVision

final class Faces: Sketch {
    let camera = Camera()
    lazy var faces = FaceTracker(camera)

    override func setup() { try? camera.start() }

    override func draw() {
        background(.black)
        guard let rect = drawFrame(camera) else { return }

        noFill(); stroke(.green); strokeWeight(2)
        for face in faces.faces {
            drawRect(face.bounds(in: rect))
            drawPolyline(face.landmarks(.faceContour, in: rect))
        }
    }
}
```

> **Swift note.** `lazy var faces = FaceTracker(camera)` builds the tracker the first time it's touched. So its declaration can mention `camera`, another property of the same class. Plain `let` properties initialize too early for that.

Every tracker follows that pattern. The analysis runs on a background thread, throttled to what the machine keeps up with. Under load it skips analysis frames rather than queueing them, and the displayed frame is never dropped. So your `draw()` stays smooth and reads the most recent result.

The second half of the diagram is about coordinates. Trackers report geometry in **normalized** coordinates, `0...1` across the frame, with the origin at the lower left and y pointing up. The canvas is pixels from the top left, with y pointing down, and the frame usually landed letterboxed somewhere inside it. So every result has to be flipped and scaled into the rectangle you drew the frame in. You never do that math yourself. Every result type carries `in:` helpers, among them `bounds(in: rect)`, `point(_:in:)`, and `landmarks(_:in:)`. Each takes the rectangle `drawFrame` returned and answers in canvas terms.

Pass `mirrored: true` to them when the sketch should answer like a bathroom mirror, left for left. It usually feels right for a sketch you stand in front of. `drawFrame` has no such switch. To show the feed flipped as well, draw it as `withState { translate(width, 0); scale(-1, 1); drawFrame(camera) }`, which flips the canvas left for right.

What a tracker hands back shakes a little from frame to frame, and a thing it is unsure of blinks in and out. [Chapter 37](37-readingpeopleandthings.md#the-same-things-in-the-next-frame-steadied) holds found things steady with `@Steadied`.

Many trackers run **trained models**, programs that learned from many example pictures rather than rules someone wrote. The heavier ones want Apple silicon. Every tracker exposes `isAvailable` and `unavailableReason`, and `drawStatus(reason, style: .warning)` turns the reason into the standard notice on the canvas instead of a silent nothing. Most trackers also read a single picture once, with no feed at all. The one-shot call is asynchronous, meaning its answer arrives a moment later rather than on the spot. `waitFor` holds the sketch until it does and hands the answer back, as [Appendix A](a-justenoughswift.md#swift-youll-see-in-listings) lists. `try? waitFor(photo) { try await FaceTracker.detect(in: $0) }` hands back the faces in `photo`, an `Image` you loaded.

## The picture as a field: optical flow

The face tracker finds a person. The next one does not care who is in frame. It reads how every part of the picture moved. **`FlowTracker`** measures **optical flow**, meaning the motion of each part of the picture since the previous frame. [Chapter 14](14-fieldsandflow.md) taught fields as "an answer at every point", and this is the same idea. The difference is that the answers are measured from the world, not computed from noise:

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="Images/36-Seeing/FlowArrows-dark.jpg">
  <img src="Images/36-Seeing/FlowArrows.jpg" alt="Two panels: a dancer on a plain studio ground with one arm swung out sideways, and the same frame with orange arrows running along both arms in opposite directions, a few on one leg and at one foot, and none on his chest" width="680">
</picture>

```swift
lazy var flow = FlowTracker(camera)
// in draw(), after `guard let rect = drawFrame(camera) else { return }`
if let field = flow.field {
    let push = field.vector(at: Vector2(mouseX, mouseY), in: rect)   // the motion under the mouse
    drawArrow(from: Vector2(mouseX, mouseY), to: Vector2(mouseX, mouseY) + push * 4)
}
```

`field` is `nil` until the second analyzed frame, because flow needs a pair. After that you can ask it anywhere. `vector(at:in:)` gives the motion under a point, `samples(in:every:)` a grid of arrows, and `averageFlow(in:)` the whole picture's drift. In the figure the arrows gather on the two arms and thin to almost nothing across the rest of him. His chest and his planted feet are just as present, and nearly still, so the field has next to nothing to report there. Flow reports motion, so a person standing quietly is invisible to it.

Motion can be measured only where the picture has texture. A blank wall or a solid backdrop doesn't read as zero. It reads as noise, because there is nothing to match from one frame to the next. If your scene is mostly flat, give it some texture before trusting the field there. Treat the sizes of the vectors as a signal rather than as a calibrated speed. Scale them by a gain of your own, a multiplier you pick by eye. The measured field has its own name, `MotionField`, apart from [Chapter 14](14-fieldsandflow.md)'s generative `FlowField`. One is a rule you invent, and the other is motion the camera saw.

## Putting it together: motion paints

The finished sketch is the painting at the top. You stand in front of the camera, and your motion is the brush. Where the picture moved, strokes appear, colored by the direction of the movement and sized by its speed. Stillness paints nothing, and old gestures sink slowly into the dark. Make `MySketches/MotionBrush.swift`:

```swift
import Ollin
import OllinVision

final class MotionBrush: Sketch {
    let camera = Camera()
    lazy var flow = FlowTracker(camera)

    override func setup() {
        try? camera.start()
        seed(21)                    // the brush dabs land the same way every run
        noClear()
        background(Color(hex: 0x0A0A14))
    }

    override func draw() {
        // A faint veil each frame, so old strokes sink slowly into the dark.
        noStroke()
        fill(Color(hex: 0x0A0A14, alpha: 0.007))
        drawRect(0, 0, width, height)

        guard let field = flow.field else { return }

        // How far a picture moves between two frames depends on what it is, so
        // the brush reads speed against this frame's own fastest sample, with a
        // floor under it so a still room paints nothing at all.
        let fastest = max(field.samples(in: bounds, every: 40).map(\.flow.length).max() ?? 0, 0.001)
        let cut = max(fastest * 0.22, 3)

        // Fling brushes at random spots; paint only where the picture moved.
        for _ in 0 ..< 900 {
            let p = Vector2(random(0, width), random(0, height))
            let v = field.vector(at: p, in: bounds, mirrored: true)
            let strength = v.length
            guard strength > cut else { continue }
            let hue = v.angle / .tau + 0.5              // direction picks the color
            stroke(Color(hue: hue, saturation: 0.75, brightness: 1)
                .withAlpha(min(0.5, strength / fastest * 0.3)))
            strokeWeight((1.2 + strength / fastest * 4) * scale)
            drawLine(p, p + v * (36 * scale / fastest))
        }
    }
}
```

The brush uses the webcam as a feed, the optical flow field, and a canvas that keeps its marks. The camera's picture is never drawn. So the field is mapped onto the whole canvas, `bounds`, stretched to fit, since a painting has no picture to line up with.

`seed(21)` fixes where the random brushes land, though a live painting still changes with the room. Each frame starts with a veil, a rectangle of the background color at an alpha of 0.007. It is [Chapter 12](12-flocksandswarms.md#roaming-wander-and-trails-from-noclear)'s fade over a canvas that is never cleared, so a stroke takes a few seconds to sink away. Then the brush reads the field once as a grid of arrows every 40 pixels, `samples(in:every:)`, and keeps the length of the fastest. The key path `\.flow.length` is [Chapter 7](07-tiles.md)'s, and `?? 0` covers an empty grid, which has no fastest arrow. `max(…, 0.001)` keeps a still frame's near-zero lengths from being divided by later.

The fastest arrow sets the scale, because how far a picture moves between frames depends on what it shows. A hand waved at a webcam crosses tens of pixels between frames, and a dancer filmed across the room crosses a few. A brush tuned to one would paint nothing for the other. So `cut` is 22 percent of the fastest motion in this frame, with a floor of 3 pixels, and a still room paints nothing.

The loop throws 900 brushes at random spots and asks the field for the motion under each one. `mirrored: true` answers like a mirror, so motion to your left paints on the left of the canvas. A spot that moved less than `cut` is skipped with `continue`. The rest become strokes. `v.angle` is the motion's direction from [Chapter 10](10-vectors.md), in radians from minus half a turn to plus half a turn. Dividing by `.tau`, a full turn, and adding 0.5 turns it into a hue from 0 to 1. So each direction has its own color. Faster motion makes a stroke more opaque, thicker, and longer, each measured against the fastest.

Then make it yours:

- Change what motion means by using `field.averageFlow(in: bounds)` to steer one big brush instead of 900 small ones. The sketch becomes a single line that follows the room.
- Paint with yourself instead of your motion. Swap the flow for `PersonSegmenter`, from [Chapter 37](37-readingpeopleandthings.md#the-person-as-pixels-personsegmenter-and-subjectsegmenter). Stamp its `matte`, tinted, wherever you stand, so motion leaves silhouettes.
- Drive the brush with `HandTracker`'s `.indexTip` instead of flow, and you're drawing in the air. [Chapter 37](37-readingpeopleandthings.md#hands-as-joints-handtracker) teaches the hand tracker.

To rehearse the brush without standing up, swap `camera` for the film from [When there is no camera](#when-there-is-no-camera-stills-and-footage), with `film.play()` in place of `camera.start()`. The dancer then paints a picture like the one at the top of the chapter, flipped left for right by `mirrored: true`. When the clip loops back to its start, the jump reads as one burst of motion, and `flow.reset()` right after the jump clears it.

This sketch paints from what happens in front of it, so keep a live painting by recording the window. Use the Mac's own screen recording, Shift-Command-5. Or send the sketch to another app while it runs, as [Chapter 47](47-performing.md#live-feeds-into-other-apps) shows. Rehearsed on the film, it exports too. An export hands the tracker each frame of the film before it draws the frame that shows it. So every run paints from the same frames.

## What the picture is about: labels and saliency

The brush answered where the picture moved. Two trackers answer a question about the whole picture instead, what is in it and where an eye would go. Both run trained models, so both want Apple silicon.

### Words for the scene: ImageClassifier

**`ImageClassifier`** names what's in view, from a fixed vocabulary of about 1,300 everyday words. It reports no positions at all, only labels and how confident it is about each. It is for a sketch that reacts to its surroundings instead of drawing on top of them. The vocabulary is Apple's, trained into the classifier that comes with the Mac.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="Images/36-Seeing/AttentionAndLabels-dark.jpg">
  <img src="Images/36-Seeing/AttentionAndLabels.jpg" alt="Two panels: a photograph of a woman standing before a wall of orange marigolds with an orange glow concentrated on her face inside a dark box, and a bar chart with people and adult at 91 percent reaching well past a dashed line, then clothing, plant, maple tree and tree, with flower and marigold at 7 percent falling below it" width="680">
</picture>

The bars on the right of the figure are its list for a photograph of a woman in front of a wall of marigolds. The vocabulary is a hierarchy, so one clear subject lights up its whole family at once, which is why `people` and `adult` tie. Read the tail, though. The picture is more marigold than anything else, and `marigold` comes back at seven percent. A classifier tells you what it was trained to notice, which is not the same as what the picture is of.

```swift
lazy var classifier = ImageClassifier(camera)

// in draw():
for (i, found) in classifier.classifications.prefix(5).enumerated() {
    drawText("\(found.name) \(Int(found.confidence * 100))%", 40, 60 + Double(i) * 32)
}
```

The classifier scores every word it knows on every frame, nearly all of them near zero. `minConfidence`, `0.1` by default, keeps `classifications` down to the few that cleared it, and the dashed line in the figure marks that floor. `confidence(of: "plant")` answers for any word in the vocabulary, whether or not it cleared the floor. So "how much does this look like a plant" can drive a color or a speed straight from the room.

### Where an eye would go: SaliencyTracker

**`SaliencyTracker`** maps where an eye would go, which is called **saliency**. It is for spending detail, density, or attention where a viewer will look. The saliency map was proposed by Christof Koch and Shimon Ullman in 1985. Laurent Itti, Christof Koch, and Ernst Niebur built the classic model of it in 1998. Apple's Vision framework makes this one with a trained model. The glow on the left of the figure above is its map, and the dark box around her face is its region. The glow gathers on her face rather than on the wall of flowers around her, because faces and contrast are what people look at.

```swift
lazy var eyes = SaliencyTracker(camera)

// in draw(), after `guard let rect = drawFrame(camera) else { return }`
if let heat = eyes.heatMap {
    tint(Color(red: 1, green: 0.6, blue: 0.2, alpha: 0.7))
    drawImage(heat, in: rect)          // where an eye would go, as a glow
    noTint()
}
```

`heatMap` is a white image whose alpha is the salience, so a `tint(_:)` turns it into a glow over the picture. `regions` are the boxes it peaks in. And `salience(at:in:)` answers for one canvas point, which is the field-shaped reading of [Chapter 14](14-fieldsandflow.md). Use it as a density for stippling, a weight for where to spend detail, or an attractor for particles. There are two kinds, chosen with `mode:`. The default `.attention` predicts where people look, while `.objectness` highlights regions likely to hold separate objects, whether or not they draw the eye. The mode is fixed when you make the tracker, so read both by making two.

## The camera in a 3D scene: the room as the light and the surface

The brush drew the camera's motion in 2D. A camera frame is an image, so it goes wherever an image goes, and that includes a 3D scene. It can be the light the scene is lit by, and a surface wrapped around a mesh.

### The room as the light: Environment.feed

[Chapter 29](29-materialsandsurroundings.md#surroundings-as-the-light-environments) lit its scenes with environments from somewhere else: a Venice evening, a studio, a synthetic sky. `Environment.feed(...)` uses the room you are in. Hand it the webcam, and its latest frame becomes the surroundings, so the room you are sitting in lights the thing you are making. The same idea, lighting a render with a photograph of real surroundings, is Paul Debevec's image-based lighting.

<img src="Images/36-Seeing/LiveRoom.jpg" alt="Three spheres floating in front of a photograph of a narrow street under a bright cloudy sky. The chrome sphere on the left carries the whole street wrapped around it, buildings and clouds and all, the middle sphere smears the same reflection into a satin sheen, and the white matte sphere on the right just takes the daylight" width="680">

The picture behind the spheres is also the light on them. Walk past the camera and the reflections move with you. Hold up something red and the whole scene warms.

```swift
let camera = Camera()          // started in setup(), as above

override func draw() {
    drawFrame(camera)              // the room as the picture
    environment(.feed(camera))     // the room as the light
    fill(.white)
    material(.metal(roughness: 0.03))
    drawSphere(radius: 1.02)
}
```

A webcam only brings a window, and lighting needs a whole sphere of surroundings. So the half the camera can't see is filled with the mirror image of the half it can. The result is plausible rather than true, and plausible is enough for lighting. The feed never draws itself as the backdrop, the way the environments of [Chapter 29](29-materialsandsurroundings.md#surroundings-as-the-light-environments) can. The wrap is made for lighting, not for looking at. Show the feed yourself with `drawFrame`, and the picture and the lighting stay one world. Any feed works the same way, such as a playing video, a screen capture, or the phone's camera. Until the first frame arrives, a neutral sky stands in. The `3D/Environments/LiveEnvironment` example is this entry, live.

### The room as the surface: textured

A camera frame is an `Image`, and [Chapter 28](28-meshes.md#a-picture-wrapped-around-it-textured) put an image on a mesh with `textured(_:)`. So the room you are sitting in can be wrapped around a globe, and lit by itself, in two lines:

<img src="Images/36-Seeing/LiveSurface.jpg" alt="A large sphere wrapped in the same street photograph as the figure above, a pink wall and its window and balcony wrapped around the globe, beside a small chrome ball reflecting the same street. Both are lit by the picture they show" width="680">

```swift
let globe = Mesh.sphere(radius: 1)            // any mesh with uvs

// in draw():
environment(.feed(camera))                  // the room as the light
if let frame = camera.frame {
    drawMesh(globe.textured(frame))         // the room as the surface
}
```

`camera.frame` is the latest capture as an `Image`, or `nil` before the first one arrives. Set the texture every frame, because each capture arrives as a fresh image. A fresh image uploads to the GPU the first time it is drawn. So there is one upload per new frame, and nothing while the frame holds. That costs little for one surface and adds up across many. So put the feed on the surface that matters, and let the same feed light the rest. The `3D/Materials/LiveSurface` example does that, with the webcam.

## The screen and the past: ScreenCapture and SlitScan

The brush read the frame in front of it, from the camera, as it arrived. Two more sources change where a frame comes from and when. The screen hands over whatever is running on the Mac, and a history of frames lets each pixel come from a different moment.

### Drawing with the screen: ScreenCapture

`ScreenCapture` hands over any display, any app, or any single window as a live image. A browser, a map, a video call, a terminal, or another sketch becomes something to draw with. It runs on Apple's ScreenCaptureKit, the part of macOS that records the screen.

```swift
import OllinScreen

let screen = ScreenCapture(.mainDisplay)

override func setup() { screen.start() }
override func draw() { drawFrame(screen) }
```

It's a feed like the camera and the film. `drawFrame` letterboxes it, filters work on it, and a tracker attaches to it as it would to a camera.

```swift
let screen = ScreenCapture(.app("Safari"))
lazy var faces = FaceTracker(screen)        // finds faces in whatever is playing
lazy var labels = ImageClassifier(screen)   // names what the window shows
```

You say what to capture as a value you write down, so the sketch records what it drew:

```swift
ScreenCapture(.app("Safari"))                    // every window one app has open
ScreenCapture(.window(matching: "Shopping list"))   // one window, by its title
```

An app matches on its name or its bundle identifier, and it has to match in full. A window matches any title that contains the text. That keeps `"Shopping list"` working when the title bar reads `"Notes: Shopping list"`. Naming something that isn't open yet is a wait rather than an error. The capture keeps looking and starts by itself when the window appears. A window captured on its own arrives at its own size with nothing in front of it, even when something covers it on screen.

Point a sketch at the screen it is drawn on and it would draw the window it is being drawn in, forever. So by default its own windows are cut out of the picture. Turn that off and the recursion becomes the picture:

```swift
screen.excludesOwnWindows = false
```

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="Images/36-Seeing/ScreenAsMaterial-dark.jpg">
  <img src="Images/36-Seeing/ScreenAsMaterial.jpg" alt="Two panels of a stand-in desktop. Left, a clean capture of a wallpaper with two windows. Right, the same capture with an Ollin sketch window on it showing the same picture, nested four levels deep" width="680">
</picture>

The result is video feedback, which people have made by pointing a camera at a monitor since the 1960s. It is the capture-side twin of [Chapter 19](19-layersandeffects.md#the-canvas-that-remembers-itself-feedback)'s feedback layer. Here it costs one Boolean. How deep it goes depends on how fast the sketch draws compared with the capture, and it smears and drifts as you move the window. The figure's desktop is made up, and the nesting is what a live one does.

At `scale = 1` a capture arrives at the screen's full resolution. On a Retina display that is twice the screen's size in points, the unit macOS lays windows out in. `screen.scale = 0.5` quarters the pixels, and it is the setting to reach for when an effect chain slows down.

Recording the screen needs the user's consent, and macOS grants that to an application. A sketch run from the terminal has no application of its own. The consent goes to whatever launched it, which is Terminal, iTerm, Ghostty, or whichever terminal you use. The prompt names your terminal, and so does the entry in System Settings. Once you allow it there, every sketch you run from that terminal can capture with no further prompt. That also means everything you run from it can record the screen. Granting it doesn't reach a process already running, so allow it and then start the sketch again. `ScreenCapture.isAvailable` and `unavailableReason` tell you where you stand, and `drawFrame` puts the reason on the canvas for you.

### Every pixel its own moment: SlitScan

A `SlitScan` is a rolling history of frames. You push the newest one every time you draw, and it keeps the last few dozen. Then you ask it for a picture in which each pixel comes from a different moment. It is for motion laid out as a shape, a moving arm drawn as a fan of sleeves. Slit scanning started as a photographic technique, a physical slit with the film moving behind it. It made the stargate sequence of *2001: A Space Odyssey*, and became a delay per pixel once video was digital. Golan Levin's informal catalog of slit-scan works maps that history.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="Images/36-Seeing/SlitScanDelay-dark.jpg">
  <img src="Images/36-Seeing/SlitScanDelay.jpg" alt="Two panels: the newest frame of a dancer with both forearms raised in front of the face, and the slit-scanned version of the same two seconds, where a hand has become a fan of pink slices sweeping out to the right" width="680">
</picture>

```swift
let history = SlitScan(capacity: 48)

override func draw() {
    if let frame = camera.frame {
        history.append(frame.resized(width: 480, height: 270))
    }
    if let warped = history.image(delay: { uv in uv.x }) {
        drawImage(warped, in: canvasRectangle, fit: .contain)
    }
}
```

The closure decides everything. It receives a pixel's position as fractions across the picture, from the top left, and returns how far back to read there. In that answer, 0 is the newest frame and 1 is the oldest one still held. Returning `uv.x` makes the left edge now and the right edge the oldest moment held. So time runs back from left to right across the image.

The figure's history holds forty-eight frames of the bundled film, just under two seconds. The hand that swung through those two seconds comes back as a fan of slices toward the right. Each column caught it at another moment. The leg the dancer kept planted looks ordinary. Any delay map works. `1 - uv.y` puts now at the bottom, since `uv.y` grows downward. `uv.distance(to: Vector2(0.5, 0.5)) / 0.71` makes time ripple outward from the center, with 0.71 about half the diagonal so the corners read the oldest frame. There's also a form that takes an `Image` as the delay map, so you can paint where time runs slow.

The history costs width times height times four bytes per frame, so push modest sizes, as the block does with [Chapter 9](09-pictures.md)'s `resized`. Resizing costs some time every frame, so keep the size small. The first push fixes the size, and after that frames of another size are skipped with a note in the console. A camera frame pushes straight in. A film's frames live on the GPU, so push `film.snapshot()` instead.

> **Swift note.** If your sketch's class is itself named `SlitScan`, it hides the framework's type of the same name. Write `Ollin.SlitScan` then. Putting the module's name in front says you mean the framework's one.

## Where this comes from

Camera art that answers the people in front of it goes back to the 1970s. Myron Krueger's *Videoplace*, in the mid-1970s, let people play with their own silhouettes. David Rokeby's *Very Nervous System* turned body motion into sound in 1986. And Camille Utterback and Romy Achituv's *Text Rain* let falling letters rest on your outline in 1999. That lineage runs through today's interactive mirrors, and Golan Levin's writing on computer vision for artists maps it. Optical flow goes back to Berthold Horn and Brian Schunck, and to Bruce Lucas and Takeo Kanade, both in 1981. The perception itself is Apple's Vision framework and Core ML, running on the machine. Ollin adds the typed reading surface, mapped to the canvas, after the approach of Kyle McDonald's ofxCv addon for openFrameworks. Most entries after the brush name their own sources. Full credits are in the project's [attribution notes](../attribution.md).

## Go deeper

- [Vision](../docs/vision/vision.md): every tracker in detail, coordinate mapping, still images, availability.
- [Video](../docs/video/video.md): loading and playing footage, analysis, the soundtrack, deterministic export.
- [Sample photos](../docs/drawing/samplephotos.md): the twenty bundled pictures and the film, with their credits.
- [A live camera environment](../docs/3d/3d.md#live-environment): `Environment.feed` with any `VideoFeed`, how the unseen half is filled, and the neutral sky before the first frame. The `3D/Environments/LiveEnvironment` and `3D/Materials/LiveSurface` examples run it with the webcam.
- [Screen capture](../docs/integration/screencapture.md): naming a display, app, or window, listing what's there, the permission story in full, and the feedback tunnel.
- [Slit scan](../docs/video/slitscan.md): the frame history, both delay forms, memory cost, and the delay maps to try.
- Appendix B draws this chapter's math, one picture per idea: [Where things are](b-justenoughmath.md#putting-a-normalized-point-onto-the-canvas), [Fields and following them](b-justenoughmath.md#optical-flow-a-measured-field).
- Worked examples: [`WebcamFeed`](../examples/vision/webcamfeed.md), [`OpticalFlow`](../examples/vision/opticalflow.md), [`SceneLabels`](../examples/vision/scenelabels.md), and [`EyeCatcher`](../examples/vision/eyecatcher.md). The examples that read people, print, and things are listed in [Chapter 37](37-readingpeopleandthings.md#go-deeper).
- Footage and history: [`Examples/Video/VideoPlayback`](../examples/video/videoplayback.md), which ships with a short clip of the *Voladores de Papantla*, [`Examples/Vision/ContourTrace`](../examples/vision/contourtrace.md), which traces a clip handed to it on launch, and [`Examples/Images/SlitScan`](../examples/images/slitscan.md). [Chapter 41](41-listening.md)'s `Soundtrack(of: player)` reads a clip's sound, so one clip can drive a sketch with its pixels and its music.
- The screen itself: [`Examples/Integration/ScreenCapture`](../examples/integration/screencapture.md), which lists what your Mac can capture as the line of code that names each one, and puts the feedback tunnel on a parameter.

---

[Contents](index.md#contents) · Previous: [Chapter 35, The lens and the slow render](35-thelensandtheslowrender.md) · Next: [Chapter 37, Reading people and things](37-readingpeopleandthings.md)
