Table of Contents

Build a Colour-Based Obstacle Avoider Robot with Quarky Intellio Using Python and OpenCV

Example Description
Learn how to build a camera-based obstacle avoider robot with Quarky Intellio and Python in PictoBlox! The robot watches the road through Intellio’s camera, detects red and blue obstacles with OpenCV colour masks, and turns its steering servo away from them — steering left around red obstacles and right around blue ones, adjusting how sharply it turns based on where the obstacle appears in the view.

Introduction

Real autonomous vehicles use cameras to recognise objects on the road and steer around them. In this project, our Intellio robot does the same with coloured obstacles. Quarky Intellio streams its camera image to PictoBlox, the Python program looks for large red or blue objects in every frame, calculates a steering angle based on where the obstacle is, and sends that angle to the steering servo while the motors keep the robot moving forward.

This project introduces learners to concepts such as:

  • Receiving a live camera stream from Quarky Intellio in Python
  • Colour detection with HSV colour masks in OpenCV
  • Finding the largest contour and its bounding box
  • Mapping an object’s position to a servo steering angle with a power curve
  • Using a timer (persistence) so the robot finishes its turn after the obstacle leaves the view
  • Controlling a servo and two motors together with the Quarky Mini Expansion Board

By the end of this activity, your Intellio robot will drive forward on its own and steer around red and blue obstacles in its path.

Setting Up the Stage / Sprite

Prerequisites

  • Quarky Intellio steering robot assembled, with the steering servo connected to S1 and the two drive motors connected to the Quarky Mini Expansion Board
  • Quarky Intellio (charged and powered on)
  • Red and blue obstacles (for example, coloured boxes or cups) large enough to fill part of the camera view
  • PictoBlox installed on a Wi-Fi connected laptop
  • Firmware uploaded to Quarky Intellio via the Upload Firmware button in PictoBlox

[INSERT IMAGE: Robot build / connection image – servo on S1 and motors on the Mini Expansion Board]

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 – https://ai.thestempedia.com/docs/quarky-intellio/quarky-intellio-getting-started/quarky-intellio-connection-guide/#method2

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. The QuarkyIntellio() object used to move the steering servo comes with the Quarky Intellio board.
  3. Open the Tobi.py file in the Python Editor and write the code explained below.

How the Robot Decides Where to Steer

Every camera frame is checked for red and blue areas. If a large red obstacle is found, the robot steers left; if a large blue obstacle is found (and no red one), it steers right. The steering angle depends on the obstacle’s horizontal position: the further a red obstacle is towards the right of the view, the harder the robot steers left, and the further a blue obstacle is towards the left, the harder it steers right. The angle stays between 55° (hardest left) and 125° (hardest right), with 90° as straight ahead – an obstacle in the middle of the view gives about 65° or 115°. After an obstacle leaves the view, the robot keeps the same turn for 0.8 seconds so it fully clears the obstacle, and then straightens up.

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 and Initialise the Robot

We import OpenCV (cv2), NumPy, socket, threading and time. QuarkyMiniExpansion() and miniinitialise() prepare the Mini Expansion Board to drive the motors, and QuarkyIntellio() lets us control the steering servo.

import cv2
import numpy as np
import socket
import threading
import time
 
mini = QuarkyMiniExpansion()
mini.miniinitialise()
intellio=QuarkyIntellio()

Step 2: Set the Configuration Values

These constants set the UDP port for the camera stream, the motor speed limits, the minimum contour area, the servo centre (90°), the hardest left (55°) and hardest right (125°) steering angles, the forward speed (60) and how long the robot keeps turning after an obstacle disappears (0.8 seconds).

# ================= CONFIGURATION =================
STREAM_PORT = 6000
LOCALHOST = "127.0.0.1"
 
MAX_UDP_PACKET = 65536
 
# Motor Parameters
MAX_SPEED = 50
MIN_SPEED = 0
diff = 5
 
# Contour filtering
MIN_CONTOUR_AREA = 150
 
SERVO_CENTER = 90
# Dynamic servo range — how far left/right we can steer
SERVO_LEFT_MAX = 55    # hardest left
SERVO_RIGHT_MAX = 125  # hardest right
 
FORWARD_SPEED = 60
 
# How long (seconds) to keep turning AFTER the obstacle leaves frame
OBSTACLE_PERSISTENCE_SEC = 0.8
 
last_servo_angle = None

Step 3: 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 and keeps only the most recent frame. It also prints a message if no data arrives for one second.

# ================= VIDEO RECEIVER =================
 
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.packets_received = 0
        self.frames_decoded = 0
        self.last_debug_print = time.time()
        self.thread = threading.Thread(target=self.receive_loop)
        self.thread.daemon = True
        self.thread.start()
        print(f"UDP Video Receiver listening on {LOCALHOST}:{port}")
 
    def receive_loop(self):
        current_buffer = bytearray()
        expected_size = 0
        receiving = False
        addr = ("?", 0)
 
        while self.running:
            try:
                data, addr = self.sock.recvfrom(MAX_UDP_PACKET)
                self.packets_received += 1
 
                if data.startswith(b"SIZE:"):
                    try:
                        header = data.decode().strip()
                        expected_size = int(header.split(":")[1])
                        current_buffer = bytearray()
                        receiving = True
                    except Exception:
                        receiving = False
                elif receiving:
                    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
                            self.frames_decoded += 1
                        receiving = False
                        current_buffer = bytearray()
 
                now = time.time()
                if now - self.last_debug_print > 2.0:
                    # print(f"[VideoReceiver] packets={self.packets_received} "
                    #       f"frames={self.frames_decoded} addr={addr}")
                    self.last_debug_print = now
            except socket.timeout:
                print("[VideoReceiver] No UDP packet in last 1s.")
                continue
            except Exception as e:
                print(f"[VideoReceiver] Error: {e}")
 
    def get_frame(self):
        with self.lock:
            return self.latest_frame
 
    def stop(self):
        self.running = False
        self.sock.close()

Step 4: Create the Colour Masks

get_red_mask() converts the frame to HSV and keeps only red pixels. Red sits at both ends of the HSV hue range, so two ranges (0–10 and 170–180) are combined. get_blue_mask() keeps blue pixels (hue 90–140). Opening and closing remove small specks and fill gaps in both masks.

# ============================================
# COLOUR MASKS
# ============================================
 
def get_red_mask(frame):
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    red1 = cv2.inRange(hsv, np.array([0, 80, 80]),   np.array([10, 255, 255]))
    red2 = cv2.inRange(hsv, np.array([170, 80, 80]), np.array([180, 255, 255]))
    mask = cv2.bitwise_or(red1, red2)
    kernel = np.ones((5, 5), np.uint8)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN,  kernel)
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
    return mask
 
def get_blue_mask(frame):
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, np.array([90, 60, 60]), np.array([140, 255, 255]))
    kernel = np.ones((5, 5), np.uint8)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN,  kernel)
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
    return mask

Step 5: Calculate the Dynamic Servo Angle

calc_servo_angle() turns the obstacle’s horizontal centre (cx) into a steering angle. The position is normalised between 0 (far left) and 1 (far right). For a left turn, the steering grows as the obstacle moves towards the right of the frame; for a right turn, it grows as the obstacle moves towards the left. A power curve boosts the result, so even obstacles near the middle of the frame produce a strong turn. The result is limited between SERVO_LEFT_MAX and SERVO_RIGHT_MAX.

