Following a line with OpenCV
A line follower sounds like a beginner project, and the basic version is.
Code: image_processing.py in line_follower_ws · Watch: The rover learning to follow a line
A line follower sounds like a beginner project, and the basic version is. Getting it to behave, though, teaches most of what matters in robot vision: look at less of the image, turn pixels into one number, and decide what to do when that number is missing.
This is how the controller in my line follower works, step by step, and where I’d change it now.
1. Look at less of the image
The camera sees the whole scene, but the robot only cares about the line just ahead of it. So the first step crops the frame:
def get_roi_portion(image):
image_height, _ = image.shape[:2]
roi = image[(3 * image_height) // 4:, :] # bottom quarter
roi_width = roi.shape[1]
third = roi_width // 3
roi = roi[:, third:2 * third] # middle third
return roi, third, image.shape[0] - roi.shape[0]
If you think in arrays, this is just slicing. An image is a NumPy array of shape (height, width, 3), so image[rows, cols] crops it. Nothing is copied or resized.
The region you choose is a trade-off. A small region near the bottom means less noise and less to process, but also less look-ahead: on a sharp bend, the line can leave the region before the robot has started turning.
2. Turn colour into black and white
Next, the cropped image goes to HSV, and a range check keeps only grey pixels:
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
binary = cv2.inRange(hsv, np.array([0, 0, 150]), np.array([180, 20, 170]))
kernel = np.ones((5, 5), np.uint8)
binary = cv2.erode(binary, kernel, iterations=5)
binary = cv2.dilate(binary, kernel, iterations=5)
HSV separates colour (hue), how colourful it is (saturation) and brightness (value). The range says “almost no colour, brightness between 150 and 170”, which matches the grey line on my simulated floor.
The erode-then-dilate pair removes specks. Eroding shrinks every white area and wipes out small noise completely. Dilating grows what’s left back to about its original size.
That brightness band is also the weakest part of the whole controller. Twenty values out of 255 is very narrow. It works in simulation, where the lighting never changes. On a real floor, a shadow or a window moves the line’s brightness out of that band and the robot goes blind. For real lighting, an adaptive threshold or a line colour that differs in hue, not just brightness, holds up much better.
3. Find the line
contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
A contour is just a list of points around the edge of a white area. The controller keeps the largest one, measured by its bounding box, and treats that as the line.
Then comes a small trick for look-ahead: it splits the contour into three horizontal slices and uses the centre of the top slice, the part furthest from the robot. Steering towards where the line is going, rather than where it is under the wheels, makes turns smoother.
4. Turn the error into steering
The error is how far that centre point is from the middle of the image, in pixels. It’s mapped onto a steering angle between -45° and 45°, and the forward speed drops as the angle grows:
def adjust_linear_velocity(angle_rad, min_speed, max_speed):
normalized_angle = abs(angle_rad) / (math.pi / 2)
return max_speed - (max_speed - min_speed) * normalized_angle
That’s proportional control: steer in proportion to the error. It’s the simplest controller there is, and on a smooth track it’s enough.
While writing this I noticed a small mismatch. The speed formula normalises by 90°, but the angle never goes beyond 45°. So with a minimum speed of 0.1 and a maximum of 1.5, the robot never drops below 0.8 even in the sharpest turn. If it overshoots corners, normalising by 45° instead gives the full speed range.
5. Decide what to do with no line
When no contour is found, my node repeats the last command it sent. In simulation that’s a reasonable guess: the line probably just curved out of view, so keep turning. On a real table, it means a robot that has lost the line drives on at full confidence. Safer options are to stop after a few frames without a line, or to slowly turn in place towards where the line was last seen.
What I’d add next
- A derivative term. Proportional control alone wobbles on straights. Adding a term for how fast the error is changing (PD control) damps that.
- A smaller camera image. The simulated camera produces 1920 by 1080 frames, and the controller crops most of it away. A lower resolution would do the same job with less work.
- Logging the error. Publishing the error as its own topic and plotting it is the quickest way to see whether the robot oscillates, lags or overshoots.
None of this needs machine learning. A crop, a threshold, a contour and one number are enough to follow a line, as long as you’re honest about the lighting.