Education › Robotics › Stage 3: Make it think

Perception and computer vision

OpenCV on a Raspberry Pi: line following, colour and object detection, and their limits.

Intermediate ~34 min read Module 12 of 16

Vision gives a robot its richest sense — a camera sees colour, shape, motion, text and faces, far more than any distance sensor. This lesson introduces computer vision for robots in a practical way: what an image really is to a computer, the classic pipeline of turning pixels into a decision, how colour and contour detection let a robot find and track an object, and where deep learning fits. You will use OpenCV, the standard vision library, and come away able to make a robot follow a coloured ball.

After this module you can
  • Describe what a digital image is to a computer and what a pixel holds
  • Walk through the classic detect-an-object vision pipeline
  • Use colour thresholding and contours to find an object with OpenCV
  • Know when to reach for deep learning instead of classic vision

What an image is to a computer

To a computer an image is just a grid of numbers. A colour image is a 3D array — height by width by three channels (blue, green and red in OpenCV's convention) — where each pixel is three values from 0 to 255 giving the intensity of each colour. A 640×480 colour image is nearly a million numbers. Computer vision is the craft of turning that wall of numbers into something meaningful: 'there is a red ball at the centre-left', 'the line curves right', 'a person is ahead'. Everything starts from understanding that the camera hands you an array, and your job is to reduce it to a decision the robot can act on.

Tip

Colour space matters. RGB mixes brightness into every channel, so a red object looks very different in shade and in sun. Converting to HSV (hue, saturation, value) separates the colour (hue) from the brightness (value), which makes colour detection far more robust to lighting — the first trick every vision beginner should learn.

The classic vision pipeline

Most simple robot-vision tasks follow the same pipeline, and knowing the stages lets you build almost any basic detector. Capture a frame from the camera. Pre-process it — resize smaller for speed, blur slightly to reduce noise, convert to a useful colour space. Segment — isolate the pixels you care about, for example everything within a colour range, producing a black-and-white mask. Find features — group the white pixels into shapes (contours), and measure them (area, centre, bounding box). Decide — pick the shape that matches what you want (the largest blob of the right colour) and turn its position into an action (steer toward its centre). Each stage is a few lines with OpenCV, and together they take you from raw pixels to a motor command.

  • Capture → grab a frame from the camera.
  • Pre-process → resize, blur, convert colour space.
  • Segment → threshold to a mask of the pixels you want.
  • Find features → contours, areas, centres, bounding boxes.
  • Decide → choose the target and turn its position into an action.

Finding a coloured object with OpenCV

Here is the pipeline in code: convert to HSV, threshold to a mask for a colour range, find contours, pick the biggest, and compute its centre. The centre's horizontal position tells a robot whether the object is to its left or right — everything a colour-following robot needs.

python
import cv2, numpy as np

cap = cv2.VideoCapture(0)
lower = np.array([100, 120, 70])    # HSV range for a blue object
upper = np.array([130, 255, 255])

while True:
    ok, frame = cap.read()
    if not ok:
        break
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower, upper)          # white where blue
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)
    if contours:
        biggest = max(contours, key=cv2.contourArea)
        if cv2.contourArea(biggest) > 500:         # ignore tiny specks
            x, y, w, h = cv2.boundingRect(biggest)
            cx = x + w // 2                        # object's x centre
            print('object at x =', cx)             # steer toward cx
    if cv2.waitKey(1) == 27:
        break

When classic vision is enough — and when it is not

Colour and contour tricks are fast, run on a small computer, and are perfectly good for well-defined tasks: follow a bright ball, track a coloured line, find a marker of known colour. Their weakness is that they break when the world is messy — varied lighting, cluttered backgrounds, or objects defined by *what they are* rather than a single colour. 'Find any person' or 'is this a cat or a dog' cannot be done by thresholding a colour. That is the job of deep learning — neural networks trained on many labelled images that recognise objects by learned features. On robots this often runs as a pre-trained object detector (like a YOLO model) that returns boxes and labels. The practical guidance: reach for classic vision first because it is simple and cheap, and move to a learned detector only when the task genuinely needs to recognise *categories* of things rather than a distinct colour or shape.

Note

A useful dividing line: if you can describe the target by a colour, a shape, or a marker, classic OpenCV will likely do it. If the target is a category ('a person', 'a chair', 'a stop sign') that varies in appearance, you want a trained neural-network detector.

Hands-on practice

Make the robot see a colour

  1. Open the camera with OpenCV and display the live frames in a window.
  2. Convert each frame to HSV and use inRange to make a mask for an object's colour.
  3. Tune the HSV lower and upper bounds until the mask is clean white on the object and black elsewhere.
  4. Find contours, pick the largest above a minimum area, and draw its bounding box on the frame.
  5. Print whether the object's centre is on the left or right half — the signal a follow-the-object robot would steer on.
Cheat sheet

Perception and computer vision — at a glance

Main things to focus on

  • An image is a grid of numbers: height × width × 3 colour channels, each 0–255.
  • Convert to HSV so colour (hue) is separated from brightness for robust detection.
  • The pipeline: capture → pre-process → segment → find features → decide.
  • inRange makes a mask; findContours groups the mask into shapes.
  • The largest contour's centre tells the robot where the object is.
  • Use classic vision for colour/shape; deep learning for object categories.

Images

H × W × 3shape of a colour image array
0–255 per channelintensity of blue, green, red
BGROpenCV's channel order
HSVseparates hue from brightness

Pipeline stages

capturegrab a frame from the camera
pre-processresize, blur, convert colour space
segmentthreshold to a mask of wanted pixels
decidepick the target, turn it into an action

OpenCV calls

cvtColor(f, BGR2HSV)convert to HSV
inRange(hsv, lo, hi)mask pixels in a colour range
findContours(mask, ...)group white pixels into shapes
contourArea / boundingRectmeasure a contour

Choosing an approach

classic visionfast, cheap; colour and shape
deep learningrecognises object categories
object detectorreturns labelled boxes (e.g. YOLO)

Common pitfalls

  • Detecting colour in RGB, so shade and sun break it — convert to HSV first.
  • Keeping tiny noise blobs instead of ignoring contours below a minimum area.
  • Running full-resolution frames and being too slow — resize before processing.
  • Reaching for deep learning when a simple colour threshold would do the job.
  • Expecting a colour threshold to recognise a category like 'a person'.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →