Table of Contents

Build a Camera-Based Lane Follower Robot with Quarky Intellio Using Python and OpenCV

Example Description
Learn how to build a self-driving lane follower robot with Quarky Intellio and Python in PictoBlox! The robot reads the live camera feed from Intellio, uses OpenCV to find the black lane borders on the floor, works out how far it has drifted from the centre of the lane, and corrects its two motors in real time using proportional (P) control — just like a mini self-driving car.

Introduction

Self-driving cars use cameras to see the lane markings on the road and keep themselves in the middle of the lane. In this project, we will build the same idea on a small scale. Quarky Intellio streams its camera image to PictoBlox, our Python program turns that image into a black-and-white mask, finds the left and right lane borders, and adjusts the speed of the two motors so the robot stays centred on the track.

This project introduces learners to concepts such as:

  • Receiving a live camera stream from Quarky Intellio in Python
  • Image processing with OpenCV – grayscale, thresholding and noise removal
  • Finding contours and their centroids inside a region of interest (ROI)
  • Calculating a position error and correcting it with proportional (P) control
  • Differential drive – steering a robot by changing the speed of each motor
  • Tuning a robot live with OpenCV trackbars (sliders)

By the end of this activity, your Intellio robot will follow a lane on its own and you will be able to fine-tune how it drives while it is running.

Setting Up the Stage / Sprite

Prerequisites

  • Quarky Intellio Lane Follower Robot assembled – follow the assembly guide: https://ai.thestempedia.com/docs/quarky-intellio/quarky-intellio-lane-follower-robot-opencv-python-assembly-guide/
  • Quarky Intellio (charged and powered on) mounted on the Quarky Mini Expansion Board
  • A track with two black lane borders on a light-coloured floor
  • PictoBlox installed on a Wi-Fi connected laptop
  • Firmware uploaded to Quarky Intellio via the Upload Firmware button in PictoBlox

Connecting your Intellio to PictoBlox

  1. Slide up the power switch to turn on Quarky Intellio. A blue light will turn on – that means Intellio is ON.
  2. Open PictoBlox and choose Python Coding as the coding environment.
  3. Click on Board at the top of your screen and select Quarky Intellio.
  4. Click the Connect tab in the top menu to connect with the serial port (USB). Be sure to Upload Firmware (top-right corner) for Intellio.
  5. Once the Upload Firmware is done, choose the Wi-Fi tab to connect Intellio with PictoBlox.

Check out the Connection guide for Wi-Fi method

Adding the Extensions

  1. Click the Add Extension button and add the Quarky Mini Expansion Board extension – it gives us the QuarkyMiniExpansion() functions that drive the motors.
  2. Add the Object Detection extension – the program creates an ObjectDetection() object during setup.
  3. Open the Tobi.py file in the Python Editor and write the code explained below.

How the Robot Sees the Lane

The camera image is converted into a black-and-white mask where the black lane borders become white blobs. The program looks inside a “near” band of the image, finds the blob closest to the centre on the left side and on the right side, and compares their positions with two target regions (shown as coloured boxes in the Debug window). The average difference is the position error: if it is zero the robot is centred, and if it is positive or negative the robot speeds up one motor and slows down the other to steer back into the lane.

Step-by-Step Python Coding Guide

The complete program is written in Tobi.py. The comments written in the code are kept exactly as they appear in the project so you can follow each part.

Step 1: Import the Libraries

We import OpenCV (cv2) for image processing, NumPy for working with image arrays, socket and threading to receive the camera stream in the background, and time and math for timing and calculations.

# ================= IMPORTING LIBRARIES =================
import cv2
import numpy as np
import socket
import threading
import time
import math

Step 2: Initialise the Robot and Object Detection

QuarkyMiniExpansion() creates the Mini Expansion Board object and miniinitialise() prepares it to drive the motors. An Object Detection object is also created with its bounding box enabled and a confidence threshold of 0.4.

# ================= INITIALIZING THE ROBOT AND OBJECT DETECTION =================
 
# initialize the Mini Expansion board.
mini = QuarkyMiniExpansion()
mini.miniinitialise()
 
# using the Object Detection Extension
od = ObjectDetection()
od.enablebox()
od.setthreshold(0.4)

Step 3: Set the Configuration Values

These constants set up the whole program: the UDP port on which the camera stream is received, the motor speed limits, the controller gains (Kp, Kd and turn gain), the base speed, the centre offset, smoothing, the minimum blob size that counts as a lane marker, and the starting lane-width estimate. Most of them are also the starting values of the tuning sliders.

# ================= CONFIGURATION =================
 
STREAM_PORT = 6000
LOCALHOST = "127.0.0.1"
MAX_UDP_PACKET = 65536
# ================= MOTOR SPEED LIMITS =================
 
MAX_SPEED = 100
MIN_SPEED = 0
 
# ================= CONTROLLER SETTINGS =================
 
# Kp controls how strongly the robot reacts to its current error.
# Larger Kp = stronger correction.
DEFAULT_KP = 0.34
 
# Kd would normally control how strongly the robot reacts to changes in the error.
DEFAULT_KD = 0.10
 
# Controls how strongly the robot turns.
DEFAULT_TURN_GAIN = 0.13
 
# ================= MOTOR CONTROL SETTINGS =================
 
DEFAULT_BASE_SPEED = 17
diff = 5
DEFAULT_MOTOR_GAIN = 0.2
 
# ================= CENTER OFFSET SETTINGS =================
 
DEFAULT_CENTER_OFFSET = 0
CENTER_OFFSET_RANGE = 50
 
# ================= SMOOTHING SETTINGS =================
 
# alpha controls smoothing.
alpha = 0.3
smoothed_target_x = None
 
# ================= IMAGE / CONTOUR FILTERING =================
 
# This helps prevent camera noise from being treated as a lane.
MIN_CONTOUR_AREA = 150
kernel = np.ones((5, 5), np.uint8)
# ================= LANE WIDTH ESTIMATION =================
 
last_lane_width_est = 60.0
lane_width_alpha = 0.2

Step 4: Create the Video Receiver

The VideoReceiver class listens on the local UDP port in a separate thread. Each frame arrives as a “SIZE:” header followed by the image data; the class collects the packets, decodes them into an image with OpenCV and keeps only the most recent frame. get_frame() returns that frame and stop() closes the connection.

# ================= VIDEO RECEIVER =================
 
# This class is responsible for receiving the camera video.
class VideoReceiver:
    def __init__(self, port):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind((LOCALHOST, port))
        self.sock.settimeout(1.0)
        self.latest_frame = None
        self.running = True
        self.lock = threading.Lock()
        self.thread = threading.Thread(target=self.receive_loop)
        self.thread.daemon = True
        self.thread.start()
        print(f"UDP Video Receiver listening on {LOCALHOST}:{port}")
 
    # This function continuously waits for camera data.
    def receive_loop(self):
        current_buffer = bytearray()
        expected_size = 0
        while self.running:
            try:
                data, _ = self.sock.recvfrom(MAX_UDP_PACKET)
                if data.startswith(b"SIZE:"):
                    try:
                        expected_size = int(data[5:].decode())
                        # Start with an empty buffer for this frame.
                        current_buffer = bytearray()
                    except:
                        expected_size = 0
                elif expected_size > 0:
                    current_buffer.extend(data)
                    if len(current_buffer) >= expected_size:
                        np_arr = np.frombuffer(current_buffer, dtype=np.uint8)
                        frame = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
                        if frame is not None:
                            with self.lock:
                                self.latest_frame = frame
 
                        expected_size = 0
                        current_buffer = bytearray()
 
            except socket.timeout:
                continue
            except Exception as e:
                print(f"Receiver Error: {e}")
 
    # GET THE MOST RECENT CAMERA IMAGE
    def get_frame(self):
        with self.lock:
            return self.latest_frame
 
    # STOP THE VIDEO RECEIVER
    def stop(self):
        self.running = False
        self.sock.close()

Step 5: Write the Helper Functions

centroid_from_contour() finds the centre point of a blob using image moments. slice_centroids() cuts a horizontal band out of the mask, finds all blobs in it that are larger than MIN_CONTOUR_AREA, and returns their centre points in full-image coordinates.

# ================= HELPER FUNCTIONS =================
def nothing(x):
    pass
 
def centroid_from_contour(c):
    M = cv2.moments(c)
    if M['m00'] == 0:
        return None
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    return (cx, cy)
 
