A corner detector tells a robot where the texture is. It never says "stop sign". Give the same camera frame to three kinds of perception, and only the learned detector stops the robot for a tilted or distant sign.
Pick the perception and the sign, and watch whether the robot stops at the line. Then we build it piece by piece: templates, windows, boxes, convolution, the detector, masks, and the path from a box to STOP.
You need what a probability is and a little Python. We build the rest from zero.
Lesson 10 of 15 in our follow-along of Stanford AA 274A, Principles of Robot Autonomy I. Every idea is re-taught here in our own words and devices. Before: Lesson 9, Features and RANSAC. Next: Lesson 11, SLAM.
Perception
The sign
Illustrative scores. The template stops above an NCC of 0.80; the detector stops above a confidence of 0.50. Corners carry no class, so they can never trigger STOP.
Chapter 0
Flip one street frame between a corner map and a labelled scene
In Lesson 9 you built a corner detector. Point it at a street and it marks dozens of spots: a window corner, a wheel rim, the edge of a red octagon. Not one mark says "stop sign".
A robot at a four-way stop needs the name. Is the red shape a stop sign, a balloon or a tail light? Is the shape ahead a person who may step out, or a mailbox? Geometric perception finds where structure sits in the image. Semantic perception names what the structure is.
Choose a view. Count what each one tells a robot that must decide whether to stop.
Illustrative scene and scores. The keypoints sit where the image changes sharply in two directions, as in Lesson 9.
Why is "what" harder than "where"? The course gives two reasons. Objects hide each other and appear at every size, angle and light. And one class varies a lot: a stop sign may fade, tilt, sit in shadow or wear stickers.
Try to write the rule "red octagon means stop sign". The sign spans 200 pixels up close and 12 far away. Edge-on, it is a thin bar. At dusk it is nearly black. Each case needs its own exception, and nobody can list them all. A learned detector sees thousands of stop signs and finds the pattern itself.
The symptom is a robot that sees the sign's keypoints and drives through. To measure it, log what reaches the executive: keypoints carry no class, so the STOP input never fires. The fix is a semantic stage between the features and the executive.
Chapter 1
Ask one scene for a label, then boxes, then a label per pixel
"Recognize the scene" is three tasks. They differ in how precise an answer you ask for.
Pick a task. Watch the answer grow from three probabilities, to boxes, to a painted image. The read-out counts the numbers out.
Illustrative scene. The classifier's three raw scores are 2.0, 0.5 and −1.0, worked below.
A classifier outputs one raw score per class, called a logit. Raw scores can be negative and do not add up to one. To turn them into probabilities, call the logit of class i zi and use e, the number 2.718.
p-i equals e to the z-i, divided by the sum over j of e to the z-j.
Raise e to each logit z. Add all the results. Divide each result by the total. This step is called the softmax.
With made-up logits 2.0, 0.5 and −1.0 for stop sign, yield sign and billboard: ez is 7.389, 1.649 and 0.368. The total is 9.406. So p is 0.786, 0.175 and 0.039. Stop sign wins at 79%.
A logit gap of 1.5 became a probability ratio of 4.5. The softmax sharpens a lead. That is why a classifier can be wrong and still sound sure.
| Task | Out for a 640 by 480 frame | Robot use |
|---|---|---|
| Classify | one label: C numbers | "is there a sign anywhere?" |
| Detect | (class, box, score) per object | "what, where, how far?" |
| Segment | 307,200 labels, one per pixel | "which pixels are road?" |
Instance segmentation goes one step further: one mask per object, so two people standing together stay two. Chapter 8 returns to it.
The symptom is a robot that is too slow, or that cannot say where the object is. To measure it, ask which question the planner needs answered. The fix is the coarsest task that answers it: detection is the usual choice on a robot.
Chapter 2
Drag a template over an image and watch a bright decoy fool the raw score
The oldest recognition trick is how you find Waldo. Keep a small picture of the thing, called the template. Slide it over the big image. At each place, ask how well it lines up.
The plain score multiplies each template pixel by the image pixel under it and adds the products. It has a flaw: a patch that is bright everywhere gives a huge sum, whatever its shape. Brightness wins, not shape.
Drag the blue box over the image, or press Scan. Switch the score between Raw sum and NCC, then rotate the object.
Illustrative 16 by 10 image. The template is a 4 by 4 cut from the object. The decoy is a flat bright square.
The fix is to normalize. Write the template as a list of numbers t, and the patch under it as a list f, in the same pixel order.
NCC equals f dot t, divided by the norm of f times the norm of t.
Take the dot product of f and t. Divide by both lengths. A patch twice as bright doubles the dot product and its own length, so the score stays the same. Only the shape counts.
With made-up pixels: t = (2, 1, 1, 0) and a patch twice as bright, f = (4, 2, 2, 0). f · t = 8 + 2 + 2 + 0 = 12. ‖f‖ = √24 = 4.899 and ‖t‖ = √6 = 2.449. NCC = 12 / 12.0 = 1.00.
| Patch f under t = (2, 1, 1, 0) | f · t | NCC |
|---|---|---|
| (4, 2, 2, 0): same shape, twice as bright | 12 | 1.00 |
| (1, 0, 2, 1): the same corner, turned 90° | 4 | 0.67 |
| (0, 1, 1, 2): bright pixel in the wrong corner | 2 | 0.33 |
NCC is the cosine of the angle between the two lists. The sum of absolute differences (SAD) is a cousin: add |f − t| over all pixels, and the smallest sum wins. It has no brightness fix: the twice-bright patch scores 4, not 0.
The symptom is a template that finds the sign on Monday and misses it on Tuesday. To measure it, rotate or shrink the object and log the peak NCC: a 90° turn drops it from 1.00 to 0.67. An image pyramid (the image at several sizes) fixes scale only. Rotation, pose and class variety need learned features (Chapter 5).
Chapter 3
Sweep a window across a frame and count the classifier calls
Suppose you have a classifier that looks at one 64 by 64 patch and says "stop sign, 0.93". How do you find signs anywhere in a 640 by 480 frame? Run it everywhere. Crop a window, score it, move one step, score again. This is the sliding window. The step size is the stride.
Press Sweep. Each blue mark is one classifier call, darker for a higher score. Raise the stride and watch the best score fall.
Illustrative classifier: its score falls off with the distance between the window centre and the sign centre (a bell curve with a 10 px spread). It fires above 0.50. The device draws one pyramid level.
How many calls is that? Call the frame width W and height H in pixels, the stride s, and the number of image sizes L. Call the total number of classifier calls N.
N is about L times W over s, times H over s.
Count the window positions across, W over s. Count them down, H over s. Multiply, then multiply by the L image sizes.
With W = 640, H = 480, s = 8 and L = 5: (640 / 8)(480 / 8) = 80 × 60 = 4,800 windows per level. Times 5 is 24,000 calls a frame. At 30 frames a second, 720,000 calls a second.
| Stride s | Windows per level | 5 levels | Per second at 30 Hz |
|---|---|---|---|
| 4 px | 19,200 | 96,000 | 2,880,000 |
| 8 px | 4,800 | 24,000 | 720,000 |
| 16 px | 1,200 | 6,000 | 180,000 |
| 32 px | 300 | 1,500 | 45,000 |
One window size finds one object size. So the robot searches a Gaussian pyramid: blur the image, halve it, repeat. Blur first, or fine stripes turn into false patterns when you halve. Scale each hit back up. At the level scaled by 0.5, a 64 by 64 window at (40, 30) becomes a 128 by 128 box at (80, 60).
The symptom is a small, far sign that the robot never sees. To measure it, plot the best score over strides. In the toy, a 32 px stride lands no window near the centre, and the score drops below 0.50. The fix is a finer stride, which costs calls, or one network pass over the whole image (Chapter 6).
Chapter 4
Turn the overlap threshold and watch duplicates merge, or real people vanish
The windows leave a heap of boxes around each object. We want one box per object. That needs two tools: a number for how much two boxes overlap, and a rule that uses it to delete duplicates.
Write each box by its corners: (x1, y1) top left and (x2, y2) bottom right. Call the shared area of boxes A and B the intersection, and the area they cover together the union.
IoU equals the area of A intersect B, over the area of A union B.
Find the overlap rectangle and its area. Add the two box areas and take the overlap away once. Divide the overlap by that union.
With made-up boxes A = (0, 0, 4, 4) and B = (2, 1, 6, 5): both areas are 16. The overlap runs from x 2 to 4 and y 1 to 4: 2 × 3 = 6. The union is 16 + 16 − 6 = 26. IoU = 6 / 26 = 0.23.
Non-max suppression (NMS) uses IoU and a threshold τ (tau):
Faint boxes are the detector's raw output; bold boxes survive NMS. Lower τ until a real person disappears, then raise it until duplicates stay.
Illustrative boxes. The two people's best boxes overlap at an IoU of 0.36; each duplicate overlaps its keeper at 0.70 or more.
Trace one pass with τ = 0.5 on four made-up boxes. P = (0, 0, 4, 4) at 0.92, Q = (1, 0, 5, 4) at 0.85, R = (10, 10, 14, 14) at 0.78 and S = (11, 10, 15, 14) at 0.60.
NMS runs once per class. A person under a sign overlaps the sign's box, but a person box never deletes a sign box.
The symptom is a crowd where the robot counts one person for two. To measure it, compare the kept count with the true count across τ. In the toy, τ below 0.28 deletes a real person; above 0.70 a duplicate survives. The fix is to tune τ on scenes like yours.
Chapter 5
Pick a 3 by 3 filter, tap a pixel, and read its nine products
A filter is a small grid of numbers, say 3 by 3. Slide it over the image. At each place, multiply each filter number by the pixel under it and add. Write the sum into an output image. This is template matching with a tiny template.
Call the filter F, the image I and the output G. The filter cell at row u, column v holds F(u, v).
G of i, j equals the sum over u and v of F of u, v times I of i plus u, j plus v.
Lay the filter F on the image I with its corner at (i, j). Multiply the 9 pairs. Add them. That one number is G(i, j). Move one pixel and repeat.
With the course's patch I = [[7, 4, 1], [8, 5, 2], [9, 6, 3]] and F = [[1, 1, 1], [0, 0, 0], [−1, −1, −1]]: top row 7 + 4 + 1 = 12, middle row 0, bottom row −9 − 6 − 3 = −18. G = 12 + 0 − 18 = −6.
Pick a filter. Tap any pixel in the input or output. The read-out shows its nine products and their sum.
Illustrative 20 by 12 image: a bright block on a dark ground with a soft shading. The output shows the size of G; the read-out keeps its sign.
The horizontal filter takes the bottom row from the top row. It is near 0 on smooth areas and large at a top-to-bottom edge. On the same patch, the vertical filter [[−1, 0, 1], [−1, 0, 1], [−1, 0, 1]] gives −24 + 0 + 6 = −18. The patch darkens strongly from left to right. The blur (1/16)[[1, 2, 1], [2, 4, 2], [1, 2, 1]] gives 80 / 16 = 5.0, the centre value, because the patch is smooth.
Weights that sum to 1 and are all positive blur. Weights that sum to 0 detect edges. A convolutional neural network (CNN) does not take these from a person. It learns them from labelled images.
Stack layers and the view grows. A layer-1 cell sees 3 by 3 pixels; a layer-2 cell sees 5 by 5. Each 3 by 3 layer adds 2 pixels to this receptive field. Layer by layer, edges become corners, then parts, then objects.
The symptom is a detector that confuses a sign with a red patch of the same size. To measure it, check the receptive field of the layer that makes the call. If it is smaller than the sign, that layer never sees the whole octagon. The fix is more layers, or downsampling, so deep cells see the full object.
Chapter 6
Step an image through the backbone, then size the head's output
A CNN detector wires the pieces into one network. One forward pass turns an image into a list of (class, box, score). The data changes shape at each stage.
Press Step. Each stage halves the width and height and grows the channels. Then set the anchors per cell and read the head's size.
A 416 by 416 input and a 13 by 13 grid, as in YOLOv2; the channel counts per stage are illustrative. The head uses 80 classes, the COCO class count.
Five halvings take 416 to 13: the image shrinks 32 times in each direction, 1,024 times in area. Each of the 169 cells now holds many learned numbers about its patch of the image. The head scores all 169 patches in one pass, in place of 24,000 window calls.
A cell does not draw a box from nothing. It starts from a few preset boxes called anchors: tall for people, wide for cars, square for signs. It predicts small shifts and stretches of each anchor. How many numbers does one cell output? Call the anchors per cell A and the classes C.
K equals A times, four plus one plus C.
Each anchor needs 4 box numbers, 1 objectness and C class scores. Multiply that by the A anchors in the cell.
With A = 5 and C = 80: K = 5 × 85 = 425. A 13 by 13 grid outputs 13 × 13 × 425 numbers, and 13 × 13 × 5 = 845 candidate boxes.
| Family | How it finds boxes | On a robot |
|---|---|---|
| Two-stage (Faster R-CNN) | proposes a few hundred regions, then classifies and refines each | accurate, slower |
| One-stage (YOLO, SSD) | predicts boxes and classes straight from the feature map | fast enough for a 10 to 30 Hz loop |
The symptom is a detector that is right on the test set and sure but wrong on the road. Think of a sign in fog, or a class it never saw. To measure it, test on frames from your own robot, not only the benchmark. The fix is to treat every detection as evidence, never as fact (Chapter 9).
Chapter 7
Slide the confidence threshold and trade false alarms for misses
A frame holds 5 real stop signs. The detector draws 8 boxes. How good is it? Match each box to a real sign of the same class at an IoU of at least 0.5.
Two numbers summarize them. Precision asks: of the boxes drawn, how many were real?
Precision equals T-P over, T-P plus F-P.
Count all the boxes drawn, TP plus FP. Divide the good ones, TP, by that count.
With made-up counts TP = 4 and FP = 2: precision = 4 / 6 = 0.67. One box in three is a false alarm.
Recall asks: of the real signs, how many did we find?
Recall equals T-P over, T-P plus F-N.
Count the real signs, TP plus FN. Divide the found ones, TP, by that count.
With TP = 4 and FN = 1: recall = 4 / 5 = 0.80. The detector finds four signs in five.
Dots are the 8 boxes on a score line. Filled dots are real signs; rings are false alarms. The detector keeps the boxes right of the threshold. Watch the point on the curve.
Illustrative detector on one frame with 5 real signs. Green: a kept real sign. Red: a kept false alarm, or a real sign below the threshold.
Raise the threshold: fewer false alarms, more misses. Lower it: the reverse. Sweep it from 1 to 0 and the points trace a precision-recall curve. The area under it, averaged over classes, is the mean average precision (mAP) that papers report.
On a robot the operating point is a safety choice. Near a crossing, favour recall: a false stop is cheaper than a missed sign. On an empty highway, favour precision: braking for phantoms is a hazard too.
The symptom is a robot tuned on a benchmark that brakes for every red billboard. To measure it, count false and missed stops per hour of driving at the chosen threshold. The fix is to set the threshold per context, from those counts.
Chapter 8
Paint a scene by class, then mark the unsure pixels unknown
A box says "a person is roughly here". The planner sometimes needs the exact shape: which pixels are road, where the person's outline is. Semantic segmentation gives every pixel a class.
A backbone shrinks the image to learn what is in it. A mask needs full size again. So a segmentation network is an encoder-decoder, shaped like an hourglass:
The network outputs C scores at every pixel. The mask takes the argmax: the class with the largest score. With made-up scores (3.1, 1.2, 0.4) for road, sidewalk and person, the pixel is road. Its softmax is (0.82, 0.12, 0.06): 82% sure.
Each cell takes the class with the top score. Raise the bar and unsure pixels at the edges turn grey: unknown. Switch the person between box and mask.
Illustrative 32 by 20 grid with made-up scores. Pixels near a class border get closer scores, as real networks do.
| Output | Splits two people? | True shape? | Robot use |
|---|---|---|---|
| Box | yes | no, a rectangle | is a sign there, how far |
| Semantic mask | no, one "person" blob | yes | drivable free space |
| Instance mask | yes | yes | count and track each person |
The road pixels become the free space the planner searches (Lessons 3 to 5). The person pixels, grown by a safety margin, become a keep-out zone. This is the semantic map of Lesson 1.
The symptom is a path that clips a kerb because the network forced a border pixel to "road". To measure it, count the pixels whose top score is low, and where they sit. The fix is to mark them unknown and keep the planner off them.
Chapter 9
Turn two dials and make the robot stop, freeze for a billboard, or blow the sign
The course's homework asks the robot to detect a stop sign and stop. Every arrow in that pipeline is a lesson of this series.
How far is the sign? A stop sign has a known width, about 0.75 m (30 inches). Call it Wreal. Call its width in the image w, in pixels, and the camera's focal length fx, in pixels, from the Lesson 8 calibration.
Z equals f-x times W-real, over w.
Multiply the focal length f-x by the true width W-real. Divide by the width w the sign takes in the image. Half the image width means twice the distance.
With made-up f-x = 600 px and w = 96 px: Z = 600 × 0.75 / 96 = 450 / 96 = 4.7 m. Drive closer until w = 192 px and Z = 2.3 m.
Which way is it? Call the box centre column u and the image centre column cx. The bearing is the angle whose tangent is (u − cx) / fx:
bearing = atan2(800 − 640, 600) = atan2(160, 600) = 0.261 rad = 14.9° to the right
So the sign is 4.7 m ahead, 15° right. The executive reads "stop sign within braking range" and moves from DRIVE to STOP.
Faint boxes are raw; bold boxes pass the threshold and NMS. The badge is the executive. Push confidence above 0.88, then below 0.34. Then swing τ.
Illustrative scores: real sign 0.88, red billboard 0.34. The range read-out uses f-x = 600 px on a 1280 px wide frame, so the sign box is 96 px wide.
| Failure | Cause | Defence |
|---|---|---|
| Missed sign | fog, glare, a branch; score below threshold | lower the threshold near crossings; a map prior of known signs |
| False stop | a red billboard or tail light | need the box in several frames in a row, with a range that shrinks as the robot drives |
Chapter 10
Keep the terms, the numbers, the code and the links in one place
Semantic perception names what is in an image: one label, a box per object, or a class per pixel. A fixed template sees one look; a CNN learns many small templates and stacks them. A detector's output passes a threshold and NMS, gets a range and a bearing, and becomes an input to the executive.
| Term | Meaning | Number to remember |
|---|---|---|
| Softmax | pi = ezi / Σ ezj | logits 2.0, 0.5, −1.0: 0.786, 0.175, 0.039 |
| NCC | (f · t) / (‖f‖ ‖t‖) | twice as bright: 1.00; turned 90°: 0.67 |
| Window count | N ≈ L (W/s)(H/s) | 640 by 480, s 8, L 5: 24,000 a frame |
| IoU | overlap / union | 6 / 26 = 0.23 |
| NMS | keep the top box, delete overlaps above τ | P, Q, R, S at τ 0.5: keep P and R |
| Convolution | G(i, j) = Σ F(u, v) I(i+u, j+v) | horizontal edge on the course patch: −6 |
| Head size | K = A (4 + 1 + C) | A 5, C 80: 425; 845 boxes on 13 by 13 |
| Precision, recall | TP/(TP+FP), TP/(TP+FN) | TP 4, FP 2, FN 1: 0.67 and 0.80 |
| Range | Z = fx Wreal / w | 600 × 0.75 / 96 = 4.7 m |
python import math def iou(a, b): # boxes (x1, y1, x2, y2) iw = max(0, min(a[2], b[2]) - max(a[0], b[0])) ih = max(0, min(a[3], b[3]) - max(a[1], b[1])) inter = iw * ih union = (a[2]-a[0])*(a[3]-a[1]) + (b[2]-b[0])*(b[3]-b[1]) - inter return inter / union if union > 0 else 0.0 def nms(dets, tau=0.5): # dets: (box, score, cls) keep = [] for d in sorted(dets, key=lambda d: -d[1]): if all(k[2] != d[2] or iou(k[0], d[0]) <= tau for k in keep): keep.append(d) # per class return keep def perceive(dets, conf, tau, fx, cx, W_REAL=0.75): kept = nms([d for d in dets if d[1] >= conf], tau) for box, score, cls in kept: if cls == 'stop sign': w = box[2] - box[0]; u = (box[0] + box[2]) / 2 Z = fx * W_REAL / w # range, metres bearing = math.atan2(u - cx, fx) # radians, right is positive return 'STOP_SIGN', Z, bearing # an input for the executive return None
Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's tenth lesson in our own words, devices and toy numbers.
Now press Present or Teach. Explain from memory the three tasks, NCC, the window count, IoU and NMS, convolution, the head size, precision, recall and range. Then go back to the robot, pick the tilted sign, and say why only the detector stops.