Line-Following with a Camera in Python
local graph
Chapter 15 — Line-Following with a Camera in Python
Section titled “Chapter 15 — Line-Following with a Camera in Python”Line-Following with a Camera in Python
Section titled “Line-Following with a Camera in Python”In the last chapter, we saw how to use a camera to follow and track objects. In this chapter, we will use the camera core system we built, with a new image processor, to create a line-sensing vision system and build a line-following behavior from its output.
We will look at where robots use line-following and how it is useful. We will also learn about some of the different approaches taken to sensing and following paths in different robots, along with their trade-offs. To test this, we will set up line-following tracks.
We will learn about some different algorithms to use and then choose a simple one. We will make a data flow diagram to see how it works, collect sample images to test it with, and then tune its performance based on the sample images. Along the way, we’ll see more ways to approach computer vision and extract useful data from it.
We will enhance our PID code, build our line detection algorithm into a robot driving behavior, and see the robot running with this. The chapter closes with ideas on how you can take this further.
Line-following is a common use case for robotics, both in industrial robotics and in autonomous robot competitions. This will allow you to exercise working with visual processing and PID control. I will also introduce you to the powerful Jupyter Notebook system on the way.
In this chapter, we’re going to cover the following main topics:
- Introduction to line following
- Making a line-follower test track
- Capturing test images for computer vision
- Line-following computer vision pipeline
- Line-following with the PID algorithm
- Adding a derivative to the PID
Technical requirements
Section titled “Technical requirements”For this chapter, you will need the following:
- The robot and code from *Chapter 14,*Robot Vision – Using a Pi Camera and OpenCV
- Access to a computer printer
- Some tape to adhere sheets to the floor
- A computer with Wi-Fi
- A floor space – around 1 meter square
- Good lighting
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.
Introduction to line following
Section titled “Introduction to line following”Before we start building code, let’s find out about line-following robot behaviors, where and how systems use them, and the different techniques for doing so.
What is line following?
Section titled “What is line following?”Some robots are required to stay on specific paths within their tasks. It is simpler for a robot to navigate a line than to plan and map whole rooms or buildings.
In simple terms, line following is the ability to follow a marked path autonomously. These can be visual markers, such as blue tape or a white line on a black road, or non-visual markers like hidden wires or magnets. As the robot drives along the line, it will continually look for where the line ahead is and correct its course to follow that line.
In robot competitions, racing on lines is a common challenge, with speed being critical after accuracy. Top algorithms can speed through complex line courses in seconds!
Usage in industry
Section titled “Usage in industry”By far the most common usage of line-following behavior is in industry. Robots known as automated guided vehicles (AGVs) need to follow set paths for many reasons. These tasks can include warehouse robots staying on tracks between aisles of stacked products or factory robots staying on paths clear of other work areas. The line may mark a route between a storage shelf and a loading bay or a robot charging station and the robot’s work area:
[figure owed: Figure 15.1 – IntelliCart – a line-following industrial robot by Mukeshhrs [Public domain]]
Figure 15.1 – IntelliCart – a line-following industrial robot by Mukeshhrs [Public domain]
Figure 15.1 – IntelliCart – a line-following industrial robot by Mukeshhrs [Public domain]
IntelliCart, shown in Figure 15.1, uses bright blue guide tape. This image is dated, but good for visualizing the principle in use. Modern robots either use under-floor hidden magnetic tracks or other guidance methods to navigate fixed factory routes. However, following a hidden track can use similar algorithms.
The route may include choice points, with multiple lines coming from a particular location. Depending on its task, the robot may need extra clues to sense that it has reached these points. An engineer can set up a repeated path for a fully automated system.
Having these demarcated means that you can set safety boundaries and be clear on where humans and robots do or do not interact; this means that robots will rarely operate outside of well-understood areas.
While map models like SLAM and visual language models are starting to see more use in industrial settings, line following is a simple and robust way for robots to navigate a factory floor. This robustness allows it to be faster, more reliable, and repeatable than SLAM-based approaches in situations where the route is pre-planned and predictable.
Now that you have some idea of where line following is used, let’s make some trade-offs on how we will detect a line.
Line sensing and trade-offs
Section titled “Line sensing and trade-offs”Like so many aspects of robot design, we will need to make hardware trade-offs. We are aiming to follow lines on the floor, making use of the platform we have to do so, and explore visual processing systems. What approaches could we take and what are the trade-offs?
- Using a line - following sensor: Adding a dedicated line-following sensor in the form of a couple of line detectors, or better yet, an array of 5 to 7 sensors. Some of these may also require adding analog inputs to our robot. Spark F un has a line follower array that fits our robot well, but costs more than the camera. These make line-sensing algorithms simpler; however, they do not make use of the hardware we have, and would not make much use of visual processing.
- Using the VL53L5CX: This distance sensor array can sense the reflectance or brightness of objects, so it could be positioned to look down and detect lines. This would require us to reconfigure our robot when we want to follow lines, and then reconfigure it back when we want to sense distances. This is also an unproven and unusual use of the sensor.
- Using the Raspberry Pi camera: The Raspberry Pi camera is the best opportunity to explore a visual processing approach to this, and is already present on the robot. We will need to modify the robot once so the camera can look down past the end of the robot, but having done so, the pan and tilt mechanism can move the camera between looking down and looking up. The camera’s position is a little forward of the wheels, too, and it comes with software complexity.
We chose the Raspberry Pi camera since it makes good use of the sensors we already have on the robot, and allows us to refine and practice working with visual processing. We will see how to reconfigure the camera position in the Moving the c amera f orward section in this chapter. This approach requires more processing power and code for the detection than simpler methods, along with suitable light conditions to be effective, however, it also demonstrates how a computer vision-based approach can be used.
Now that we know which sensor we will use, we can create a test track that our robot can follow.
Making a line-follower test track
Section titled “Making a line-follower test track”Since you will be making your robot follow a line, we need to start with a section of the line to follow. The track will be used at the beginning to test our line detection algorithm and can then be extended to more exciting tracks when we turn on the motors and start driving along the line.
What I will show you in this section is easy to make and extendable. It allows you to experiment with different line shapes and curves and see how the robot responds. You can even experiment with different color and contrast options.
There are many methods to make this track:
- Using black/dark tape on a white sheet: Insulating tape or black duct tape works. The sheet can be paper, foam, or other white materials. Thick, large format flipchart sheets are good for this.
- Marker or painted line: Use a black marker or paint to trace a thick line on a white/light sheet. Keep paint or fill even.
- White line on a dark surface: Use white paint on a dark/black sheet. You may need a few coats of paint to ensure it has good contrast. Keep the painted line even.
- Purchase a sheet: There are pre-printed line-following sheets, like the Kitronik*:MOVE* Mat.
- Printed line - following sheets: Print out line-following sheets and stick them with tape – if you have a printer, you can likely print A4/letter size. I recommend https://robotsquare.com/2012/11/28/line-following/ with sections that can be arranged into custom layouts. Use good, heavy paper or printable card sheets for this.
- Large-format printed track: If you have access to a large-format printer, or can pay for printing, you may be able to print a large-format sheet.
With all these methods, there are some important rules to follow:
- The line should be clearly contrasted in brightness against the background. If the robot can’t contrast it, it can’t see it.
- The line should have the same thickness. Somewhere between 15 and 30 mm is a good thickness. Different thicknesses can confuse line-following systems.
- Ensure that the dark sections aren’t too glossy or reflective. Highly reflective surfaces can make dark areas appear bright.
- Ensure the surface is not going to be disturbed or damaged as the robot drives on it. The robot will be driving around the track and may also steer a lot to align to the track; you do not want the sheet to become damaged or move.
The method I will use is a printable A4 card with a computer printer, and tape to adhere sections together.
Track sections can be downloaded from RobotSquare: https://robotsquare.com/wp-content/uploads/2012/11/linefollowtiles.pdf. These are provided free by RobotSquare.
Start with a really simple design, like an oval, until you have the algorithm working well. After that, you can choose to make more complex designs or aim for a faster robot.
I don’t recommend printing them yet until you have a design. You are likely to require more than one of a particular section, and none of the other segments. Let’s make a design so we can plan that.
Designing the simple track
Section titled “Designing the simple track”Using tiles to design a track means we can combine the tiles into different configurations. A simple rectangle with rounded corners is enough to demonstrate and tune a line-following robot.
The PDF contains a grid for you to design your own line track. I arranged tile screenshots into Inkscape, my preferred drawing tool:

Figure 15.2 – Line-following track layout
Figure 15.2 – Line-following track layout
The preceding figure shows a simple line-following track design, a rectangular design with smooth curves. Using the tiles above, you will need to print the following:
- 4 x straight pieces – page 2
- 4 x curve pieces – page 3
You can print those on the card stock, then carefully cut. In most systems, in the print dialog, writing 2,2,2,2,3,3,3,3 will get the right pages printed out. Ensure it’s black and white and single-sided printing.
The slash/box corner areas show where you can apply tape to join the track. I used a backing sheet of spare foam board, but a thick paper/card sheet will do. This makes it convenient to move, but you can also use a white background to avoid gaps confusing the robot. Sticky-tac works as a temporary setup.
You can join these together in different ways, like a robotic train set! These will be fun to test with later as you further tune and play with the line-following code. However, I encourage you to keep it simple to get it initially working.
Now that we have a test track ready, we have a few small changes to make to the robot.
Moving the camera forward
Section titled “Moving the camera forward”We are going to use the camera for line following; however, our Raspberry Pi camera’s current pan/tilt position would have it looking down into the sensor assembly, which would obscure part of the line we are following. We are going to need to move things around a bit to accommodate it.
As you develop any robot, its capabilities, add sensors, or adapt its uses to new challenges, rearranging a robot’s layout is going to be a common activity. Occasional rebuilds are part of the process of robot-making.
Let’s see what our new goal looks like:

Figure 15.3 – Rearranging the robot
Figure 15.3 – Rearranging the robot
The preceding figure shows how we are rearranging the robot. The P an/ Tilt base has been moved forward, so it is able to look past the front of the robot and sensor. The Sensor bracket has moved down and reversed, coming up from under the top plate, with the Sensor bracket sharing screws with the Pan / Tilt base. This allows the Sensor to be recessed back and no longer in the camera’s view when looking down.
The E xploded diagram shows how the parts are assembled together for this. Let’s break it down a bit:
- You will need to unbolt the sensor bracket and sensor, along with the Pan/T ilt base, from the chassis.
- Place two long bolts in the Pan / Tilt base down through the chassis holes to the reversed sensor bracket.
- You should be able to initially hand-tighten the nuts to this. You can then screw the long bolts and secure the Pan / Tilt base and sensor bracket to the chassis plate. Center the sensor plate horizontally before fully tightening.
- You can now assemble the sensor back onto the bracket – bolt the standoffs to the bracket, then bolt the sensor to the standoffs.
The robot is now able to pan to look down and see the line. Now that the camera is better positioned, we can capture some test images from the robot’s point of view.
Capturing test images for computer vision
Section titled “Capturing test images for computer vision”In this section, we will look at how and why to use test images. We will write our first chunk of code for this behavior and try it on test images from our robot’s camera. These tests will prepare us for using the code to drive the robot.
Why use test images?
Section titled “Why use test images?”So far, our computer vision work has been written directly with robot behaviors; this is the end goal, but sometimes, you want to try the visual processing code in isolation.
This can be useful for exploring algorithms, bug fixing, performance testing, or just trying competing algorithms with many images.
For performance testing, trying the same image 100 times or the same set of images will give consistent results for performance measures to be meaningful. Testing algorithms directly on the camera view from the robot comes with problems. First, this will be new data every time, resulting in unexpected or potentially noisy results, making it hard to compare with previous runs or sensing algorithm changes. If the robot is moving, you would not want it doing so while responding to unstable algorithm data.
When running the robot, adding new test images to see what would happen is fascinating, especially if we later find the detection behaved unexpectedly.
So now that we know why we use them, let’s try capturing some test images.
Capturing test images
Section titled “Capturing test images”You may recall, from the previous chapter, using rpicam‑still to capture an image. We are going to do the same here. First, we want to put our camera into a new position, facing down, so we are looking down onto the line.
This section requires the setup from *Chapter 14,*Robot Vision – Using a Pi Camera and OpenCV.
We can use PyInfra to help us capture images. Turn the motor power on to the Raspberry Pi, then follow these steps:
- SSH into the Raspberry Pi.
- Use
mosquitto_pubto set the pan forward:mosquitto_pub -u robot -P robot -t motors/servo/pan/position -m 0 - Also using
mosquitto_pub, tilt the camera down:Note that this is smaller than 90, to look past the sensors.mosquitto_pub -u robot -P robot -t motors/servo/tilt/position -m 80 - Put the robot onto your test line track. Try to position the robot so that the camera is right above the line.
- In the SSH terminal, type the following to capture a test image:
$ rpicam-still --immediate --output line_1.jpg
- You can now download this image to your PC:
pyinfra inventory.py -y -- files.get line_1.jpg line_1.jpg
Figure 15.4 shows a test image, which is also used for the preceding examples:

Figure 15.4 – A test image of a line
Figure 15.4 – A test image of a line
Figure 15.4 shows one of my test images. Note that the line is roughly starting in the middle of the picture, but it isn’t exact and doesn’t need to be. It’s also blurry, as this is closer than the camera’s intended focus range. This is not a problem for line-following.
It’s worth building a collection of these as you experiment with line-following. My collection looks like this:

Figure 15.5 – A collection of test images
Figure 15.5 – A collection of test images
The collection above shows a few other test images. Each is labeled with what conditions were changed. The line is in different positions, some curves, different lighting conditions, and some really difficult, noisy ones with a carpet. I even added some with no line to follow, so we can see that it behaves sensibly.
Now that we have test images, we can write code to test them with!
Line-following computer vision pipeline
Section titled “Line-following computer vision pipeline”As we did with the previous computer vision tasks, we will visualize this as a pipeline. Before we do, there are many methods for tracking a line with computer vision.
Camera line-tracking algorithms
Section titled “Camera line-tracking algorithms”There are many ways to follow a line. As always, there is a trade-off between complexity, speed, and accuracy. Here is a small selection of methods we could use:
- Using a neural network line detector: There are neural network models that will produce line results given an image with a line to follow. At the time of writing, these did not give gains above the other algorithms in the trade-off. They are also easy to confuse.
- Using C anny edge detection and Hough line detection: An edge detection algorithm, such as the Canny edge detector, can be run across the image, turning any transitions it finds into edges. OpenCV has a built-in edge detection system if we want to use it. The system can detect dark-to-light and light-to-dark edges. Noise produces strange results here.
- Finding differences along rows: This is a pragmatic shortcut to edge detection, using only a particular row. By finding the difference between each pixel along a row in the image, any edges will show significant differences. This works well for a sensor directly below the robot’s wheels, but not so well in front.
- Using contours and rectangles: This is a technique that builds upon the tools we used for the colored object detector, fitting a minimum area rectangle with orientation around the line after masking.
The contours and rectangles option is stable and builds upon the computer vision techniques we have used.
Let’s explore this algorithm with the test images we captured.
Exploring our test images
Section titled “Exploring our test images”There is an amazing tool for exploring test images with Python: Jupyter Notebook allows you to experiment and see how the image stages work. We can then convert our findings into code to drop into our robot system.
Setting up a Jupyter Notebook
Section titled “Setting up a Jupyter Notebook”On the computer you are running pyinfra from, in the same folder as your robot code, run the following:
poetry add opencv-python-headless numpy matplotlib notebookThis may take a short while to install. We’ve seen OpenCV and NumPy on the robot. The Matplotlib library lets us make simple plots; while it’s too slow to run on the robot behind the web pages, it’s handy here. Let’s look at what the Jupyter Notebook does for us. Run the following to start it:
poetry run jupyter notebookThis will output a lot, but eventually give you a link to open. Click this to see Jupyter in your browser. You should see the following:

Figure 15.6 – Jupyter file browser
Figure 15.6 – Jupyter file browser
The screenshot shows Jupyter Notebook with a folder tree. Click New to create an experiments folder and open the folder. Copy all your captured line pictures into this folder.
Then click New again, and this time select Python 3. You should see the following screen:

Figure 15.7 – Jupyter Notebook
Figure 15.7 – Jupyter Notebook
The preceding figure shows two screenshots of the Jupyter Notebook. Jupyter Notebooks are made of cells. You can click in a cell to type code. I also recommend naming this notebook line_detection by clicking on the Untitled name.
We can type and test code here. Let’s add some imports to this first cell. We will need to import NumPy to process the image numerically, OpenCV to manipulate the image, and Matplotlib to graph the results:
import cv2import numpy as npfrom matplotlib import pyplot as plt
GREEN = (0, 255, 0)RED = (255, 0, 0)There are also some helpful color definitions that we can use while plotting.
The screenshot in Figure 15.7 shows a “cell” where code can be added. While my mouse is hovering, there’s also a button to add new cells.
There’s a label Untitled at the top of the screen (in the first screenshot from the top); click on this to name the notebook. I suggest calling it line_detection.ipynb.
When you click Play, a little [1] will appear next to the first cell, which shows it has run first, and a new cell has appeared to add further code. Note that if you start the notebook again in a later session, you’ll want to click the Restart and re run all cells button.
In the following section, we will be running each cell after we put code in it, before adding a further cell.
In the new cell, let’s load and prepare an image. Add this code:
image = cv2.imread('line_1.jpg')resized = cv2.resize(image, (320, 240))gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)plt.imshow(gray, cmap="gray")We have used OpenCV imread to load one of our example images. We resize it to a smaller image; this will make things quicker, and our algorithm does not need to be super high resolution as the lines are expected to be wide.
In computer vision, it’s useful to use the lowest resolution you can to do the job. Every additional pixel adds more memory and processing to cope with. At 320*240, this is 76,800 pixels. The Raspberry Pi camera can record at 4608 x 2592 – 12 million pixels – 155 times as much data! We need this to be quick, so we keep the resolution low.
We convert it to grayscale since we are working with pixel intensities with cvtColor. In grayscale, each pixel is a light intensity. Then we ask plt (from Matplotlib) to show the image, ensuring Matplotlib displays it as gray too. You get interesting colors if you leave out the cmap element.
When you run it, you’ll see the following:

Figure 15.8 – Image plotted in Jupyter Notebook
Figure 15.8 – Image plotted in Jupyter Notebook
The screenshot shows the new cell, and its result after running it. The cell gets a Cell run number. The same number is used for the Cell results below. In the cell results, there is some Python output. In this case, the more useful output is the Plot. The Plot is right here in the cell results with the code, which is the key reason we are using this notebook. We can explore code and its results together here.
The pixels are now numbered with helpful axes.
Now we have plots, let’s extract some data from our image. We’ll start by masking in a similar way:
masked = cv2.inRange(gray, 0, 50)plt.imshow(masked, cmap='gray')When you run the cell, you should see an image like this:

Figure 15.9 – The line with a mask
This mask should be familiar from the colored object masking. We’ve made the threshold 50, however, depending on lighting and other parameters, you may need to change this value. Tune it carefully, as higher values may start to identify shadows. The higher the value is, the lighter a shade can be to be considered part of a line.
We can then find contours in it:
contours, _ = cv2.findContours(masked, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)largest_contour = max(contours, key=cv2.contourArea)cv2.drawContours(resized, [largest_contour], -1, GREEN, 1)plt.imshow(resized)Here, we are once again finding the contour, filtering for the largest, and plotting it onto the resized image:

Figure 15.10 – Line with contour plotted
The preceding image shows the contour around the line. The contour has been found, but it is a little noisy. We can next take this and fit an oriented minimum area rectangle around it. Add this code into the next cell:
rect = cv2.minAreaRect(largest_contour)box = cv2.boxPoints(rect)box = np.intp(box)cv2.drawContours(resized, [box], 0, GREEN, 2)plt.imshow(resized)This will find a minimum enclosing rectangle oriented to match the line. It’s then converted to a box for plotting, as it’s not readily in a format to draw the rect.

Figure 15.11 – Drawing the rectangle around the line
The preceding image shows a green thicker-lined rectangle superimposed over the contour of the line. It’s slightly angled to match the angle of the line. It doesn’t hug the line and doesn’t account for any perspective, but it should be good enough.
For us to actually follow a line, we need to know where the line is. It would be a line that goes down the middle of this rectangle. Let’s extract that information in a new cell:
((center_x, center_y)), (width, height), theta = rect
if width < height: theta += 90.0 length = heightelse: length = width
theta = (-theta) % 180int(theta), int(length)The first line is extracting the components of our rectangle: center_x and center_y, then a width and height, and then theta, an angle in degrees.
The OpenCV function minAreaRect can consider the width or the height as the longest side. However, we always want a line that matches the longest side. So we check and rotate the angle 90 degrees if the height is greater than the width. The length variable now always holds the longest edge.
Our robot poses are based on Y = 0 being the bottom of a map. OpenCV images have Y = 0 at the top of the map. We must reflect the Y-axis of the coordinates.
We have to adjust the angle and reflect it to account for this by negating theta. A line has two possible directions; however, we are only interested in the end pointing forward from the robot, so we use the modulo operation % to ensure it stays between 0 and 180.
The last two lines are just so Jupyter can show us these values: (91, 239).
The angle is 91 degrees counterclockwise from the east. The length 239 is a pixel short of 240, which again correlates with the rectangle being slightly up from the bottom of the image.
Let’s add a cell to draw a line from that and see how well it matches:
theta_rad = np.deg2rad(theta)end = ( int(center_x + length/2 * np.cos(theta_rad)), int(center_y - length/2 * np.sin(theta_rad)))cv2.line(resized, (int(center_x), int(center_y)), end, RED, 2)plt.imshow(resized)We need to convert our angle to radians, since most math functions work in radians. We can use this to find the line end point. This is half the length of the line, in the direction of theta, away from the center of the line. Recalling from Chapter 12, Encoder- B ased Localisation with Python, if we know a starting coordinate (cx, cy), a length, and an angle in radians, the end point is:
end x = center x + length/2 * cos(theta)
end y = center y - length/2 * sin (theta)
Note that we negate the second length term to reverse the Y between the pose coordinates and image coordinates. We then need to convert these to integers, along with the center, to be able to plot this as a line. We plot it onto the resized image in red and redraw it. The following image shows what that looks like:

Figure 15.12 – Direction line plotted onto the original image
The preceding screenshot shows the test image with the contour, and rectangle drawn on it in green. It now has a red line plotted showing the direction and end point of the detection. The red line fits best to the rectangle.
Troubleshooting
Section titled “Troubleshooting”We should troubleshoot before testing other images:
- If you see text like
Command 'jupyter' not found, check that you have installed it in the corresponding poetry environment. - If you see a
NameError, it can mean you’ve missed a cell, missed running an earlier cell, or mistyped Python in a cell. - If you see the line at 90 degrees to the above, or two lines, this may be due to rerunning cells without clearing previous data. This will modify the
thetavariable and theresizedimage variable. For a clean run, rerun cells from the image load (imread) cell downward to prevent this. We will be making the algorithm a bit easier to tune in the following subsection. - If you do not get a good, clean mask, try ensuring the test image is well-lit or adjusting the threshold until the mask is clean. The value 50 was arrived at in my tests, but different backgrounds and lighting may require another threshold.
Now that we have a single line, we are going to try this with multiple test images.
Testing the algorithm with multiple images
Section titled “Testing the algorithm with multiple images”The more images we test with, the more confidence we create in our algorithm, or we have more opportunities to tune it for a better result. Create a cell with a list of the test image names you have collected:
images_to_test = [ "line_1.jpg", "line_2.jpg", "line_3.jpg", "line_4.jpg", "line_5.jpg", "line_6.jpg", "carpet_line1.jpg", "empty_carpet.jpg", "empty_gray.jpg"]The more different images you have in this list, the more you’ll be able to see how the algorithm behaves. If you find the robot behaves strangely in a particular situation, get the image from that, and add it back into the list. Note that I have a couple of items without a line in them to see how things behave without a line.
Now we can add a cell which will put our algorithm so far into a function, so we can use it many times:
def test_image(resized): gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) masked = cv2.inRange(gray, 0, 50) contours, _ = cv2.findContours(masked, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) if not contours: print("No contours found") return None
largest_contour = max(contours, key=cv2.contourArea) rect = cv2.minAreaRect(largest_contour) box = cv2.boxPoints(rect) box = np.intp(box) cv2.drawContours(resized, [box], 0, GREEN, 2)
((center_x, center_y)), (width, height), theta = rect if min(width, height) < 10: print("Detected line is too small") return None
if width < height: theta += 90.0 length = height else: length = width
theta = (-theta) % 180
theta = np.deg2rad(theta) end = ( int(center_x + length/2 * np.cos(theta)), int(center_y - length/2 * np.sin(theta)) ) cv2.line(resized, (int(center_x), int(center_y)), end, RED, 2) plt.imshow(resized)This is using code you’d tried above. However, we’ve added some verification checks. First, in some test images, it may not find contours, meaning there is not a line, so we return None. Second, in some images, a contour may be found that is not a line, so those are discarded, and None is returned too. With the algorithm in a single function, tuning it will be easier to use and rerun.
The end of this test draws the line and the image. We can then use this in a for loop to test them. Add it in a new cell:
for image_name in images_to_test: plt.figure(figsize=(10, 5)) plt.subplot(1, 2, 1) print(f"Testing image {image_name}") image = cv2.imread(image_name) resized = cv2.resize(image, (320, 240)) plt.imshow(resized) plt.subplot(1, 2, 2) test_image(resized)This will create a fresh figure for each test image. A figure can have subplots, letting us put a picture of the image before and after side by side, which is helpful for testing.
We can then load, resize, and show the initial image, then test it and show the result beside it. When you run it, you’ll see some text output showing images being tested along with pictures of each. For my test images, I get the following text:
Testing image line_1.jpgTesting image line_2.jpgTesting image line_3.jpgTesting image line_4.jpgTesting image line_5.jpgTesting image line_6.jpgTesting image carpet_line1.jpgTesting image empty_carpet.jpgNo contours foundTesting image empty_gray.jpgDetected line is too smallAs there are a lot of images, Jupyter may choose to put a scrollbar against the output, and you may need to scroll down to see them all. The following screenshot shows some of my tests:

Figure 15.13 – Testing many images
Figure 15.13 – Testing many images
The preceding image shows the different outputs of many images we tested. Each input-output pair is numbered, with the numbers kept clear of the defining features:
- This test image is a straight line going slightly to the right.
- A test curve is detected as a line going to the right. The line shows a useful trajectory.
- This is a curved image going to the left. Note that it crosses the left boundary instead of the top of the image. It is also poorly lit, but the algorithm copes well.
- This curved image has confused other algorithms. It should be an unlikely image from a robot unless the robot has come off the line. This algorithm has correctly shown where the end point is, which the robot should aim for.
- In this image, I’ve made it trickier with a very noisy carpet. The algorithm has coped and still shown a clear end point for the red line.
- Having no line should be clearly identified; the right plot is what we see when a line cannot be detected.
- Having no line on a carpet means ensuring the algorithm does not match noise as being part of the line. The algorithm has correctly responded here.
The last screenshot shows it correctly finding a line, or no line. Try this on many test images, and it should be relatively stable. While it’s possible to find images that break it, we can stop here as we now have a good enough algorithm.
As you can see, testing the code on test images has allowed us to learn a lot about the system. By taking the same pictures and trying different parameters and pipeline changes, you can optimize this for different scenarios. As you experiment more with computer vision, make this a habit.
Let’s build a pipeline around what we’ve learned so far.
The pipeline
Section titled “The pipeline”We can visualize the way we process data as a pipeline. The following diagram shows how we process camera data for this method:

Figure 15.14 – Image processing pipeline for finding a line
Figure 15.14 – Image processing pipeline for finding a line
In *Figure 15.*1 4, we have turned our experiments into a pipeline. We’ll need to perform this on each frame as it comes in. These are steps you have explored in the notebook.
It starts with the Camera, from which we Resize image (s) to a 320-by-240-pixel resolution. We then Convert to grayscale (the image, that is), so we only need to consider the brightness. We apply the Mask or threshold, so we have a binary image.
We can then use the binary image to Detect contours and use the contours to Fit a rotated rectangle to the image.
The rectangle parameters allow us to find a length and angle, and importantly, Find the end point for the line. Our robot can aim for that end point.
Let’s use what we know with our camera app system to build a line detector. Create a new file robot/line_detector.py with the following content:
import cv2import numpy as np
from common.camera_core import start, camera_app_urlfrom common.mqtt_behavior import connect, publish_jsonWe started with familiar imports for OpenCV, NumPy, our camera core, and MQTT. Continue with a set of constants:
SIZE = (704, 364)GREEN = (0, 255, 0)RED = (0, 0, 255)MIDDLE = 320 / 2We define the camera image sizes, as we did for the Camera view app, along with the same colors we used in the Jupyter Notebook. We resized the image to 320 by 240 in the notebook, so the middle is half this width. We start our detector in a LineDetector class:
class LineDetector: def __init__(self): self.client = connect()The class LineDetector starts with a constructor preparing an MQTT client. We can then add a method to find a line:
def find_line(self, resized): gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) masked = cv2.inRange(gray, 0, 50) contours, _ = cv2.findContours(masked, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) if not contours: return None
largest_contour = max(contours, key=cv2.contourArea) cv2.drawContours(resized, [largest_contour], -1, GREEN, 2) rect = cv2.minAreaRect(largest_contour) ((center_x, center_y)), (width, height), theta = rect if min(width, height) < 10: return None
if width < height: theta += 90.0 length = height else: length = width
theta = (-theta) % 180
theta = np.deg2rad(theta) end = ( int(center_x + length/2 * np.cos(theta)), int(center_y - length/2 * np.sin(theta)) ) cv2.line(resized, (int(center_x), int(center_y)), end, RED, 2) return end[0] - MIDDLEThe find_line method uses the algorithm we prototyped in the notebook, which should be familiar; however, there are a few differences:
- We’ve skipped drawing the rectangle, going directly for the contour and line drawings.
- When we find a line, we return the line position; when we don’t, we return
None, which we can use to mean no line. - We’ve chosen to return how far the x component of the line end is from the middle; however, you could modify this to return
thetainstead, or some combination of them.
This will be a camera core based detector, so it needs a processor method:
def processor(self, frame): resized = cv2.resize(frame, (320, 240)) position = self.find_line(resized)
publish_json( self.client, "line_detector/position", {"line": position}, )
return resizedThe processor method resizes each frame, sends it to the find_line method, and then publishes the return to MQTT as a JSON payload.
The class needs a start method to set up MQTT connections and start the camera processing:
def start(self): # Look down publish_json(self.client, "motors/servo/pan/position", 0) publish_json(self.client, "motors/servo/tilt/position", 80)
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)As always, the start method sets everything in motion and prepares the service to run. When it starts, before the subscriptions are made, it asks the servos to position the camera forward and down, using the same values we found when gathering test images.
Finally, we can end with the normal creation and start section:
if __name__ == "__main__": detector = LineDetector() detector.start()We need to add this service to deploy/deploy_services.py:
code = files.put( name="Update line detector code", src="robot/line_detector.py", dest="robot/line_detector.py")deploy_service("line_detector", "robot/line_detector.py", False, common.changed or code.changed)Next, we will need a viewer for it in robot_control/line_detector.html:
{% extends "robot_control/page.html.j2" %}{% block title %}Line detector{% endblock %}{% block content %} <button id="start_detection">Start detection</button> <button id="stop_detection">Stop detection</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_detection", "launcher/start", "line_detector"); publish_when_clicked(mqttClient, "stop_detection", "launcher/stop", "line_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 %}This is a familiar control page, similar to those we’ve used for other detectors.
Add a link in the menu in robot_control/index.html:
<li><a href="line_detector.html">Line detector</a></li>And then send it with pyinfra:
pyinfra inventory.py -- deploy/deploy_services.pyWe can use a pyinfra command to follow the log as we click start here:
pyinfra inventory.py exec -- journalctl -u line_detector -fThis will let us see the log without needing to SSH to the robot for it.
Now, click the Start detection button on the web control page, and put an interesting line segment under the camera. The camera should orient itself to look down at the line, then you should see the following screen:

Figure 15.15 – Line detector control screenshot
The preceding screenshot shows the line detector control page. Below the Back to menu link and title are two control buttons:
- Start detection: It starts the line detection service and will update the display
- Stop detection: It stops the line detection service
The main view from the camera is a live updating view of what is below the camera, with the contour and line drawn. If you move the line around, the line, and contour should follow.
You should also be seeing the output in your journalctl log terminal while this runs. Let’s make sure this is working.
Troubleshooting
Section titled “Troubleshooting”These troubleshooting tips should help if it’s not working:
- Check the console log you are getting for any errors and verify the Python code.
- If the buttons do not do anything, ensure you have made the
deploy_services.pychange from above. - Check also for errors in the browser inspect JavaScript console. Typos in the servo motor position could lead to these.
- If you are not seeing a camera image at all, and there is no console error, verify that the camera view in Chapter 14*,* Robot Vision — Using a Pi Camera and OpenCV, is working.
- If no line is being found, or the line being found is strange, you may have found a case that confuses the algorithm. Disable the line detector, enable the camera view, and then drag the image from the browser into your collection of test images. This is a good candidate to put in the test image list and try different thresholds in the Jupyter Notebook until you get a match. Note that the current masking assumes brightness contrasts; other contrasts, like color hue, will not be detected.
When this is working, be sure to press Stop detection and use Ctrl + C in your console to stop following the log.
Now that we have tried our visual processing code on the camera, it’s time to put it on a robot behavior!
Line-following with the PID algorithm
Section titled “Line-following with the PID algorithm”In this section, we will combine the visual processing seen previously with the PID control loops with our line detection. We started building the PID (proportional integral derivative) controller in Chapter 11, Programming Encoders with Python, a system that lets us make smooth, responsive robot movement based on sensor input.
We will do the following here:
- Investigate the data flow for a line-following behavior.
- Create a behavior to follow the line using our line data with PID and our motors.
- Update the control page to have start/stop buttons for the follow line.
- Update the control page to show the PID graph for follow line.
Let’s get into making these changes.
Line-following data flow
Section titled “Line-following data flow”Before we build a new behavior, creating a data flow diagram will help us get a picture of what happens to the data after we’ve processed it.
The system will look familiar, as it is similar to those we made in Chapter 1 4, Robot Vision – Using a Pi Camera and OpenCV. Take a look at the following figure:

Figure 15.16 – The line-following behavior
Figure 15.16 – The line-following behavior
Figure 15.16 shows how the data and control flow for a line-following behavior. The Line detector will send MQTT messages with the Line position. The L ine detector gave us a position that is relative to 0, so we can use this directly as an error value for the Line position PID.
The PID output is a Turn correction, a factor to Turn by to try and correct the orientation of the robot. This is combined with Speed to make control values for the motors.
As we’ve seen before, we subtract the Turn from the Speed for the Left motor and add the Turn to the Speed for the Right motor.
This will cause the robot Camera view to move, which will mean the Line detector will produce an updated line position, feeding back into the system. This system will continue trying to detect a line until it is stopped.
Finding a line again
Section titled “Finding a line again”One important aspect of our design is what will happen when we come off the line.
The strategies we could choose for this are:
- Keep turning**,** as we are already turning: This is likely to find the line again but won’t always work. This also gives a little resilience to breaks in the line, like gaps between the tiles.
- Drive in a straight line: This is simple, but the robot could drive away from the line this way.
- Turning in a spin until a line is found: This is likely to bring the line in view again, but is less elegant than keeping to the turn we are already in.
- Stopping: The robot could stop; in a safety-conscious industrial environment this would be absolutely the right choice. However, in our robot, this could be frustrating as we tune to keep on the line.
Since our robot will hopefully be turning toward where it last saw the line, keeping the same turn correction until we find a line again will keep the robot on the path returning to the line. This won’t always work, but in my testing, it has been good enough and assisted in tuning a better line-following algorithm.
Let’s build this follower.
Creating the follower code
Section titled “Creating the follower code”Let’s start by building code to follow the line. This code is similar to robot/object_follower.py. Let’s put code in the file robot/line_follower.py, and we can note the differences. Let’s start with imports, an initializer, and a data-receiving handler:
import timeimport json
from common.mqtt_behavior import connect, publish_jsonfrom common.pid_controller import PIDControllerfrom common.time_stepper import TimeStepper
speed = 0.4
class FollowLineBehavior: def __init__(self): self.line_error = 0
def on_line_detected(self, client, userdata, msg): # Sense data = json.loads(msg.payload) self.line_error = data["line"]In this code, we are calling the received data line_error. This assumes that 0 is the target, keeping the line in the middle. There’s a base speed. Lower speeds are easier to tune.
Now we add the interesting part, where it uses the data with a PID:
def follow_line(self, client): line_pid = PIDController(0.001, 0.0001, smart_reset=True) turn = 0 time_stepper = TimeStepper() while True: time_difference = time_stepper.step() # Think if self.line_error is None: line_pid.reset() print("No line") else: turn = -line_pid.control(self.line_error, time_difference) publish_json( client, "line_follower/log", { "direction_error": self.line_error / 100, "turn": turn, "time": time.time() }, )
# Act left = speed - turn right = speed + turn publish_json( client, "motors/wheels", [left, right] )
time.sleep(0.05)This code uses a PID with smart reset enabled. The main loop will check if we’ve received a line; if not, it resets the PID to ensure there’s no integral left here. However, it leaves the last turn, so the robot will carry on the same prior trajectory.
If a line is detected, we feed the line error to the PID. The line error will be negative when the line is to the left or counterclockwise. However, all our pose work has been oriented the other way, so we negate the turn output of the PID control.
If we’ve found a line, we publish a log message showing the turn value and the error divided by 100, so it’s in a similar range to the turn value.
We always publish a motor message, and like we’ve seen before, we subtract the turn signal from the base speed for the left motor and add it to the base speed for the right motor. There’s then a short sleep before the next loop cycle.
The last part of this connects the service to MQTT and starts it up:
def start(self): client = connect() client.subscribe("line_detector/position") client.message_callback_add( "line_detector/position", self.on_line_detected ) self.follow_line(client)
behavior = FollowLineBehavior()behavior.start()This behavior will need changes to start it. Add this to deploy/deploy_services.py:
code = files.put( name="Update line follower code", src="robot/line_follower.py", dest="robot/line_follower.py")deploy_service("line_follower", "robot/line_follower.py", False, common.changed or code.changed)We then need some modifications to robot_control/line_detector.html to launch and view the log results. The highlighted areas have been added:
{% extends "robot_control/page.html.j2" %}{% block title %}Line detector{% endblock %}{% block content %} <button id="start_detection">Start detection</button> <button id="stop_detection">Stop detection</button> <button id="start_following">Start following</button> <button id="stop_following">Stop following</button>
<div id="camera_view"></div> <div class="line_chart"> <canvas id="plot"></canvas> </div>
<script type="module"> import 'https://cdn.jsdelivr.net/npm/chart.js'; import { create_timeseries_chart } from './chart_helper.js'; import { connect, publish_when_clicked } from './mqtt_client.js';
let mqttClient = connect(); publish_when_clicked(mqttClient, "start_detection", "launcher/start", "line_detector"); publish_when_clicked(mqttClient, "stop_detection", "launcher/stop", "line_detector"); publish_when_clicked(mqttClient, "start_following", "launcher/start", "line_follower"); publish_when_clicked(mqttClient, "stop_following", "launcher/stop", "line_follower");
const camera_view = document.getElementById('camera_view'); const behavior_chart = create_timeseries_chart('plot', ['turn', 'direction_error']);
mqttClient.subscribe('camera_view/url'); mqttClient.subscribe('line_follower/log'); 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; case 'line_follower/log': const log_data = JSON.parse(message); behavior_chart.update_data(log_data); break; } }); </script>{% endblock %}The additions add the following:
- Buttons and their handlers to start/stop the line follower.
- A line plot to show the followers’ logged data, including an MQTT subscription and handler for it.
Run pyinfra inventory.py deploy/deploy_services.py again to deploy this. When you reload the page, you should see the following:

Figure 15.17 – Line follower screenshot
The preceding screenshot shows the line detection page with the ability to follow added. There are two new buttons to start and stop the behavior. When you press S tart following, the robot should start driving around the line.
On the track I’ve set out, I see a graph like the following:

Figure 15.18 – PID response graph for line following
In the preceding graph, the direction error has some quite large drop-offs, which cause the robot to over- and understeer repeatedly. It is kind of following the line but still swinging rapidly. The large peaks are when a curve is encountered.
We showed one method of cycling changes to a PID using a configuration system before, which we could introduce into this code again. However, another method is to shorten the cycle time from the code to logging.
The following command line lets us tune the PID and see the logs:
pyinfra inventory.py deploy/update_code.py -y ; date ; pyinfra inventory.py exec -- journalctl -u line_follower -u line_detector -fThis is a mouthful, but it’s really just chaining a few commands together using the semicolon character:
pyinfra inventory.py deploy/update_code.py ‑ywill send updated Python code to the robot. Note that this does not update the website but runs faster thanupdate_services.datewill print the current date and time. Useful to see when you last sent code.pyinfra inventory.py exec ‑‑ journalctl ‑u line_follower ‑u line_detector ‑fis directly following theline_followerandline_detectorjournals right here on your computer, until Ctrl + C is pressed. This is convenient to see any problems.
When you want to change the PID values, stop the follower in the web control page, run this command, refresh the control page to clear the old graph, then start the follower in the web page again. You will also need to stop/start the detector if you’ve tuned values like masking there.
I don’t expect this to be stable yet, but let’s troubleshoot first.
Troubleshooting
Section titled “Troubleshooting”Before extending our line-following system further, let’s ensure what we have is working:
- If nothing is happening when the buttons are pressed, verify that there are no errors in the web browser inspection console.
- If it is not moving the motors, check the journal outputs for
line_followerandline_detectorfor tracebacks. Common typo issues can cause it to crash. - Very low P (proportional controller gain) values can cause no steering and cause it to drive in a straight line.
- If it’s coming off the line a lot, bring the speed down and the PID down to
0.001, then slowly bring up P to get it to come back to line more often. You can increase the speed again once you have values that don’t lose the line as often. - Once again, be on the lookout for when no line is found. These may be fleeting and pass quickly, but if you can screenshot and add them to your examples, you can use that to tune the line detection algorithm.
The robot will be wobbling a lot, but it will roughly follow the line. If the line following is steering too late, increase the P constant, if it’s oversteering a lot, try reducing the P constant. The I constant can correct for a constant understeer a little, but at anything but the lowest speed does not contribute a lot here.
We could do with damping down some of the overturns. There is one part of the PID that we have yet to implement; let’s see that.
Adding a derivative to the PID
Section titled “Adding a derivative to the PID”Our PID has the proportional and integral terms, but we have not added the derivative term. To recap, the derivative term would represent the slope of the error curve and would behave as a damping factor. It will also act as a reactive factor—a derivative kick—to sudden changes.
The derivative is simply a change divided by time. In our case, we will take the change in error and divide it by the time since the last update. Conveniently, we are already capturing the time difference, so we don’t need to add much to the PID controller.
Open the file robot/common/pid_controller.py. Find the PIDController.__init__ method and change it to the following:
def __init__(self, proportional_constant, integral_constant=0, derivative_constant=0, smart_reset=False, windup_limit=None): self.proportional_constant = proportional_constant self.integral_constant = integral_constant self.integral = 0 self.last_error = None self.derivative_constant = derivative_constant self.smart_reset = smart_reset self.windup_limit = windup_limitThe highlights show the changes. We’ve added a derivative constant, which will be used to multiply the derivative, and a last error. We can use the last error to see the difference when the PID is updated. The last error is initially set to None so we don’t try to react or assume an initial value.
We change the PIDController.control method to the following:
def control(self, error, time_difference=1): if self.smart_reset and np.sign(error) != np.sign(self.integral): self.reset() self.integral += error * time_difference if self.windup_limit is not None: # Prevent integral windup self.integral = np.clip( self.integral, -self.windup_limit, self.windup_limit) if self.last_error is not None: derivative = (error - self.last_error) / time_difference else: derivative = 0 self.last_error = error print(f"PID Control - P: {self.proportional_constant * error}, I: {self.integral_constant * self.integral}, D: {self.derivative_constant * derivative}") return self.proportional_constant * error \ + self.integral_constant * self.integral \ + self.derivative_constant * derivativeIn this code, we’ve first added a check for the last error. If we have a last error, we calculate the derivative, by first getting the difference between the current error and the last error, then dividing it by time.
If we do not have a last error, we set the derivative to 0. Regardless of what we had before, we can now set the last error value ready for the next cycle.
We then have some logging, so we can track PID values over time. This would show up in the journal for the running apps, so the components of the PID can be seen.
Lastly, we multiply the derivative by the derivative constant and add it to the returned control value.
With our PID upgraded, we can easily add it to our line-following behavior.
Adding the derivative to line-following
Section titled “Adding the derivative to line-following”Open the file robot/line_follower.py, and find the FollowLineBehavior.follow_line method. We only need to change the line that sets up the PID to modify this:
line_pid = PIDController(0.001, 0.0001, 0.0005, smart_reset=True)The PID here now has three setup values: the Proportional constant, the Integral constant, and the Derivative constant. The Derivative constant here is set to half the proportional constant, a little high, but it resulted in a smoother line following for me.
Tuning the integral constant is a matter of adding a small value, seeing if it settles the robot a little, and gently increasing it. The robot should be smoother on the line.
With some time, you will be able to find smoother line following, and perhaps make it faster. The following shows a graph of a smoother follow:

Figure 15.19 – Smoother line follow graph
The preceding figure shows the direction error and turn again. Although the turn looks less smooth, the direction error is not crossing the 0 line so often, which means the line is being kept to one side of the robot. The robot doesn’t lose the line very often, and is no longer making big swings other than an initial steer onto the line right at the start. The curves are still showing the curve of the track we are following, so I don’t often expect the direction error to be 0.
Finding the right combination of PID values tends to be different at different speeds, and when you find an improvement, make a note before refining it further. This does take a lot of testing and enough time that you will make multiple robot battery charges. I tested mine so much that I had to reprint some of the tiles where the robot had worn through the ink.
Now, let’s see what we’ve learned in this chapter.
Summary
Section titled “Summary”In this chapter, you saw how to use the camera to detect a line and how to plot data showing what it found, exercising computer vision principles and publishing detection data to a bus, common in robotics systems. You then saw how to take this published data and put it into a robot driving behavior so that the robot follows the line. You added to your OpenCV knowledge and saw how to tune the PID to make the line following more accurate.
In the next chapter, we will see how to control your robot with your voice and have it start and stop behaviors, as well as respond to you with a voice too. You will add speech recognition software and a headset.
Challenges
Section titled “Challenges”Now that we’ve got this to work, there are ways we could enhance the system and make it more interesting:
- Extending the PID model and masking threshold here with the configuration system from Chapter 11, Programming Encoders with Python, would make tuning easier from the web page.
- You could modify the motor handling code to go faster when the line is closer to the middle and slow down when it is farther.
- I spent a lot of time experimenting with different values from the line detector to feed to our PID control. Try the center X value, or theta (this will be a bit tricky), to see if different values make for smoother processing.
- Investigate the other line sensing hardware, like sensor arrays. These can give very smooth results.
These exercises should give you some interesting ways to play and experiment with the things you’ve built and learned in this chapter.
Further reading
Section titled “Further reading”The following should help you look further into line following:
- Read about an alternative approach for line processing in the Go language on the Raspberry Pi from Pi Wars legend Brian Starkey at: https://blog.usedbytes.com/2019/02/autonomous-challenge-blast-off/
- Here is another line-following robot, using an approach like ours but more sophisticated: https://www.raspberrypi.org/blog/an-image-processing-robot-for-robocup-junior/