AI from scratch · Chapter 9

Vision in practice

Chapter 6 taught a network to read digits on a black square. Real images are messier: rain, glare, night, a bus blocking half the view. NYC publishes about 900 live traffic cameras, refreshed every couple of seconds. Let's point everything we've built at them: first plain arithmetic, then a real trained detector running in your browser.

1. A live camera

live frame
what a network gets: numbers per pixel

A frame is about 350 × 240 pixels, each with red, green and blue values: some 250,000 numbers. That's what every method below starts from.

The math: from color to gray

The right-hand picture turns three numbers per pixel into one brightness. Not a plain average: eyes are most sensitive to green and least to blue, so the standard (ITU-R BT.601) weighting is

\[ Y = 0.299\,R + 0.587\,G + 0.114\,B \]

Pure green (0, 255, 0) comes out as 150, much brighter than pure blue (0, 0, 255) at 29, which matches how they look. Many vision models skip this and take all three channels, so their first layer's filters are \(k \times k \times 3\).

Exactly how many numbers is one 352 × 240 color frame?

\(352 \times 240 \times 3 = 253{,}440\).

A camera frame is a quarter of a million numbers, and every method starts from them.

2. Motion, by subtraction

The simplest vision trick needs no learning at all. Take two frames a few seconds apart and subtract them, pixel by pixel. The road, buildings and sky cancel out; whatever moved lights up. Traffic engineers used this long before neural networks.

|frame 2 − frame 1|
moving pixels (above threshold)

It finds motion but not what moved: two cars side by side merge into one blob, a parked car is invisible, and swaying trees or a camera adjusting its exposure light up as false alarms. To know what's there, we need a model that has learned what cars look like.

The math, step by step

For each pixel, the difference image and the mask are

\[ D[r][c] = \lvert F_2[r][c] - F_1[r][c] \rvert, \qquad M[r][c] = \begin{cases} 1 & D[r][c] > \theta \\ 0 & \text{otherwise} \end{cases} \]

The threshold \(\theta\) trades noise against sensitivity: camera noise and compression wiggle pixels by a few levels, so a tiny \(\theta\) lights up the whole frame, while a big one misses dark cars on dark asphalt. To count objects, group touching 1-pixels into connected components (blobs) with a flood fill. That's exactly where two cars side by side become one blob.

Subtracting two frames finds what changed, but not what it is.

3. A trained detector

This is COCO-SSD: a convolutional network (chapter 6, but dozens of layers deep, based on MobileNet) trained on the COCO dataset of 330,000 photos labeled with 80 kinds of objects. For each image it proposes boxes and gives each one a class and a confidence: a softmax (chapter 5) per box. Loading it downloads about 5 MB once, and then it runs entirely in your browser; no image leaves your computer.

detections

Slide the confidence down and more boxes appear, including wrong ones; slide it up and real cars far away disappear. Every detector lives on that trade-off between missing things and imagining them. Detectors also produce many overlapping boxes for each object; a step called non-maximum suppression keeps only the most confident box among ones that overlap a lot.

The math: overlap, suppression, and scoring a detector

Intersection over union measures how much two boxes overlap, from 0 (apart) to 1 (identical):

\[ \operatorname{IoU}(A, B) = \frac{\operatorname{area}(A \cap B)}{\operatorname{area}(A \cup B)} = \frac{\operatorname{area}(A \cap B)}{\operatorname{area}(A) + \operatorname{area}(B) - \operatorname{area}(A \cap B)} \]

Non-maximum suppression: sort boxes by confidence; keep the top one; delete every remaining box of the same class whose IoU with it is above about 0.5; repeat with the next box still standing.

Scoring. A detection counts as right (a true positive) if it overlaps a real object with IoU ≥ 0.5. Then precision = right detections / all detections ("when it says car, how often is it a car?") and recall = right detections / all real objects ("how many of the cars did it find?"). The confidence slider above trades one for the other.

Two boxes of the same size; one is shifted right by half its width. What is their IoU? (Decimal.)

Overlap = half a box. Union = 1 + 1 − ½ = 1½ boxes. IoU = ½ ÷ 1½ = 1/3. So "half overlapping" is only 0.33, below the usual 0.5 cutoff.

On a frame with 12 real cars the detector draws 10 boxes: 8 on cars, 2 on nothing. Precision and recall?

Precision = 8/10 = 0.8. Recall = 8/12 ≈ 0.67. Lowering the confidence threshold would raise recall and lower precision.

A detector proposes boxes, each with a class and a softmax confidence; the threshold trades missed objects against imagined ones.

Why a detector needs non-maximum suppression at all
  1. A detector like SSD doesn't search for objects. It scores a fixed set of thousands of candidate boxes (at many positions and sizes) all at once, one softmax per box.
  2. A car covers many of those candidates. Each candidate that sits over most of the car sees almost the same pixels, so it gets almost the same high score.
  3. So the raw output is a cluster of strong boxes per object, all overlapping each other with high IoU.
  4. NMS keeps the best box of each cluster and deletes its neighbors above an IoU of about 0.5: one box per object.
  5. The rule assumes two real objects never overlap that much, which is exactly where it fails (below).

4. Counting the city, right now

Put the detector on a loop over many cameras and you get something no single camera gives you: a snapshot of the city. It counts objects only; at this resolution nobody can be identified, and nothing is stored.

This is the pattern behind real traffic-counting systems: a fixed, pretrained model plus your own aggregation and archive. The "AI" part is a component; the value is in what you build around it, here a count across a city at one instant, which you could log every five minutes and turn into a busyness map. That's where this world ends: from matrices as moves of the plane, through gradients, neurons, backprop, probability, convolutions, attention and agents, to a model reading the streets of New York.

A pretrained model is a component; the value is in what you build around it.

Where it breaks: crowds, odd angles and unknown things

All chapters: AI from scratch. Detector: COCO-SSD for TensorFlow.js (Apache 2.0). Cameras: NYC DOT.

Last updated