# ============================================
# DYNAMIC SERVO ANGLE CALCULATOR
# ============================================
def calc_servo_angle(cx, frame_width, direction):
    norm = cx / frame_width  # 0.0 = far left, 1.0 = far right
 
    # Power curve — exponent > 1 makes even mid-frame detections steer harder
    # 2.0 = quadratic, try 1.5 to 3.0 to taste
    CURVE = 2.0
 
    if direction == "left":
        t = norm ** (1 / CURVE)   # boost the steer amount
        angle = SERVO_CENTER - t * (SERVO_CENTER - SERVO_LEFT_MAX)
    else:
        t = (1.0 - norm) ** (1 / CURVE)
        angle = SERVO_CENTER + t * (SERVO_RIGHT_MAX - SERVO_CENTER)
 
    return int(np.clip(angle, SERVO_LEFT

Step 6: Set Up the Persistence State

last_obstacle remembers the direction and angle of the last obstacle and the time until which the robot should keep turning. It starts as None because no obstacle has been seen yet.

# ============================================
# PERSISTENCE STATE
# ============================================
 
# Stores the last seen obstacle so we can keep steering after it leaves frame
# { "direction": "left"/"right", "angle": int, "expires_at": float }
last_obstacle = None

Step 7: Start the Receiver and Centre the Servo

The program starts the video receiver, opens three windows (Video feed, Red Mask and Blue Mask) and moves the steering servo on S1 to the centre position before the main loop begins.

# ================= MAIN SETUP =================
receiver = VideoReceiver(STREAM_PORT)
 
cv2.namedWindow("Video feed",    cv2.WINDOW_NORMAL)
cv2.namedWindow("Red Mask",      cv2.WINDOW_NORMAL)
cv2.namedWindow("Blue Mask",     cv2.WINDOW_NORMAL)
 
# initialize_board()
intellio.write("S1",SERVO_CENTER)
# set_servo_angle(SERVO_CENTER)
time.sleep(0.5)

Step 8: Start the Main Loop and Prepare the Frame

The loop gets the latest frame. If no frame has arrived, it shows “Waiting for video stream…”, stops the robot and tries again. Otherwise the frame is resized to 320 × 240, the red and blue masks are created, their contours are found, and the decision defaults to FORWARD with the servo centred.

# ================= MAIN LOOP =================
while True:
    frame = receiver.get_frame()
    if frame is None:
        placeholder = np.zeros((240, 320, 3), dtype=np.uint8)
        cv2.putText(placeholder, "Waiting for video stream...",
                    (10, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
        cv2.imshow("Video feed", placeholder)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        mini.stoprobot()
        time.sleep(0.05)
        continue
 
    try:
        frame = cv2.resize(frame, (320, 240))
        h, w = frame.shape[:2]
        debug = frame.copy()
 
        red_mask  = get_red_mask(frame)
        blue_mask = get_blue_mask(frame)
 
        red_contours,  _ = cv2.findContours(red_mask,  cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        blue_contours, _ = cv2.findContours(blue_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 
        decision     = "FORWARD"
        servo_angle  = SERVO_CENTER
        red_found    = False
        blue_found   = False
        now          = time.time()

Step 9: Detect a Red Obstacle and Steer Left

Only red contours larger than 3000 pixels are kept. The largest one is taken as the obstacle; a red box and a yellow centre dot are drawn on it, the steering angle is calculated for a left turn, and the obstacle is saved in last_obstacle with an expiry time.

  # %% Find the LARGEST red contour above threshold %%%%%%%%%%%%%%%
        valid_red = [c for c in red_contours if cv2.contourArea(c) > 3000]
        if valid_red:
            cnt = max(valid_red, key=cv2.contourArea)
            red_found = True
            x, y, w_box, h_box = cv2.boundingRect(cnt)
            cx = x + w_box // 2          # horizontal centre of obstacle
 
            cv2.rectangle(debug, (x, y), (x + w_box, y + h_box), (0, 0, 255), 2)
            # Mark the centre so you can see what the servo is reacting to
            cv2.circle(debug, (cx, y + h_box // 2), 5, (0, 255, 255), -1)
            servo_angle = calc_servo_angle(cx, w, "left")
            decision    = f"RED -> LEFT  angle={servo_angle}"
 
            last_obstacle = {
                "direction": "left",
                "angle":     servo_angle,
                "expires_at": now + OBSTACLE_PERSISTENCE_SEC
            }

Step 10: Detect a Blue Obstacle and Steer Right

If no red obstacle was found, the same check is done for blue. The largest blue obstacle gets a blue box and centre dot, the steering angle is calculated for a right turn, and the obstacle is saved in last_obstacle.

 # %% Find the LARGEST blue contour above threshold %%%%%%%%%%%%%%
        if not red_found:
            valid_blue = [c for c in blue_contours if cv2.contourArea(c) > 3000]
            if valid_blue:
                cnt = max(valid_blue, key=cv2.contourArea)
                blue_found = True
                x, y, w_box, h_box = cv2.boundingRect(cnt)
                cx = x + w_box // 2
 
                cv2.rectangle(debug, (x, y), (x + w_box, y + h_box), (255, 0, 0), 2)
                cv2.circle(debug, (cx, y + h_box // 2), 5, (0, 255, 255), -1)
 
                servo_angle = calc_servo_angle(cx, w, "right")
                decision    = f"BLUE -> RIGHT  angle={servo_angle}"
 
                last_obstacle = {
                    "direction": "right",
                    "angle":     servo_angle,
                    "expires_at": now + OBSTACLE_PERSISTENCE_SEC
                }

Step 11: Keep Turning After the Obstacle Leaves the View

If neither colour is visible but the last obstacle has not expired yet, the robot keeps the previous steering angle and shows how much time is left. Once the time is over, last_obstacle is cleared and the servo returns to the centre.

 # %% Persistence: keep last turn if obstacle just left frame %%%%
        if not red_found and not blue_found:
            if last_obstacle and now < last_obstacle["expires_at"]:
                servo_angle = last_obstacle["angle"]
                remaining   = last_obstacle["expires_at"] - now
                decision    = (f"PERSIST {last_obstacle['direction'].upper()} "
                               f"angle={servo_angle} ({remaining:.1f}s left)")
            else:
                last_obstacle = None   # fully expired → go straight
                servo_angle   = SERVO_CENTER
                decision      = "FORWARD"

Step 12: Apply the Commands

The chosen angle is written to the servo on S1 and both motors run forward at FORWARD_SPEED. The decision is written on the video feed, the three windows are updated, and pressing Q exits the program.

 # %% Apply commands %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        intellio.write("S1",servo_angle)
        # set_servo_angle(servo_angle)
        mini.runbothmotors('1','1',int(FORWARD_SPEED), int(FORWARD_SPEED))
        # control_motors(FORWARD_SPEED, FORWARD_SPEED)
 
        cv2.putText(debug, decision, (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
 
        cv2.imshow("Video feed", debug)
        cv2.imshow("Red Mask",   red_mask)
        cv2.imshow("Blue Mask",  blue_mask)
 
        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. When the loop ends, the video receiver is closed, the robot is stopped and all OpenCV windows are closed.

except Exception as ex:
        print("Loop Error:", ex)
        mini.stoprobot()
 
# Cleanup
receiver.stop()
mini.stoprobot()
cv2.destroyAllWindows()

Output

Run the program and place the robot on the floor with a red or blue obstacle ahead. Three windows open: Video feed (the camera view with the detected obstacle and the current decision), Red Mask and Blue Mask. The robot drives forward, steers left when it sees a red obstacle and right when it sees a blue one, keeps turning briefly after passing the obstacle, and then straightens up. Press Q to stop.

[Output GIF]

Conclusion

In this project, we built a camera-based obstacle avoider robot with Quarky Intellio using Python and OpenCV in PictoBlox. We received a live camera stream, used HSV colour masks to find red and blue obstacles, and picked the largest one in each frame. Its position was converted into a smooth steering angle for the servo, and a short persistence timer helped the robot finish each turn safely. As a next step, you can add more colours with their own rules, or slow the motors down when an obstacle is very large and close.