Robot Vision – Using a Pi Camera and OpenCV
local graph
Chapter 14 — Robot Vision – Using a Pi Camera and OpenCV
Section titled “Chapter 14 — Robot Vision – Using a Pi Camera and OpenCV”Robot Vision – Using a Pi Camera and OpenCV
Section titled “Robot Vision – Using a Pi Camera and OpenCV”Vision is the primary sense for many creatures, ourselves included. Adding the ability to see and process that information gives a robot interesting ways to respond to its environment.
In this chapter, we will set up our Raspberry Pi to work with the camera.
We’ll use the camera to learn about computer vision, and along the way, we will learn more about using the PID algorithm. We’ll also see how to stream camera output to a web page, so we can see what the robot is seeing and tune its results.
We will use AI with the robot and camera to follow faces with our pan-and-tilt mechanism. Then, we’ll take a different computer vision approach to track and follow colored objects.
The following topics will be covered in this chapter:
- Setting up the Raspberry Pi camera
- Setting up computer vision software
- Tracking faces with AI in Python
- Following colored objects with Python
Technical requirements
Section titled “Technical requirements”Tools and parts are specified in detail in Appendix A*:* Shopping for Robot Parts. Before we get started, make sure you have the following:
- Your robot and code from Chapter 13, IMU-Based Robot Navigation with Python
- A computer with a recent browser
- The Raspberry Pi camera module 3
- A 200 mm Raspberry Pi camera cable
- M2 stand-off kit—2 x 6 mm M2 bolts, 2 x M2 nuts, 2 x M2 * 6 + 5 stand-offs
- A pin vise drill with a 1 mm and 2 mm bit
- A set of digital calipers
- A set of screwdrivers
- Long nose flat-tipped pliers
- A kids’ bowling set—the type with differently colored pins (plain, with no pictures) as targets for color tracking
- A well-lit space for the robot to drive in
You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files are included in the downloadable code bundle.
Setting up the Raspberry Pi camera
Section titled “Setting up the Raspberry Pi camera”In this section, we will see how to install the Raspberry Pi camera onto our robot physically, wire it into the Raspberry Pi, and then set up the Raspberry Pi to get images from it.
Your robot and Raspberry Pi should be turned off before you start this section.
Physically attaching the camera to the robot
Section titled “Physically attaching the camera to the robot”In Chapter 10, Using Python to Control Servo Motors, you added a pan-and-tilt mechanism to your robot. We will mount the camera onto the front plate of this.
We will add a couple of holes to the mounting plate to bolt the camera on. We will then use the stand-offs to bolt it into place.
Could we glue this? Yes. However, this would make it far harder to replace or maintain the camera. I generally avoid glue in my robot builds, looking for modular and replaceable solutions.
The parts we will need are shown in the following figure:

Figure 14.1 – The parts needed to fit the camera module
Figure 14.1 – The parts needed to fit the camera module
Figure 14.1 shows the materials laid out: the tilt head on the robot, 2 mm bolts, stand-offs and nuts, the Raspberry Pi camera module, and a Raspberry Pi camera cable.
While making this, try not to touch the camera’s lens. Start by marking out and drilling the head. The following diagram shows where we will drill:

Figure 14.2 – Where we will drill
Figure 14.2 – Where we will drill
The preceding diagram shows the plans for holes to drill. Let’s first examine these parts:
- The pan-tilt head has outer dimensions of 36 mm by 38 mm.
- The camera hole dimensions are 21 mm apart horizontally, with 2.2 mm diameter holes. The holes are 14.5 mm apart vertically.
The combined view shows how we would put them together. The lower holes will intersect with the slots and interfere with the servo motor behind the tilt head, so we will not use them. However, we can use our mounting hardware for the top holes. We must use the stand-offs so that no pressure is applied to the connector on the back of the camera.
Now that we have seen how we would combine the parts and their dimensions, we can plan the holes. The pan-tilt head width minus the camera hole width is 36 mm – 21 mm = 15 mm. We want to center the camera, so the spacing for the holes on either side needs to be half that difference, 7.5 mm. We also want the camera to be clear of the ridge at the top of the pan-tilt head, so 5.5 mm down.
The hole diameter should be close to the M2 used for the camera; 2.5 mm is a reasonable closest common drill bit diameter. Let’s use this as a guide to make the holes:

Figure 14.3 – Marking and drilling out holes
Figure 14.3 – Marking and drilling out holes
The preceding figure shows marking and drilling out the holes. Use these steps:
- Use the calipers to measure 5.5 mm from the top of the pan-tilt head. Use a sharp point such as a craft knife to carefully scratch construction lines for the holes on the part. Do the same for a point 7.5 mm in from each side of the pan-tilt.
- Use the pin vise to carefully drill 2.5 mm holes out where the scratch lines cross on each side.
These steps can be carried out in place on the robot. The part is shown isolated here for illustrative purposes.
You are now ready to assemble this. The following diagram shows the assembly so far:

Figure 14.4 – Assembly steps
Figure 14.4 – Assembly steps
The preceding diagram shows how to assemble the stand-offs and nuts on the tilt head. The left shows this in diagrammatic form, and the right shows this on the robot. Use the flat long-nosed pliers to hold the nut in place, and finger-tighten the stand-offs into the nuts.
The next stage of the camera assembly is to insert the camera cable. The following set of photos shows how:

Figure 14.5 – Camera cable assembly
Figure 14.5 – Camera cable assembly
Follow these steps, which correspond with the panel numbering in the preceding images:
- First, gently loosen and pry open the cable-retaining clip. Fingernails should be sufficient—the clip should gently slide up.
- Align the cable. If you are looking at the back of the camera, then the blue part should be facing you, too.
- Insert the cable into the slot. The cable should gently slot in until it goes no further. Keep it straight.
- Gently push the retaining clip back in to hold the cable in place. I run a fingernail over the clip to ensure it’s evenly down.
With the camera wired, we can now assemble it onto the pan-and-tilt, as shown in *Figure 14.*6:

Figure 14.6 – Attaching the camera to the pan-and-tilt
Figure 14.6 – Attaching the camera to the pan-and-tilt
The preceding image shows the camera mounted on the robot. Here’s how:
- Slide the camera cable through the gap between the tilt head and pan base.
- Bolt the camera into place as the assembly diagram shows.
- The finished camera assembly looks like this.
You now have the camera firmly attached to the robot. You still need to wire the camera into the Raspberry Pi. See *Figure 14.*7 for help:

Figure 14.7 – Wiring the camera cable to the Raspberry Pi
Figure 14.7 – Wiring the camera cable to the Raspberry Pi
The preceding figure shows how to connect the camera to the Raspberry Pi. This is similar to the connector on the camera:
- There are two similar flat connectors on the Raspberry Pi. We are interested in the one nearest to the big block of USB connectors. Gently pry the retaining clip open using your fingernails.
- Line the camera cable up, with the blue stiff part of the cable facing the USB ports of the Raspberry Pi.
- Push the cable in gently until it will go no further.
- Ensure the cable is straight and gently push the retaining clip down.
The camera is now attached to the robot and connected electronically to the Raspberry Pi. You can now get a picture from this camera to test it!
Testing the camera
Section titled “Testing the camera”Raspberry Pi OS comes with camera support enabled. This means you can power the robot on and quickly try some interactions with the camera. Power the robot with a Raspberry Pi power supply (not from a battery).
The camera software updates frequently, so I recommend a full upgrade on the Pi first. Run this pyinfra command:
pyinfra -y inventory.py -- deploy/update_packages.pyThis will take a while to run. When it is complete, type sudo reboot and wait for the green light to come back on.
After the reboot, SSH back into the Pi and try the following:
rpicam-still --list-camerasYou should see something like this:
Available cameras-----------------0 : imx708 [4608x2592 10-bit RGGB] (/base/soc/i2c0mux/i2c@1/imx708@1a) Modes: 'SRGGB10_CSI2P' : 1536x864 [120.13 fps - (768, 432)/3072x1728 crop] 2304x1296 [56.03 fps - (0, 0)/4608x2592 crop] 4608x2592 [14.35 fps - (0, 0)/4608x2592 crop]If you see No cameras available, power down and check the wiring of your camera.
Let’s take a picture! Type rpicam‑still ‑‑immediate ‑‑output test.jpg.
This will take a photo and leave a test.jpg file on the Raspberry Pi’s filesystem.
How can we get that photo? With pyinfra —on your computer, type the following:
pyinfra inventory.py -- files.get test.jpg test.jpg -yThis will download the image to your local computer, and you can take a look at it. It should be the right way up.
Troubleshooting
Section titled “Troubleshooting”Try these steps if you are unable to get a still image:
- If you see errors here, first check that you’ve typed the commands correctly.
- If there are still errors, turn off the Raspberry Pi and check the camera wiring.
- If you get dark images, check your lighting. The Raspberry Pi camera is sensitive to light conditions and needs a well-lit space to operate. Note that none of the following tracking will work if the camera is not getting enough light.
Now that you know you can get images from the camera, let’s get Python code talking to it.
Setting up computer vision software
Section titled “Setting up computer vision software”We will need a number of software packages to work with the camera. We will also need to carefully look at the architecture of the Python program we write to process the camera data.
Installing visual-processing packages
Section titled “Installing visual-processing packages”Let’s see what these visual-processing packages are and then use PyInfra to install them:
- Python3- picamera: This offers a Python layer to talk with the Raspberry Pi camera.
- Python3-opencv: OpenCV, or Open Computer Vision, is a library of tools for creating computer vision systems. This package lets us use these tools in Python.
- Flask: We will use this to make the video available in our browser.
Installing this in PyInfra requires some changes to our packages list. Create the deploy/deploy_vision.py file with the following code:
from pyinfra.operations import apt
apt.packages( name="Install AI packages", packages=["python3-picamera2", "python3-opencv", "python3-flask"], no_recommends=True, _sudo=True,)This uses apt to install the packages. We enabled no_recommends to prevent a lot of extra software from being accidentally installed.
Save this, and with the Raspberry Pi externally powered, run pyinfra inventory.py deploy/deploy_vision.py ‑y to install it. Now we need software to talk with this.
Writing camera Python software
Section titled “Writing camera Python software”When talking about visual processing, we treat video as a series of images, called frames. The resolution of each frame will have a relationship to how much time it takes to process them, so we will be keeping the resolution quite low. Also, due to the overhead of processing images, you should not expect frame rates above 20 frames per second.
Camera data is too heavy to send over MQTT, so we need other strategies to send it. We can use MJPEG, a simple way of making a video stream available to the browser. Using MJPEG involves sending frames as a series of JPEG images, updating a single image element.
Here are block diagrams of the software system we will build:

Figure 14.8 – Camera core system
Figure 14.8 – Camera core system
*Figure 14.*8 shows a camera core system. This will be a common architecture for camera-based sensing services.
We start with a S ystem architecture, where what we plan to do is build services for detection/sensing around a camera core. The camera core (in dark gr a y) will supply frames from the camera to a processor. This processor is where we can specialize in detecting faces, colored objects, or lines. The processor will do three things:
- Update frames with annotations, such as rectangles around recognized objects
- Publish MQTT messages with what has been detected
- Potentially handle MQTT messages, configuring that detection
The camera core will then consume frames from the processor into a web server that can provide a video stream to a browser.
We will make multiple programs like this, so the darker areas will be in a common library, the camera core. We will put thecamera core and processor in the same Python app. However, the behaviors will be a separate app, so we can use multiple behaviors built around a detector.
On the right is a behavior that will use data from the sensing area to decide how to move the robot. A good example is using PIDs to drive toward a colored object, with the visual app sending colored object position and size data to the behavior. We could use the same data in another behavior that makes the pan-and-tilt look at the object instead.
The D ata flow diagram in the lower half of *Figure 14.*8 shows how specific data flows:
- Input frames flow from the camera into the processorin a format suitable for processing. We can call this sourcing frames.
- Output frames flow from the processor to a frame buffer—this ensures that the server and processor do not need to wait for each other. Output frames will include annotations such as object bounding boxes. We can call this sinking frames. It’s called sinking because it drains frames from a process.
- Buffered frames flow from the frame buffer to the server.
- Stream requests from a browser flow to the server.
- Video frames flow from the server to the browser, packaged in a format suitable for the browser.
- MQTT detection messagesflow from the processor to the behavior. This has data such as object positions.
- MQTT control messages can flow from thebehavior to the processor.
Because camera behaviors are expensive in terms of power and CPU, we will be using the launcher to start and stop these. As a more concrete decision, we will be using OpenCV for most visual processing. We will use the system Flask for our web server.
Let’s build this.
Building a Raspberry Pi camera stream system
Section titled “Building a Raspberry Pi camera stream system”It’s time to start building the code. We’ll make a camera core, which handles sourcing frames from the camera and sinking video frames to a web view:
- Create the
robot/common/camera_core.pyfile. This module implements the camera core system from Figure 14.8. We’ll import the tools to build this:We importimport timefrom multiprocessing import Process, Queuefrom flask import Flask, Responsefrom picamera2 import Picamera2import cv2from common.mqtt_behavior import publish_jsontimeso we can control looping speeds. We importmultiprocessingso we can put the web server and processor in different processes, with a multiprocessingQueueused as a buffer. We’ll see how shortly. This code imports Flask for the web server components andpicamera2to interact with the Raspberry Pi camera module. We use thecv2(OpenCV) import to prepare frames for the web server. Finally, the code imports the MQTT publish code. - This app will have some global setup variables:
The constantENCODE_PARAM = [int(cv2.IMWRITE_JPEG_QUALITY), 90]app = Flask(__name__)frame_buffer = Queue(maxsize=2)
ENCODE_PARAMis used to set the image quality for our web server. We can reduce this percentage for a faster frame output if there are issues. We create a Flask app—the web requests will use this app.frame_bufferis aQueuethat can have frames written to it and read from it simultaneously without things breaking. We can cause undefined code behavior if we use a plain frame variable, as another part of the code may try to consume a partially updated variable. The queue allows code to add a new frame, while other code can simultaneously read off a completed frame safely, - We should only buffer a new frame if the previous frame has been consumed:
This checks whether the queue is empty first, and if so, it puts the new frame in.def buffer_frame(frame):if frame_buffer.empty():frame_buffer.put(frame)
- We also need to JPG-encode frames for the web server:
Thedef encode_frame(frame):_, jpeg = cv2.imencode(".jpg", frame, ENCODE_PARAM)return jpeg.tobytes()
encode_framefunction converts raw image data (a block of memory holding color values) into JPEG usingENCODE_PARAM. The JPEG uses a lot less data than the raw frame and is a common format used by browsers. - We need to send the browser a continuous stream of frames. Flask implements this using a Python generator, a function that can be looped over:
Thedef frame_generator():while True:time.sleep(0.05)frame = frame_buffer.get()frame_bytes = encode_frame(frame)yield (b'--frame\r\n' +b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
frame_generatorfunction loops forever. For each loop, it will use thesleepfunction to slow it down so it doesn’t spin. It will then get an image frame from the buffer and wait if there is not one. The frame is encoded as bytes. This is then wrapped in a way for HTML to consume—a multipart data block. Browsers are very specific about the pattern of newline (\r\n) characters here. This is yielded, making the generated block available to a Python loop to iterate over. - The next part is to make a browser request handler to respond with this data:
This code uses the Flask@app.route("/")def stream():response = Response(frame_generator(),mimetype="multipart/x-mixed-replace; boundary=frame")response.headers.add('Access-Control-Allow-Origin', '*')return response
appto route a request to a function, with"/"representing a request to the top level of the server, routed to thisstreamfunction. Thestreamfunction returns a response. The response body contains the result offrame_generator, which loops indefinitely over frames until stopped. The response also specifies a content type with a boundary between items. This boundary must be a string of characters. We have usedframe. The boundary must match in themimetypeand the boundary (‑‑frame) in the content (step 5). - The next section of code is used to start the Flask server in a process:
This code starts Flask’sdef start_server_process():server = Process(target=app.run, kwargs={"host": "0.0.0.0","port": 5001})server.start()return server
app.runin a separate process, specifying0.0.0.0so it will accept all incoming requests and port5001. - Next, we need a function to set up the camera:
This function accepts adef setup_camera(size):camera = Picamera2()config = camera.create_video_configuration(main={"format": 'RGB888', "size": size})camera.configure(config)camera.start()return camera
sizeparameter, which will be the width and height of the video frames to get from the camera. It sets upPicamera 2with this size. The video format is set up for OpenCV asRGB888, which specifies 8 bits for each of the red, green, and blue channels. We store this with some default video configuration, and use that to configure the camera, then start the camera producing video frames and return thecameraobject. - We now tie this all together in a function to start the camera core:
It accepts two parameters: adef start(processor, size):camera = setup_camera(size)server = start_server_process()try:while True:frame = camera.capture_array("main")buffer_frame(processor(frame))finally:server.terminate()server.join()
processorfunction andsize. Thisprocessorfunction will be called with each frame. This prepares the camera with the function from s tep 8, and the server process from step 7. It then has atry/catchblock to ensure the server process is stopped. In thetry, there’s awhileloop, which will get a new frame every loop from the main camera. It will pass that frame to theprocessorfunction. The processor function is expected to return a processed frame, which this function buffers, so the loop in step 5 can consume them. - This code controls which port our server is on:
Thedef camera_app_url(client, userdata, message):publish_json(client, "camera_view/url", "http://learnrob3.local:5001/")
camera_app_urlfunction is an MQTT handler that, when called, will publish the location of the camera app. You will need to substitute your own Pi hostname or IP address here.
This camera app core will let us build a number of visual-processing examples. However, before things get complicated, let’s make a simple camera view.
Building a camera view
Section titled “Building a camera view”Adding a camera view to our manual_drive page will make driving the robot more fun and useful. The camera view will also allow us to test important parts of the camera core that we’ve just built. There will be a small Python part to configure the core we built, and a change to the manual drive page to start, stop, and display the camera view.
Let’s make the simplest processor to support this:
- Create the
robot/camera_view.pyfile. - Start by importing OpenCV, our camera core, and the MQTT helpers:
import cv2from common.camera_core import start, camera_app_urlfrom common.mqtt_behavior import connect
- We are going to draw a green cross-hair in the middle of the frame. We need to have a few constants describing it:
TheSIZE = (704, 364)MIDDLE = (SIZE[0] // 2, SIZE[1] // 2)GREEN = (0, 255, 0)CROSS_SIZE = 10
SIZEconstant will be the size of our frames. We can make higher-resolution frames, but smaller frames are easier for the Raspberry Pi to process. We calculate theMIDDLEconstant once, so we can draw something there. We set up aGREENcolor constant and useCROSS_SIZEto specify how big the crosshair will be. - Next, we build the processor, a function that accepts a frame and draws the crosshair on it:
This uses OpenCV to draw a horizontal line and then a vertical line onto the frame in green, then returns it.def draw_crosshair(frame):cv2.line(frame,(MIDDLE[0] - CROSS_SIZE, MIDDLE[1]),(MIDDLE[0] + CROSS_SIZE, MIDDLE[1]),GREEN, 2)cv2.line(frame,(MIDDLE[0], MIDDLE[1] - CROSS_SIZE),(MIDDLE[0], MIDDLE[1] + CROSS_SIZE),GREEN, 2)return frame
- The last bit of this code connects the processor to the core and starts it all:
This demonstrates processing video in the same app as handling MQTT messages, with an endpoint to ask for the URL of the camera stream.if __name__ == "__main__":client = connect()client.subscribe("camera_view/url/get")client.message_callback_add("camera_view/url/get", camera_app_url)camera_app_url(client, None, None)start(draw_crosshair, SIZE)
- Let’s add a camera view to our manual drive page. Open the
robot_control/manual_drive.htmlfile. - Find the line starting with
<div id="joydiv"and add this above it:We now have start/stop buttons for the camera, and a div to show the camera in.<button id="start">Start</button><button id="stop">Stop</button><div id="camera_view"></div> - Find the line
<script type="module">; we will replace everything from here to the line starting withvar joystick. - Add the following to connect the buttons to the MQTT launcher service:
import { connect, publish_when_clicked } from './mqtt_client.js';let mqttClient = connect();publish_when_clicked(mqttClient, "start", "launcher/start", "camera_view");publish_when_clicked(mqttClient, "stop", "launcher/stop", "camera_view");
- Get a variable reference to the
camera_viewdiv:const camera_view = document.getElementById('camera_view'); - Add code to set the location of the view to a URL provided over MQTT, by subscribing and handling its message:
When themqttClient.subscribe('camera_view/url');mqttClient.on('message', (topic, message) => {switch (topic) {case 'camera_view/url':const location = JSON.parse(message);camera_view.innerHTML = \`<img src='${location}'/>\`;break;}});
camera_view/urltopic message is received, it uses the payload to create animg(image) tag with this location inside thecamera_view div. Why do we ask for aurlhere and send it in when the camera view Python service starts? If our page loads before we start the service, the service needs to tell the page where to find the camera view (or to replace an empty one). If our page loads after the camera view service is running, we need the page to ask it for a new message; otherwise, it will never be told about the message. We also don’t want the page to display a broken image link before the camera view is ready. - Publish a message requesting the URL as the web page starts:
mqttClient.publish('camera_view/url/get', '');
- After this line should be the
var joysticklines you had from before.
You will now need to extend the PyInfra deployments to send our new view service to the Raspberry Pi:
- Open
deploy/deploy_services.pyand find the list of services. - Add the following entry here:
code = files.put(name="Update camera view code",src="robot/camera_view.py",dest="robot/camera_view.py")deploy_service("camera_view", "robot/camera_view.py",False, common.changed or code.changed)
You can deploy this all by using pyinfra with the deploy_services script.
Go to the index and load the manual drive. You may need to use C trl + S hift + R (or C md + S hift + R) to reload the page. When you press the start button, you should see the camera view, as shown in *Figure 14.*9:

Figure 14.9 – Screenshot of joystick plus camera view
The screenshot has the joystick vertically under the screen, which is suitable for PC and phone.
Notice that the window view is much brighter than the window frame. Strong light, such as sunlight, can drown out other things that you want the camera to recognize. You should see the green cross in the middle, drawn with OpenCV.
You can now drive your robot while seeing through the camera.
Troubleshooting
Section titled “Troubleshooting”If you are unable to make this work, for example, you see a dead image link or no link, check the following:
- Ensure you have updated the location URL to the hostname or IP address of your Raspberry Pi.
- Ensure you’ve been able to get a still image from the camera.
- Check that you have installed all the required software.
- Use
journalctland the browser JavaScript console to look for errors.
We’ve built a system here that can run background tasks while streaming video and handle MQTT messages. We can now use the same system to build more interesting camera apps. Next, we’ll see how to track faces.
Tracking faces with AI in Python
Section titled “Tracking faces with AI in Python”There are multiple ways to write face tracking systems. The Viola-Jones Haar Cascade technique uses image differences and, with the right model, can deal with forward-facing or profile faces, but not both together. It is quick, but not particularly robust or accurate.
However, we can now use AI neural network models to get more stable results. We aren’t going to dive deep, but we are going to quickly examine what a neural network is and how to integrate one, running on the Raspberry Pi, into your Python code.
What is a neural network?
Section titled “What is a neural network?”A neural network (or ANN, which stands for a rtificial n eural n etwork) is a system that models brain cells. The following diagram in *Figure 14.*10 shows a simple one:

Figure 14.10 – An artificial neural network
Figure 14.10 – An artificial neural network
The preceding figure shows an artificial neural network. These networks consist of neurons, which are processing elements that accept inputs and combine them to produce an output, usually by calculating a weighted sum.
A neural network is usually made of layers, with an Input layer that has information from our system for the neural network to process, a number of H idden layer (s) performing the processing, and an O utput layer, producing output our robot could use.
Connections between the neurons carry the outputs of neurons to the inputs of others, using a weight determining how much influence its signal has on the receiving neuron. A weight can increase, reduce, or neutralize an input’s effect.
A neuron computes its output by multiplying each incoming value by its connection weight and summing the results. The neuron adds a bias and may apply an activation function, a mathematical function that shapes the output. The resulting output becomes the input for the next layer of the network.
Setting the weights and biases of a neural network can be complicated. This small network has only 10 neurons, yet it has 24 weights. There are many possible combinations of weights and biases to configure even this small network.
Training is used to configure neural network parameters. They are typically trained by showing the network many examples and their expected outputs. Learning algorithms then adjust weights and biases based on how close the network’s output is to the expected result.
Neural networks are great at matching patterns or picking things out of messy and noisy input, such as pictures from the real world. They tend to be far bigger than the 10-neuron network that we mentioned, and can take many months to train on very powerful computers.
A trained set of weights plus architecture is known as a model, modeling some aspect of the world in a useful way. People share useful models and their training data on the internet, which makes for a great library for us to use. A model zoo is a library of models for a particular problem or for fitting a particular neural network size.
Building and training a neural network will take a long time and is outside the scope of this book. Instead, we’ll focus on how to use existing neural network models in our robot.
Building a neural network-based processor
Section titled “Building a neural network-based processor”We already have OpenCV on our robot, and while we’ve used it for the trivial task of drawing a line, it is designed for computer vision tasks. OpenCV can make use of neural network models, feeding camera data into them.
Let’s see the architecture we are going to build here:

Figure 14.11 – The face detection service
Figure 14.11 – The face detection service
The preceding diagram shows how the processor is implemented for face detection. The input frames from the camera are fed to a face detection model. This model responds with a set of face detections, that is, a list of faces, where they are located, and how confident the model is that they are a face. Sometimes, it may find things that aren’t quite faces, so we will filter detections based on a confidence threshold.
The next stage will publish detectionsover MQTT as a list of faces and their locations so other behaviors can use them. It will also draw boundary rectangles around the faces, making a new annotated frame that goes into the frame buffer.
Choosing and downloading a neural network model
Section titled “Choosing and downloading a neural network model”We will be using a small and light neural network model, known as Yu N et, from the OpenCV model zoo at https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet. The model is trained for face detection, while being small.
This model has been quantized; that is, its weights have turned into simple 8-bit numbers that need a lot less memory and processing to make use of. This means that it is less precise than the full model, but in practice, it’s still very good. The model output fits with our expected face detections output, creating simple rectangles around areas that may contain a face.
Let’s use PyInfra and make this model available on our robot:
- Open the
deploy/deploy_vision.pyfile. - In the imports, we need to add the
filesoperation:from pyinfra.operations import apt, files - We can now download and store the model. Add this at the end of the file:
This URL was retrieved by finding the model (files.download(name="Download Face detection model",src="https://github.com/opencv/opencv_zoo/raw/refs/heads/main/models/face_detection_yunet/face_detection_yunet_2023mar_int8.onnx",dest="face_detection_yunet_2023mar_int8.onnx")
int8) version, then copying the raw link. If you chose another model, it is important that you use the raw link. I suggest that you use the recommended model to get things working first. - Run
pyinfra inventory.py deploy/deploy_vision.pyto deploy it.
With this model loaded, we can use it to detect faces.
Using a neural network in OpenCV
Section titled “Using a neural network in OpenCV”We are going to make the face detector by using this model and our camera core framework. Let’s see how:
- Create the
robot/face_detector.pyfile. - We’ll start with imports:
These imports are familiar, withimport osimport cv2from common.camera_core import start, camera_app_urlfrom common.mqtt_behavior import connect, publish_json
cv2being the OpenCV library. We are importingosso we can check whether the file is present. - We set up some constants for our processor in a similar way to the camera view:
You’ve seen theSIZE = (704, 364)GREEN = (0, 255, 0)MODEL_FILE = "face_detection_yunet_2023mar_int8.onnx"SCORE_THRESHOLD = 0.7
SIZEandGREENconstants from before. We are going to draw boundary boxes for detected faces inGREEN. We then useMODEL_FILEto specify where to find the model file, which should match thedestparameter indeploy/deploy_vision.py. The final constant isSCORE_THRESHOLD. This is the minimum confidence score we will filter for faces, with1meaning all faces. If this is too low, the system may detect many false positives (seeing faces where there are no faces). If this is too high, then the model will likely reject faces we want to detect. - We’re going to put our detector in a class, still in
robot/face_detector.py:Thisclass FaceDetector:def __init__(self):assert os.path.exists(MODEL_FILE), "Model file not found"self.detector = cv2.FaceDetectorYN.create(MODEL_FILE,"",SIZE,SCORE_THRESHOLD,)self.client = connect()FaceDetectorclass will prepare our detector when created. In the__init__method, we start by checking that the model file is present—OpenCV tends to leave less useful error messages, so adding this assert first helps us. After checking that the model exists, we prepare the detector model. Because the YuNet model is well known to OpenCV, it has aFaceDetectorYNwrapper that we can use. We must tell it where the model file is, what the image size will be, and the score threshold. We store the initialized model inself.detector. We then make a shared connected MQTT client. - We can now build a processor to use this detector. Let’s start with sending a frame in to get detections:
This function starts by sending the frame to our detector, which returns a potential error and a data structure with detected faces. There’s an undocumented return value that we also throw away with the underscore (def processor(self, frame):_, faces = self.detector.detect(frame)
_). - We can now process the faces and create boundaries:
This checks whether we have faces, and if so, it extracts the items that we want. There are 15 parameters returned for each face; however, we want theif faces is not None:detected = [(int(face[0]), int(face[1]),int(face[2]), int(face[3]), face[-1]) for face in faces]
x,y,width,height, andscore. So, we index with these numbers and store them in thedetectedvariable. - We then draw boundaries around the detections:
For each of the detected faces, we draw a rectangle on the frame in green. We then draw the score above this in the same color.for x, y, w, h, score in detected:cv2.rectangle(frame, (x, y), (x + w, y + h), GREEN, 1)cv2.putText(frame, f"{score:.2f}", (x, y - 10),cv2.FONT_HERSHEY_SIMPLEX, 0.5, GREEN, 2)
- Now we send this list over MQTT, converting our list into a dictionary on the way:
publish_json(self.client, "face_detector/faces", [{"x": int(x), "y": int(y), "w": int(w), "h": int(h), "score": float(score)}for (x, y, w, h, score) in detected])
- If we find no faces, we need to send an empty list over MQTT instead:
else:publish_json(self.client, "face_detector/faces", [])
- We now return the frame with the painted-on boundaries:
return frame
- We give the class a
startmethod to set up MQTT and the camera core:def start(self):self.client.subscribe("camera_view/url/get")self.client.message_callback_add("camera_view/url/get", camera_app_url)camera_app_url(self.client, None, None)start(self.processor, size=SIZE) - We can finish this file by creating the processor class and starting it:
This code is wrapped in a check to ensure it only runs when the detector is started as the main program. As we are using multiple processes for the camera core, we need to ensure it doesn’t try to recreate the processes multiple times. The check forif __name__ == "__main__":detector = FaceDetector()detector.start()
mainensures this will only happen in the main outer process. - Make an entry to deploy this into
deploy/deploy_services.py:code = files.put(name="Update face detector code",src="robot/face_detector.py",dest="robot/face_detector.py")deploy_service("face_detector", "robot/face_detector.py",False, common.changed or code.changed) - Now we need a page to view this. Create the
robot_control/face_detector.htmlfile. - The page combines a
camera_viewdiv with launcher buttons:This has a camera view, start and stop buttons, and MQTT handling like previous web control examples.{% extends "robot_control/page.html.j2" %}{% block title %}Face detector{% endblock %}{% block content %}<button id="start">Start</button><button id="stop">Stop</button><div id="camera_view"></div><script type="module">import { connect, publish_when_clicked } from './mqtt_client.js';let mqttClient = connect();publish_when_clicked(mqttClient, "start", "launcher/start", "face_detector");publish_when_clicked(mqttClient, "stop", "launcher/stop", "face_detector");const camera_view = document.getElementById('camera_view');mqttClient.subscribe('camera_view/url');mqttClient.publish('camera_view/url/get', '')mqttClient.on('message', (topic, message) => {switch (topic) {case 'camera_view/url':const location = JSON.parse(message);camera_view.innerHTML = \`<img src='${location}'/>\`;break;}});</script>{% endblock %} - Add a menu link for this in
robot_control/index.py. - Run
pyinfra inventory.py deploy/deploy_services.pyto upload it. - Go to the menu and load this page, then click S tart.
If you bring your face into view of the robot camera, you should be able to see your face with a boundary around it, which follows you as you move your face around:

Figure 14.12 – Face detection screenshot
The preceding screenshot shows the face detector app, with my face highlighted by a boundary. I’m not in the middle of the shot, but we’ll get the robot to fix that later.
The detector behaves best if you are not too close to the camera, so your whole face is in view. It also prefers good light conditions. My face score of 0.89 is pretty high.
Check for errors with journalctl if you aren’t seeing anything. Try with multiple faces, and you should see a boundary around each. You can try covering your face and see the score change. You can also try holding up photos of people to see if it can detect multiple faces.
We now have a face detector, which is also outputting MQTT data. You can examine the data with mosquitto_sub:
$ mosquitto_sub -u robot -P robot -t 'face_detector/faces' -vface_detector/faces []face_detector/faces []face_detector/faces []face_detector/faces []face_detector/faces [{"x":371,"y":134,"w":208,"h":282,"score":0.8943767547607422}]face_detector/faces [{"x":175,"y":145,"w":208,"h":287,"score":0.8943767547607422}]face_detector/faces [{"x":187,"y":140,"w":202,"h":296,"score":0.8943767547607422}]face_detector/faces []face_detector/faces [{"x":538,"y":164,"w":92,"h":102,"score":0.9160295128822327},{"x":394,"y":160,"w":76,"h":97,"score":0.9016427397727966}]I’ve abridged the output, but you can see a few different situations here. Initially, there are no faces in the shot, so an empty list is sent. Then, I move my face into the shot, and it shows the location and score for it. I briefly move my face out of the shot to find a photo, and go back into the shot with the photo, which results in two faces being detected.
This shows us that it works, but it’s going to be more interesting to use it in a behavior. Let’s get the robot to center a face in the camera.
Tracking the face
Section titled “Tracking the face”We’ve got the robot to find faces, but what if we could get the robot to look at them? We have a servo mount pan-and-tilt mechanism for the camera. Let’s link the servo motor movement to the position we saw a face at using PIDs.
The following diagram shows how this behavior will work:
![]()
Figure 14.13 – Face-tracking behavior
Figure 14.13 – Face-tracking behavior
The preceding figure shows how this behavior will work. The key on the right helps with reading this diagram.
We start on the left, where the program will receive a list of face locations over MQTT. From this list, it will extract the largest face. The program will then calculate the middle coordinate of this face.
The X coordinate of the face is compared with the horizontal middle of the frame, with the error converted to a servo control signal by the pan PID. This signal will control the pan servo, moving the camera left or right to try to align the face.
The Y coordinate undergoes a similar comparison with the vertical middle, going through a tilt PID to generate a control signal for the tilt servo, moving the camera up or down.
The resulting camera moves will change the location of the faces, which the face detector (outside this program) will pick up, producing feedback as a new set of face coordinates.
With the correct PID tuning, the servo motors will move to put the largest face in the middle and keep it there.
Let’s build this code:
- Start by creating the
robot/look_at_face.pyfile. - Add the imports for a standard PID-controlled MQTT behavior:
import timeimport jsonimport numpy as npfrom common.mqtt_behavior import connect, publish_jsonfrom common.pid_controller import PIDController
- We are going to restrict the range of the servo motors with some constants:
pan_range = 70tilt_range = 50center_x = 704/2center_y = 364/2
- The behavior class will set its starting point to the middle of the camera:
class LookAtFaceBehavior:def __init__(self):self.face_x = center_xself.face_y = center_y
- Now we create a
look_at_facefunction, starting with the PIDs:The PIDs here hold a servo at a position relative to where the face is, so we only use the integral term. Also, the tilt PID is negative to match the servo motor orientation.def look_at_face(self, client):pan_pid = PIDController(0, 0.006)tilt_pid = PIDController(0, -0.006) - Let’s get into the main loop for this:
The error values for each are calculated by subtracting the current face position from the center of the camera.while True:# Thinkpan_error = center_x - self.face_xtilt_error = center_y - self.face_y
- We need to make the PID controls and keep the range sensible:
We are using the servo control output here for the servo motor position; however, we need to clip the range so it doesn’t go far enough to damage the servo motors or camera cable.pan_position = pan_pid.control(pan_error)tilt_position = tilt_pid.control(tilt_error)pan_position = np.clip(pan_position, -pan_range, pan_range)tilt_position = np.clip(tilt_position, -tilt_range, tilt_range)
- We can now act on this:
# Actpublish_json(client, "motors/servo/pan/position", pan_position)publish_json(client, "motors/servo/tilt/position", tilt_position)time.sleep(0.05)
- The next part of the code needs to deal with sensing and extracting the face. Create a new method and start by loading an MQTT message:
def on_faces_detected(self, client, userdata, msg):# Senseface_data = json.loads(msg.payload)
- We need to find the largest face:
This code uses the width multiplied by the height of each face to find the largest face. Thelargest_face = max(face_data, key=lambda face: face['w'] * face['h'], default=None)
maxfunction here is being used so that it finds the largest item in a list (face_data) using the provided key. We provide a default ofNonein case of an empty list. - If we have a face, we can get its middle:
if largest_face:self.face_x = largest_face['x'] + (largest_face['w'] / 2)self.face_y = largest_face['y'] + (largest_face['h'] / 2)
- Otherwise, we set the coordinates to the center (which will stop the camera from moving):
else:self.face_x = center_xself.face_y = center_y
- We need a
startmethod to connect it to MQTT:def start(self):client = connect()client.subscribe("face_detector/faces")client.message_callback_add("face_detector/faces", self.on_faces_detected)self.look_at_face(client) - Now the code needs to create the behavior from the class and start it:
behavior = LookAtFaceBehavior()behavior.start()
- Add a section for this to
deploy/deploy_services.pyforpyinfra:code = files.put(name="Update look at face behavior code",src="robot/look_at_face.py",dest="robot/look_at_face.py")deploy_service("look_at_face", "robot/look_at_face.py",False, common.changed or code.changed) - Next, we need a page for this. Open the
robot_control/face_detector.htmlfile. In thecontrolssection, we’ll add two more buttons:<button id="start_look_at">Start looking at face</button><button id="stop_look_at">Stop looking at face</button> - In the JavaScript button handlers, add two more launcher connections:
publish_when_clicked(mqttClient, "start_look_at", "launcher/start", "look_at_face");publish_when_clicked(mqttClient, "stop_look_at", "launcher/stop", "look_at_face");
- You are now ready to send this with
pyinfra ‑y inventory.py deploy/deploy_services.py. - When it’s done, launch the R obot control menu and go to the Face detector menu option.
- Press the Start button to start the detector, followed by the Start looking at face button.
You should see something like the following:
![]()
Figure 14.14 – Face-tracking screenshot
Figure 14.14 – Face-tracking screenshot
The preceding screenshot shows the additional two buttons for looking at faces. My face is now in the middle of the shot, and unless I move quite fast or past the limits of the pan-tilt motors, it will stay in shot.
Troubleshooting
Section titled “Troubleshooting”This behavior integrates many different components, so I strongly recommend that you have all prior examples for servo motors, PID control, and camera face detection working.
If the face-tracking behavior does not work as expected, check the following:
- If the lighting is poor, the robot will have a hard time seeing anything. If you have multiple faces, it may jump between them.
- If you find it is sliding off or away from faces, making for an amusing antisocial robot behavior, this can mean the PID values are too high; reduce the integral by a small amount. If it’s taking too long to seek, then the integral may be too low.
- Low power in batteries can cause the servo motors to behave poorly, so if you see a lot of jittering, check that your battery is charged or your power supply and cable are good.
- If nothing is happening at all, use
journalctl ‑u look_at_face ‑fvia SSH to check for errors and verify your code there.
You’ve now built an AI-based face tracking behavior. However, not every visual processing task needs AI. Let’s see how some simpler image manipulations can do it.
Following colored objects with Python
Section titled “Following colored objects with Python”Let’s build a system to detect objects in a certain color range, and then we’ll add a behavior to follow them.
The component architecture is the same as the face tracker; however, the internals of the detector are different, and the follower drives the main motors instead of the servo motors.
Test this on a floor, as this behavior can drive a robot off a desk.
Let’s start with the colored object detector.
Turning a picture into information
Section titled “Turning a picture into information”We are using colored pins from a kids’ bowling set. They come in nice, bright primary colors. I will use green as an example. We will start with just a picture. However, a set of transformations to the data is needed to turn the picture into information the robot can use to make decisions.
A pipeline is a good way to design a set of transformations. Let’s look at the color tracking as an image-processing pipeline in the following diagram:
![]()
Figure 14.15 – Color-tracking pipeline
Figure 14.15 – Color-tracking pipeline
The preceding pipeline shows how we’ll go from a camera image to a list of colored object detections. An important concept in object detection is to extract the desired information and throw away as much unnecessary detail as we can to get what the behavior needs.
We start with an initial phase: a c olor - filter ing pipeline to get a color mask.
The system converts the image from the camera to the Hue, Saturation, Value (HSV) color space, where hue represents where the color is on a color wheel, saturation is how intense the color is between gray and vivid, and value is how bright it is.
RGB (or BGR) images are tricky to filter, as getting the different light and saturation levels of a particular hue (say, the blues) is not viable. The figure shows the hue color wheel above this step. In OpenCV terms, hues go from 0 to 179. The color wheel shows that 0 is red, and around 30 is the greens, for example.
After converting to HSV, we then filter the colors in the image with a mask, highlighting pixels in a particular range. It will output white if the object is in the range, or black if it’s not. Above this step, the unshaded region on the hue color wheel shows the range, with the masked output next to it. There is a function in OpenCV to do this: cv2.inRange. This gives us a binary output, a masked image, which is suitable for drawing around in our system.
The next phase is o bject position and size extraction. Our pipeline then uses the contours system to draw around our masked image, finding the boundary points of our object. OpenCV provides a cv2.findContours function to do this, which returns a list of shapes, each defined by its outlines. The pipeline step shows the contours (taken from the mask) drawn onto the image. Note how light and shade have made the bottom of the bowling pin a bit rough as it doesn’t quite fit the mask.
The processing pipeline then takes the contours (outlines) and uses cv2.minEnclosingCircle to draw circles around them. We take these circles and output by drawing them onto the output frame, and also sending them to MQTT as a list of detections with a radius and size.
A caveat about red objects: we will use green because red is slightly tricky, as it requires two masks. The hues for red cross a boundary between 179 (the upper limit of our hue range) and 0 (the lower limit), so we would have to mask the image twice and then combine these with an or operation. You could use the cv2.bitwise_or function to try masking red.
Let’s build this detection system.
Creating a colored object detector
Section titled “Creating a colored object detector”We will be able to build this using the camera_core as we did for faces. Use the following steps to write and test this code:
- Create the
robot/colored_object_detector.pyfile. - We can start with familiar imports and constants:
import cv2from common.camera_core import start, camera_app_urlfrom common.mqtt_behavior import connect, publish_jsonSIZE = (704, 364)GREEN = (0, 255, 0)
- Then, we add a class definition, starting with
init, setting up some more for this detector:We use theclass ColoredObjectDetector:def __init__(self):self.low_range = (30, 90, 50)self.high_range = (80, 255, 255)self.client = connect()low_rangeandhigh_rangevalues for the color filter (as seen in Figure 14.1 5). Colors that lie between these HSV ranges would be white in the masked image. We are looking for a green hue between 25 and 80. Saturation is 70 to 255—any lower and we’d start to detect washed-out or gray colors. The value (or light) is 25 (very dark) to 255 (fully lit). - Like the face detector, we then need a processor. Let’s break this down:
This first step converts the frame to an HSV frame.def processor(self, frame):frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
- Next, we need to mask the colors falling between the low and upper ends of our range:
masked = cv2.inRange(frame_hsv, self.low_range, self.high_range)
- Following this, we extract the contours (outlines) from the mask:
We asked for contours in thecontours, _ = cv2.findContours(masked, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
maskedimage. The next parameter specifies that we want them as a list withcv2.RETR_LIST; other modes return hierarchies we don’t currently need. The contours can also be approximated in various ways; however,cv2.CHAIN_APPROX_SIMPLEapproximates many points simplified into lines, as we aren’t that interested in every single point. - We are only interested in rectangles, so we can look at objects. We can get OpenCV to give us a boundary rectangle for each contour:
rectangles = [cv2.boundingRect(cnt) for cnt in contours]
- We then draw each rectangle on our frame in green, similar to the faces:
[cv2.rectangle(frame, (x, y), (x + w, y + h), GREEN)for x, y, w, h in rectangles]
- We also send this as JSON over MQTT:
publish_json(self.client,"colored_object_detector/detections",[{"x": int(x), "y": int(y), "w": int(w), "h": int(h)}for x, y, w, h in rectangles],)
- We then return the frame:
return frame
- The
startmethod looks very similar to the face detector:def start(self):self.client.subscribe("camera_view/url/get")self.client.message_callback_add("camera_view/url/get", camera_app_url)camera_app_url(self.client, None, None)start(self.processor, size=SIZE) - Then we start the behavior:
if __name__ == "__main__":detector = ColoredObjectDetector()detector.start()
- We need to add this new detector to
deploy/deploy_services.py:code = files.put(name="Update colored object detector code",src="robot/colored_object_detector.py",dest="robot/colored_object_detector.py")deploy_service("colored_object_detector","robot/colored_object_detector.py",False, common.changed or code.changed) - We’ll add a page to control this detector in
robot_control/colored_object_detector.html:This code should be familiar as it is using previously seen elements.{% extends "robot_control/page.html.j2" %}{% block title %}Colored object detector{% endblock %}{% block content %}<button id="start">Start</button><button id="stop">Stop</button><div id="camera_view"></div><script type="module">import { connect, publish_when_clicked } from './mqtt_client.js';let mqttClient = connect();publish_when_clicked(mqttClient, "start", "launcher/start", "colored_object_detector");publish_when_clicked(mqttClient, "stop", "launcher/stop", "colored_object_detector");const camera_view = document.getElementById('camera_view');mqttClient.subscribe('camera_view/url');mqttClient.publish('camera_view/url/get', '')mqttClient.on('message', (topic, message) => {switch (topic) {case 'camera_view/url':const location = JSON.parse(message);camera_view.innerHTML = \`<img src='${location}'/>\`;break;}});</script>{% endblock %} - Add a link to that page in
robot_control/index.html. - Use
pyinfra ‑y inventory.py deploy/deploy_services.pyto deploy this.
Find a green pin from a kids’ bowling set, then load it and press the S tart button. You should see something as in the following screenshot:

Figure 14.16 – Color detector showing a bowling pin
Figure 14.16 – Color detector showing a bowling pin
In the preceding screenshot, I’ve pressed the S tart button, and I’m holding a green bowling pin in front of the camera. It has drawn a boundary rectangle around the pin but has made boundary rectangles around features on the pin too. If we use MQTT to subscribe to the colored_object_detector/detections topic, we will see these too:
colored_object_detector/detections []colored_object_detector/detections [{"x":587,"y":453,"w":53,"h":27}]colored_object_detector/detections [{"x":418,"y":400,"w":1,"h":1},{"x":419,"y":396,"w":3,"h":3},{"x":406,"y":302,"w":1,"h":1},{"x":407,"y":295,"w":3,"h":3},{"x":404,"y":284,"w":2,"h":3},{"x":407,"y":282,"w":3,"h":3},{"x":403,"y":252,"w":1,"h":2},{"x":405,"y":248,"w":1,"h":1},{"x":439,"y":230,"w":13,"h":15},{"x":402,"y":213,"w":108,"h":267}]The preceding sample of MQTT messages shows no detections, a single detection, or a list of them. The last message is quite likely, so our behavior will need to filter these further.
Troubleshoot using journalctl until you are able to see something like the preceding, then we can start building a behavior with it. But first, the PID needs a further feature.
Upgrading the PID with windup limiting
Section titled “Upgrading the PID with windup limiting”We are going to add another feature to our PID. Sometimes, the integral on a PID can increase while the plant (in this case, the motors) cannot keep up. This can cause large overshoots. This is known as integral windup.
We can deal with this in our PID system by adding an optional windup limit. Let’s see how:
- Open
robot/common/pid_controller.py. - In the
__init__method, we can add the windup limit:We default the limit todef __init__(self, proportional_constant, integral_constant=0, smart_reset=False,windup_limit=None):self.proportional_constant = proportional_constantself.integral_constant = integral_constantself.integral = 0self.smart_reset = smart_resetself.windup_limit = windup_limitNone, so we can detect when it’s not been set. - We then need to add this to the
controlmethod:In this code, andef control(self, error, time_difference=1):if self.smart_reset and np.sign(error) != np.sign(self.integral):self.reset()self.integral += error * time_differenceif self.windup_limit is not None:# Prevent integral windupself.integral = np.clip(self.integral,-self.windup_limit, self.windup_limit)return self.proportional_constant * error \+ self.integral_constant * self.integralifstatement checks that the windup limit is active and, if so, constrains it to within that limit. Errors should center around the 0 mark, so this code can assume the limit applies to both positive and negative numbers.
Now that we have an upgraded PID, we can use it to build a color follower.
Following a colored object
Section titled “Following a colored object”We can now use this detected item with a little bit of code to follow the object. This works in a fairly similar way to the look-at-face behavior. The following diagram shows how:

Figure 14.17 – Color-following behavior
Figure 14.17 – Color-following behavior
The preceding diagram uses the same key and style as Figure 14.1 3. We are now selecting the size and location of the detected objects, but are still picking out the largest.
The object size goes into a speed PID controller, which also has an object size reference as its set point. Depending on the difference between the expected size and actual size, this PID will output a speed for the motors, optimizing the width to be the same as the object size reference. That way, the robot will maintain a distance from an object of a known size. This is a base speed for both motors.
Let’s build this. We are going to make the code in larger steps, as there is a lot of familiar code:
- Create the
robot/object_follower.pyfile. - Set up the imports and a few constants:
I obtained theimport timeimport jsonfrom common.mqtt_behavior import connect, publish_jsonfrom common.pid_controller import PIDControllercenter_x = 704 / 2object_size_ref = 370
object_size_refvariable value by inspecting the width output from MQTT when I had the object as close as I wanted it to the robot. - We can now start building the behavior class:
We set the initial object size toclass FollowObjectBehavior:def __init__(self):self.object_x = center_xself.object_size = None
None, as we’ve yet to detect an object. - We can make the
Sensesection update those values when an object is detected:In thedef on_object_detected(self, client, userdata, msg):# Senseobject_data = json.loads(msg.payload)largest_object = max(object_data,key=lambda object: object['w'] * object['h'],default=None)if largest_object:self.object_size = largest_object["w"]self.object_x = largest_object['x'] + (largest_object['w'] / 2)else:self.object_size = Noneon_object_detectedmethod, we use the same technique for finding the largest object as we did for face detection. When we have the largest object, we setobject_sizeto the largest object’s width. We setobject_xto the middle of the object. If there was no object, we set the size toNone. - We can now start building the main following loop. First, we prepare the method with two PIDs:
Here, we are setting fairly high windup limits, but quite low PID values. The low PID values relate to the object X being hundreds of pixels, while the motor control values are fractions between -1.0 and 1.0.def follow_object(self, client):speed_pid = PIDController(0.0003, 0.0007, smart_reset=True,windup_limit=120)direction_pid = PIDController(0.0003, 0.0007, smart_reset=True,windup_limit=120)
- Continuing in the
follow_objectmethod, let’s ensure the camera is looking forward with the pan-and-tilt system:publish_json(client, "motors/servo/pan/position", 0)publish_json(client, "motors/servo/tilt/position", 0)time.sleep(0.1)publish_json(client, "motors/servo/pan/stop", None)publish_json(client, "motors/servo/tilt/stop", None) - We start the main loop in
follow_objectby handling the no-object case by stopping the motors:while True:# Thinkif self.object_size is None:# If no object detected, stop the robotpublish_json(client, "motors/wheels", [0, 0])time.sleep(0.05)continue - We now calculate the errors and control signals through the PIDs:
# Calculate errorsdirection_error = center_x - self.object_xspeed_error = object_size_ref - self.object_sizedirection = direction_pid.control(direction_error)speed = speed_pid.control(speed_error)
- We can log the system via MQTT to help us tune it:
# Actpublish_json(client,"object_follower/log",{"direction_error": direction_error,"speed_error": speed_error,"direction": direction,"speed": speed,},)
- After calculating all of this, we can send the output to the wheels:
You’ll see an extrapublish_json(client, "motors/wheels/fake", [speed - direction, speed + direction])time.sleep(0.05)
/fakein the topic. This behavior will drive right off the table if not quite right, so we are just keeping an eye on it before letting it truly loose! - We now need to add a
startmethod and start the behavior using it:def start(self):client = connect()client.subscribe("colored_object_detector/detections")client.message_callback_add("colored_object_detector/detections", self.on_object_detected)self.follow_object(client)behavior = FollowObjectBehavior()behavior.start() - We need to add this file to our
deploy/deploy_service.pytool:code = files.put(name="Update object follower behavior code",src="robot/object_follower.py",dest="robot/object_follower.py")deploy_service("object_follower", "robot/object_follower.py",False, common.changed or code.changed) - We then update
robot_control/colored_object_detector.htmlwith buttons to start it. Add these after the camera start/stop buttons:<button id="start_look_at">Start following</button><button id="stop_look_at">Stop following</button> - We also need to add some click handlers in the JavaScript, linking the buttons to the launcher:
publish_when_clicked(mqttClient, "start_look_at", "launcher/start", "object_follower");publish_when_clicked(mqttClient, "stop_look_at", "launcher/stop", "object_follower");
- Send this all with
pyinfra ‑y inventory.py deploy/deploy_services.py. - When this has been sent, load the Colors object detector page, and click the S tart button to see the view.
- Then, via SSH and
mosquitto sub(ormqttuion your computer), subscribe toobject_follower/logandmotors/wheels/fake. - What you should be seeing is quite small values when your pin is close to the middle, and the motors are turning to put it in the middle. They shouldn’t be sending silly motor values over 1.0. If these values are too large, reduce the
PandIvalues on the PID. - When your pin is not in view, the motors should stop and be set to
0. - When you are happy with this, remove
/fakefrompublish_jsonso the motors will be active. Ensure the robot is on battery power (you may need to power down and switch to battery) and put it on a floor. - Send the updated code with
pyinfraagain. - You should now be able to put the pin in front and have the robot try to keep it in the middle and at a distance. Move the pin closer and it will back off; move it further away and the robot should follow as long as it is still in view.
You now have a robot that can follow and maintain a distance from a colored object. Let’s ensure things are working.
Troubleshooting
Section titled “Troubleshooting”If you run into problems, try these:
- Verify that all the previous examples have worked.
- Use
journalctlto view the behavior logs and check for errors. - If the system is running into things, reduce the
PorIvalue on the speed PID. If it’s sweeping past the pin, reduce the values on the direction PID. - If it’s jumping around erratically, look for green things in the background—a window with trees can easily confuse this behavior.
- Low light values may also cause it to have problems detecting the object.
Now that you have it running, try to see what happens when you use your hands to cover the object—it’s not as robust as the face detector, as it has no knowledge of the object’s shape, only blobs of color that match a mask.
Let’s now summarize what we’ve learned.
Summary
Section titled “Summary”In this chapter, we’ve seen how to attach a camera to the Raspberry Pi and get images from it. We’ve seen how to pass images along to a browser as a video.
We then saw two ways to extract information from video frames, using a neural network AI model for faces, or color manipulation and detection for colored objects.
You’ve enhanced the PID with windup limited to prevent a PID-based system from having a big buildup.
In the next chapter, we are going to use the camera and another image detection technique to follow lines!
Challenges
Section titled “Challenges”The following challenges will let you build a better robot, try some exciting experiments, and learn more from the techniques in this chapter:
- We’ve used the YuNet face detector model. The model zoo at https://github.com/opencv/opencv_zoo has models to recognize facial expressions, hand gestures, or body poses. Consider how you would integrate a different model into the processor.
- You’ve tracked green objects. Try other colors. Red will be the trickiest due to it falling across the 0 mark.
- Try to swap these behaviors and have the robot look up and follow faces, and have another behavior to look at colored objects.
- Use techniques from prior chapters to graph the motor outputs and better tune the PIDs.
- Use the config store and controls from prior chapters to make the PIDs, reference sizes, and colors tracked configurable.
- Tune the color mask (and servo motor angle) to detect a colored patch on your feet. Perhaps also have the robot follow a little way behind you.
- We made a lot of use of the servo motors, and added some range restrictions on them; try to move this limiting to the Inventor HAT service.
Further reading
Section titled “Further reading”Please refer to the following for more information:
- Find the Pi camera mechanical specification at https://datasheets.raspberrypi.com/camera/camera-module-3-standard-mechanical-drawing.pdf.
- Find the Raspberry Pi camera 2 manual at https://datasheets.raspberrypi.com/camera/picamera2-manual.pdf.
- See https://www.raspberrypi.com/documentation/computers/camera_software.html#rpicam-still for more information on taking still pictures with the Pi camera.
- Python multiprocessing is well documented at https://docs.python.org/3/library/multiprocessing.html.
- See this OpenCV tutorial on using contours: https://docs.opencv.org/3.4/dd/d49/tutorial_py_contour_features.html.
- I strongly recommend The Official Raspberry Pi Camera Guide at https://magazine.raspberrypi.com/books/camera-guide-2nd-edition to see more options for the Raspberry Pi camera.
- For more OpenCV experiments, try Computer Vision Projects with OpenCV and Python 3: Six end-to-end projects built using machine learning with OpenCV, Python, and TensorFlow by Matthew Rever. You may have to adapt examples for the Raspberry Pi camera and frame system, or try more powerful computer vision on your bigger PC.