Class 4 · See tags¶
The car can see, but it doesn't understand what it sees. Today it learns to read AprilTags: square black-and-white codes, like simple QR codes, that a camera can find quickly and measure. From one tag, the car learns which tag it is, how far away it is, and in which direction. Then you'll write the first decisions the car makes on its own.
By the end of class
Put a tag anywhere in front of the car; it turns to face the tag and stops 20 cm from it.
New parts today¶
| Part | What it's for |
|---|---|
| Printed AprilTags, family 36h11 | Landmarks the car can identify and measure |
| Printed checkerboard on stiff cardboard | Calibrating the camera |
| Ruler or tape measure | Checking the car's measurements |
Where Claude Code fits today
Claude Code may help with camera calibration (Mission 1). The decisions (Mission 3, the state machine that turns and stops) are yours to write. The detection code in Mission 2 is short enough that you should write it from the tool below.
Build it¶
-
Tags. You need 36h11 tags with IDs 0 to 9 at least. OpenCV can draw them (OpenCV 4.7 or newer):
import cv2 tags = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_APRILTAG_36h11) for tag_id in range(10): img = cv2.aruco.generateImageMarker(tags, tag_id, 800) cv2.imwrite(f"tag36h11_{tag_id}.png", img)Print each one so that the black square is 8 cm on a side, with the white paper around it as a border (the white border is part of what makes it readable). Write the ID small in a corner, outside the black square. Printers scale things, so measure the black square with a ruler: that number is your
tag_size. -
Glue each tag to a piece of foam board so it stays flat. A curled tag gives wrong distances.
-
Checkerboard. Print a checkerboard of 10 × 7 squares (that's 9 × 6 inside corners) with squares about 25 mm, and glue it flat onto cardboard. Measure a square with a ruler.
Tool: what camera calibration is
Every camera has its own focal length (how zoomed in it is) and its own center (where straight ahead lands in the picture), in pixels. To turn "the tag is 120 pixels wide" into "the tag is 40 cm away", the code needs those numbers for your camera:
| Number | Meaning |
|---|---|
fx, fy |
Focal length in pixels, horizontally and vertically |
cx, cy |
The pixel the camera looks straight through (near the middle of the image) |
You find them by showing the camera a pattern whose size you know, a checkerboard, from many angles. OpenCV's findChessboardCorners() finds the corners in each photo and calibrateCamera() solves for the numbers. It also reports a reprojection error in pixels: how far, on average, the corners it predicts are from the corners it found. Under 1 pixel is good.
Calibrate at the same resolution you'll drive at (640 × 480). Change the resolution later and you need to calibrate again.
Mission 1 · Calibrate the camera
Take 15 to 20 photos of the checkerboard with the car's webcam: close and far, tilted left, right, up and down, in every corner of the frame. Run a calibration script (Claude Code may write it with you) that saves fx, fy, cx, cy to a file your other programs read, for example camera.json.
Done when
The reprojection error is under 1 pixel, cx and cy are near the middle of a 640 × 480 image, and camera.json is in your project folder.
Tool: finding AprilTags with pupil-apriltags
Install it in your venv: pip install pupil-apriltags. If pip has to build it from source on the Pi, it takes a few minutes.
Example: find the tags in one photo saved on disk, and print what each one is and where.
import cv2
from pupil_apriltags import Detector
detector = Detector(families="tag36h11")
camera = (600.0, 600.0, 320.0, 240.0) # fx, fy, cx, cy: use yours
TAG_SIZE = 0.080 # black square, in meters
img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # the detector wants gray
for tag in detector.detect(gray, estimate_tag_pose=True,
camera_params=camera, tag_size=TAG_SIZE):
x, y, z = tag.pose_t.flatten() # meters, from the camera to the tag
print(f"tag {tag.tag_id}: {z*100:.0f} cm ahead, {x*100:.0f} cm to the right")
pose_t is where the tag's center is, measured from the camera: x to the right, y down, z straight ahead. It's in the same units as tag_size, so meters here. (pose_R is the tag's rotation. You'll need it in Class 5.)
The horizontal angle to the tag, in degrees, is math.degrees(math.atan2(x, z)): 0 means dead ahead, positive means the tag is to the right.
Mission 2 · ID, distance, angle
Combine the camera loop from Class 3 with the detector. For every tag in view, draw its ID, its distance in cm and its angle in degrees on the camera window. Read fx, fy, cx, cy from camera.json and use your measured tag_size.
Check every printed tag once: the ID on screen must match the ID you wrote on the paper.
Done when
With a tag 50 cm straight ahead (measured with a ruler), the screen says 48 to 52 cm and an angle within 3° of zero. Moving it to the side changes the angle in the direction you expect.
Tool: a state machine in Python
A state machine keeps one variable, the state, that says what the machine is doing right now. Each time through the loop it looks at the state, acts, and decides whether to change state. Each state stays simple; the hard part is choosing the states and the rules between them.
Example: a microwave.
import time
state = "IDLE"
end_time = 0
while True:
if state == "IDLE":
if start_button_pressed():
end_time = time.time() + 30
state = "COOKING"
elif state == "COOKING":
if door_opened():
state = "PAUSED"
elif time.time() >= end_time:
beep()
state = "IDLE"
elif state == "PAUSED":
if door_closed() and start_button_pressed():
state = "COOKING"
time.sleep(0.05)
Draw your states as circles and the rules as arrows on paper before you write any code.
Mission 3 · Face it, approach, stop
Write the car's first decisions as a state machine. One possible set of states: SEARCH (spin slowly until a tag is in view), AIM (turn until the angle is small), APPROACH (drive forward, steering to keep the angle small), ARRIVED (stop). What happens if the tag disappears halfway?
Use your car.py bridge to send the commands. Remember the Uno's safety stop: the loop has to keep sending commands.
Done when
With a tag placed at three different spots (one straight ahead, one off to the side, one behind the car), the car ends up facing it, stopped 18 to 22 cm away (measure with a ruler). Take a video of one run.
If you finish early¶
- Proportional steering again: in APPROACH, make the turn amount proportional to the angle, like the corridor in Class 2.
- Print the detection's
decision_marginand see how it changes with distance and lighting. At what distance does the car stop seeing tags? - Try a tag at 1.5 m. Is the distance still right?
Sign-off with Dr. Alvear
- Camera calibrated; reprojection error under 1 pixel
- On-screen distance within 2 cm of a ruler at 50 cm
- State diagram on paper, and your state machine code
- Car faces a tag and stops 20 cm away
- Build log updated (photo + two sentences)