Computer vision: color detection and face tracking
Time: 11:35 AM to 12:15 PM
Program 1: color detection
Build a script that detects colored objects in the camera feed and streams the annotated video to your browser.Step 1 — Imports
You need four libraries:picamera2 for the camera, cv2 (OpenCV) for image processing, numpy for arrays, and Python’s built-in http.server and threading for the web stream:
Step 2 — Define color ranges
Colors are defined in HSV (hue/saturation/value) color space. HSV separates the color itself (hue) from brightness, which makes detection more reliable under different lighting:Step 3 — Detection function
Convert the frame to HSV, create a mask of matching pixels, find the largest group, and draw a bounding box:cv2.inRange checks every pixel: is it within the HSV range? cv2.findContours groups the matching pixels into shapes. cv2.contourArea measures the size — we ignore anything smaller than 500 pixels to filter out noise.
Step 4 — MJPEG web stream
Serve the annotated frames as a live video stream in any browser:threading.Lock prevents the camera loop and the web server from accessing the frame at the same time.
Step 5 — Main loop
Start the camera, start the web server, and run the detection loop:Run it
Final code: color_detect.py
Click to see the complete program
Click to see the complete program
Program 2: face tracker
Build a script that detects faces and moves the pan/tilt servos to keep the face centered in the frame.Step 1 — Face detection with Haar cascades
OpenCV includes a pre-trained Haar cascade classifier for face detection. Load it at the top of the script:Step 2 — Servo helper functions
The PiCar-X API for camera servos varies between library versions. These helpers handle both:Step 3 — Proportional tracking
The tracking algorithm uses proportional control: measure how far the face is from the center of the frame, multiply by a small gain, and adjust the servo by that amount.Step 4 — The tracking loop
Detect faces, find the largest one, calculate the error from frame center, and adjust servos:Run it
http://picar.local:9000 in your browser. Stand in front of the camera and move around — the camera should physically follow your face.
Final code: face_tracker.py
Click to see the complete program
Click to see the complete program
Classical CV vs. AI
Everything today used explicit rules. The color detector only finds colors you defined in
COLOR_RANGES. The face tracker only recognizes the pattern “face” using a pre-built classifier. Neither system can learn, adapt, or recognize new objects.On Day 4, you will replace these rules with an AI that can recognize any object and describe what it sees in natural language.