def slice_centroids(mask, y_top, y_bottom, slice_name="Slice"):
    h, w = mask.shape
    y_top = max(0, min(h-1, int(y_top)))
    y_bottom = max(0, min(h, int(y_bottom)))
    if y_bottom <= y_top:
        return []
 
    slice_img = mask[y_top:y_bottom, :]
    contours, _ = cv2.findContours(slice_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    centroids = []
 
    corrected_y_coords = []
 
    for c in contours:
        if cv2.contourArea(c) >= MIN_CONTOUR_AREA:
            cent = centroid_from_contour(c)
            if cent:
                cx, cy_relative = cent
                cy_global = y_top + cy_relative
                centroids.append((cx, cy_global))
                corrected_y_coords.append(cy_global)
 
    if corrected_y_coords and slice_name != "SkipPrint":
        print(f"{slice_name} Centroid Y-Coordinates: {corrected_y_coords}")
 
    return centroids

Step 6: Create the Tuning Window and Sliders

The program starts the video receiver and opens a “Tuning” window with trackbars. These sliders let you change the black threshold, Kp, Kd, turn gain, base speed, motor gain, centre offset and the size and position of the image regions while the robot is running.

# ================= CREATE  THE TUNING WINDOW AND SLIDERS =================
 
receiver = VideoReceiver(STREAM_PORT)
 
cv2.namedWindow("Tuning", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Tuning", 800, 600)
 
cv2.createTrackbar("Black Threshold", "Tuning", 100, 255, nothing)
cv2.createTrackbar("Kp x100", "Tuning", int(DEFAULT_KP*100), 300, nothing)
cv2.createTrackbar("Kd x100", "Tuning", int(DEFAULT_KD*100), 200, nothing)
cv2.createTrackbar("TurnGain x100", "Tuning", int(DEFAULT_TURN_GAIN*100), 300, nothing)
cv2.createTrackbar("Base Speed", "Tuning", DEFAULT_BASE_SPEED, MAX_SPEED, nothing)
cv2.createTrackbar("Motor Gain x100", "Tuning", int(DEFAULT_MOTOR_GAIN*100), 100, nothing)
cv2.createTrackbar("Center Offset", "Tuning", DEFAULT_CENTER_OFFSET + CENTER_OFFSET_RANGE, 2*CENTER_OFFSET_RANGE, nothing)
cv2.createTrackbar("Bottom Ignore %", "Tuning", 10, 40, nothing)
cv2.createTrackbar("Far ROI top %", "Tuning", 15, 60, nothing)
cv2.createTrackbar("Far ROI bottom %", "Tuning", 39, 80, nothing)
cv2.createTrackbar("Near ROI top %", "Tuning", 42, 90, nothing)
cv2.createTrackbar("Left Region Center %", "Tuning", 12, 50, nothing)
cv2.createTrackbar("Left Region Width %", "Tuning", 29, 50, nothing)
cv2.createTrackbar("Right Region Center %", "Tuning", 86, 100, nothing)
cv2.createTrackbar("Right Region Width %", "Tuning", 27, 50, nothing)

Step 7: Start the Main Robot Loop

The forever loop gets the latest camera frame. If no frame has arrived yet, the robot is stopped and the loop tries again. Otherwise the frame is resized to 320 × 240 pixels so the processing is fast and consistent.

# ================= MAIN ROBOT LOOP =================
 
while True:
    frame = receiver.get_frame()
    if frame is None:
        mini.stoprobot()
        time.sleep(0.01)
        continuE
 
    try:
        frame = cv2.resize(frame, (320, 240))
        h, w = frame.shape[:2]

Step 8: Read the Slider Values and Region Settings

Every loop reads the current value of each slider, converts it into the right unit (for example, Kp x100 is divided by 100), calculates the desired centre of the image including the centre offset, and reads the size and position of the near, far, left and right regions.

# ================= READ CURRENT SLIDER VALUES =================
 
        thresh_val = cv2.getTrackbarPos("Black Threshold", "Tuning")
        Kp = cv2.getTrackbarPos("Kp x100", "Tuning") / 100.0
        Kd = cv2.getTrackbarPos("Kd x100", "Tuning") / 100.0
        turn_gain = cv2.getTrackbarPos("TurnGain x100", "Tuning") / 100.0
        base_speed = cv2.getTrackbarPos("Base Speed", "Tuning")
        motor_gain = cv2.getTrackbarPos("Motor Gain x100", "Tuning") / 100.0
 
# ================= FIND DESIRED CENTER =================
 
        raw_offset = cv2.getTrackbarPos("Center Offset", "Tuning")
        center_offset = raw_offset - CENTER_OFFSET_RANGE
        TARGET_CENTER_X = w // 2 + center_offset
 
# ================= READ REGION SETTINGS =================
 
        bottom_ignore_pct = cv2.getTrackbarPos("Bottom Ignore %", "Tuning") / 100.0
        far_top_pct = cv2.getTrackbarPos("Far ROI top %", "Tuning") / 100.0
        far_bottom_pct = cv2.getTrackbarPos("Far ROI bottom %", "Tuning") / 100.0
        near_top_pct = cv2.getTrackbarPos("Near ROI top %", "Tuning") / 100.0
# ================= LEFT / RIGHT REGION SETTINGS ================
 
        left_center_pct = cv2.getTrackbarPos("Left Region Center %", "Tuning") / 100.0
        left_width_pct = max(1, cv2.getTrackbarPos("Left Region Width %", "Tuning")) / 100.0
        right_center_pct = cv2.getTrackbarPos("Right Region Center %", "Tuning") / 100.0
        right_width_pct = max(1, cv2.getTrackbarPos("Right Region Width %", "Tuning")) / 100.0

Step 9: Convert the Image and Calculate the Regions

The frame is converted to grayscale and thresholded with THRESH_BINARY_INV, so dark lane borders become white in the mask. Opening and closing remove small specks and fill small gaps. The slider percentages are then converted into pixel positions for the far and near bands.

# ================= CONVERT CAMERA IMAGE INTO BLACK/WHITE =================
 
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        _, mask = cv2.threshold(gray, thresh_val, 255, cv2.THRESH_BINARY_INV)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
 
# ================= CALCULATE IMAGE REGIONS =================
 
        bottom_ignore = int(h * bottom_ignore_pct)
        far_top = int(h * far_top_pct)
        far_bottom = int(h * far_bottom_pct)
        near_top = int(h * near_top_pct)
        near_bottom = h - bottom_ignore

Step 10: Find the Lane Markers and Separate Left and Right

slice_centroids() finds the lane blobs in the near and far bands, and both bands are drawn on the Debug image. Blobs in the left half of the near band belong to the left border and the rest to the right border. The left marker closest to the centre and the right marker closest to the centre are chosen and marked with red dots.

# ================= FIND LANE MARKERS =================
 
        near_centroids = slice_centroids(mask, near_top, near_bottom, "SkipPrint")
        far_centroids = slice_centroids(mask, far_top, far_bottom, "SkipPrint")
        debug = frame.copy()
        cv2.rectangle(debug, (0, far_top), (w-1, far_bottom), (200, 200, 0), 1)
        cv2.rectangle(debug, (0, near_top), (w-1, near_bottom), (200, 200, 0), 1)
 
# ================= SEPARATE LEFT AND RIGHT MARKERS =================
 
        left = []
        right = []
        if near_centroids:
            left = [c for c in near_centroids if c[0] < w//2]
            right = [c for c in near_centroids if c[0] >= w//2]
 
        left_marker = None
        right_marker = None
        if left:
            left_marker = max(left, key=lambda x: x[0])
            cv2.circle(debug, left_marker, 5, (0,0,255), -1)
        if right:
            right_marker = min(right, key=lambda x: x[0])
            cv2.circle(debug, right_marker, 5, (0,0,255), -1)

Step 11: Estimate the Lane Width and Draw the Target Regions

When both markers are visible, the lane width is measured and smoothed. The left and right target regions are calculated from the slider values and drawn as semi-transparent boxes on the Debug image, so you can see where the robot expects each border to be.

# ================= ESTIMATE LANE WIDTH =================
 
        if left_marker and right_marker:
            measured_width = abs(right_marker[0] - left_marker[0])
            last_lane_width_est = (lane_width_alpha * measured_width) + (1 - lane_width_alpha) * last_lane_width_est
 
# ================= CREATE LEFT AND RIGHT TARGET REGIONS =================
 
        left_region_center_x = int(left_center_pct * w)
        left_region_half_w = int((left_width_pct * w) / 2)
        left_region_x1 = max(0, left_region_center_x - left_region_half_w)
        left_region_x2 = min(w-1, left_region_center_x + left_region_half_w)
 
        right_region_center_x = int(right_center_pct * w)
        right_region_half_w = int((right_width_pct * w) / 2)
        right_region_x1 = max(0, right_region_center_x - right_region_half_w)
        right_region_x2 = min(w-1, right_region_center_x + right_region_half_w)
 
# ================= DRAW TARGET REGIONS =================
 
        overlay = debug.copy()
        alpha_overlay = 0.35
        cv2.rectangle(overlay, (left_region_x1, near_top), (left_region_x2, near_bottom), (255, 0, 0), -1)
        cv2.rectangle(overlay, (right_region_x1, near_top), (right_region_x2, near_bottom), (255, 0, 255), -1)
        cv2.addWeighted(overlay, alpha_overlay, debug, 1 - alpha_overlay, 0, debug)

Step 12: Calculate the Error and Drive the Motors

The error is the distance between each detected marker and the centre of its target region; the two errors are averaged. If neither border is found, the robot stops. Otherwise the error is multiplied by Kp (proportional control) and by the motor gain, subtracted from the base speed for one motor and added for the other, and sent to runbothmotors(). The Mask and Debug windows are updated, and pressing Q exits the program.

# CALCULATE POSITION ERROR
        # This list will store how far each detected marker is from its desired position.
        errors = []
        if left_marker:
            left_err = left_marker[0] - left_region_center_x
            errors.append(left_err)
        if right_marker:
            right_err = right_marker[0] - right_region_center_x
            errors.append(right_err)
 
        # If neither side of the lane was found, stop the robot
 
        if (not left_marker) and (not right_marker):
            mini.stoprobot()
            cv2.imshow("Mask", mask)
            cv2.imshow("Debug", debug)
 
            # If the user presses Q, exit the program.
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
            continue
 
        avg_error = sum(errors) / len(errors) if errors else 0.0
 
        # Multiply the error by Kp.
        # Larger error -> stronger correction.
        # Smaller error -> smaller correction.
        p_control_signal = Kp * avg_error
        speed_adjustment = motor_gain * p_control_signal
 
        # If the robot needs to correct its direction, one motor becomes slower and other becomes fast
        motor1_speed = base_speed - speed_adjustment
        motor2_speed = base_speed + speed_adjustment
 
        mini.runbothmotors('1','1',int(motor1_speed), int(motor2_speed))
 
        # SHOW DEBUGGING WINDOWS
        cv2.imshow("Mask", mask)
        cv2.imshow("Debug", debug)
 
        # Save the current error for possible future control logic.
        prev_error = avg_error
 
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
 
        time.sleep(0.070)

Step 13: Handle Errors and Clean Up

If anything goes wrong inside the loop, the error is printed and the robot is stopped for safety. When the loop ends, the video receiver is closed, the motors are stopped and all OpenCV windows are closed.

  # If something unexpected goes wrong inside the main loop, stop the robot.
    except Exception as ex:
        print("Loop Error:", ex)
        mini.stoprobot()
 
# ================= CLEANUP =================
 
# Stop the robot and receiving video feed
receiver.stop()
mini.stoprobot()
cv2.destroyAllWindows()

Output

Run the program and place the robot in the middle of the lane. Three windows open: Tuning (the sliders), Mask (the black-and-white view of the lane borders) and Debug (the camera view with the regions, target boxes and detected markers). The robot drives forward and keeps adjusting its two motors to stay between the borders. Adjust Black Threshold first until only the lane borders appear white in the Mask window, then tune Base Speed, Kp and Motor Gain until the robot follows the lane smoothly. Press Q to stop.

Conclusion

In this project, we built a camera-based lane follower robot with Quarky Intellio using Python and OpenCV in PictoBlox. We received a live camera stream, turned it into a black-and-white mask, found the left and right lane borders as contours, and calculated how far the robot had drifted from its target position. Using proportional control, we turned that error into different speeds for the two motors so the robot steers itself back into the lane. As a next step, you can use the far region to look ahead at curves, or add the derivative (Kd) term to make the robot even smoother.