TactivergeLite

Lite / Textbooks / Introduction to Intelligent Systems / Chapter 3

3. Machine vision

Version 1 · Technically checked (automated checks only) · 5 source lessons · Full interactive version

Introduction

A camera image is a grid of numbers, and every vision algorithm is arithmetic on that grid. This chapter builds a small vision pipeline from first principles: store and index pixels, threshold a picture into a mask, slide a kernel across the image to blur or sharpen, find edges with the Sobel operator, and group pixels into objects whose area and centre you can measure. Every step can be checked by hand on a 3 × 3 patch.

Figure 3.1. Sobel on one patch (described in words)

A 3 by 3 patch of pixels with values 20 and 100, brighter towards the lower right, beside the Sobel x and Sobel y kernels. Multiplying and summing gives Gx = 320 and Gy = 160, so the gradient magnitude is √(320² + 160²) ≈ 357.8: a strong edge.

Explanation

Built from 5 School lessons. Each part is the lesson's own explanation.

3.1 Images are arrays of numbers

To a robot, your face is a grid of about two million numbers. Which number is your nose?

A grid of samples

A camera sensor is an array of light-measuring cells. Each one integrates light during the exposure and is converted to a number: the image is sampled in space (pixels) and quantised in brightness (usually 8 bits, 0–255). A greyscale image is a 2D array img[row][col]; row 0 is at the top.

Colour is three arrays

A colour image stores three channels, red, green and blue, so each pixel is a triple like (230, 40, 35) for a red-ish part. Many cameras actually measure one colour per cell through a mosaic of filters and fill in the other two by interpolation.

Size and cost

Memory = width × height × channels × bytes per channel. Processing time grows the same way, so robots often shrink images (downsample), convert to greyscale, or process only a region of interest. Downsampling an image is sampling again, so fine stripes can alias into false patterns, called moiré.

Same lessons as sensors

Each pixel is a sensor reading with noise, bias (a dark offset), limited range (saturated white areas lose detail) and resolution. Everything from weeks 19–23 applies, now in two dimensions.

Common mix-ups

Open the Lite lesson: Images are arrays of numbers

3.2 Thresholding: from picture to mask

Draw one line through the brightness scale and every pixel becomes 'object' or 'not object'. Where should the line go?

A threshold is a rule

mask[r][c] = 1 if img[r][c] ≥ T, else 0. The result is a binary mask: object pixels and background pixels. Everything later, from counting objects to measuring them, works on this mask, so mistakes here spread through the whole pipeline.

Let the histogram choose

A histogram of pixel values for a well-lit scene often has two humps: background and object. A good threshold sits in the valley between them. Automatic methods such as Otsu's choose T to make the two groups as internally similar as possible, which usually lands in that valley.

When one threshold fails

Noise makes the humps overlap, so some pixels are always misclassified. Uneven lighting shifts brightness across the image, so a threshold right on the left is wrong on the right. Fixes: control the lighting, smooth before thresholding, or use an adaptive threshold computed from each region's neighbourhood.

Common mix-ups

Open the Lite lesson: Thresholding: from picture to mask

3.3 Kernels: the moving average goes 2D

Nine numbers in a 3×3 grid can blur a photo, sharpen it or find its edges. How can so few numbers do so much?

Slide, multiply, add

To filter an image, place the kernel over each pixel in turn, multiply each kernel weight by the pixel beneath it, add the nine products, and write the result into a new image at that position. Use a fresh output image: overwriting as you go corrupts the neighbours you still need.

Blur is averaging in 2D

The box blur averages each 3×3 neighbourhood, so independent pixel noise drops by about 3. Like the moving average, it costs sharpness: edges spread over several pixels. A Gaussian kernel weights the centre more than the corners, which blurs more gently for the same noise reduction.

Edges and ranges

At the border the kernel overhangs the image. Common fixes: repeat the nearest pixel (used in the diagram), mirror the image, or skip the border. Outputs can fall outside 0–255 (sharpening, edge kernels), so compute in a wider number type and clip or rescale only for display.

Derivation: Applying a kernel to one pixel
  1. Take the 3×3 neighbourhood centred on the pixel, values p(i, j) for i, j ∈ {−1, 0, 1}.

  2. Take the kernel weights k(i, j) in the same layout.

  3. Output = Σᵢ Σⱼ k(i, j) · p(i, j): nine products, added. (Strict mathematical convolution flips the kernel first, using k(−i, −j); for symmetric kernels like the blur it makes no difference.)

  4. Box blur: all k = 1/9, so the output is the mean of the nine pixels: a 2D moving average. Noise falls by about √9 = 3.

  5. Example patch rows [10, 20, 30] [40, 50, 60] [70, 80, 90] with a box blur: sum = 450, output = 450 ÷ 9 = 50.

  6. Sharpen [[0, −1, 0], [−1, 5, −1], [0, −1, 0]] = identity plus (centre − neighbours). On that patch: 5×50 − (20 + 40 + 60 + 80) = 250 − 200 = 50, unchanged on a smooth ramp; at an edge it exaggerates the difference.

  7. Weights summing to 1 keep average brightness; weights summing to 0 (edge kernels) give 0 on flat regions.

Common mix-ups

Open the Lite lesson: Kernels: the moving average goes 2D

3.4 Edge detection with Sobel

Outlines are where brightness changes fastest. How do you measure 'change' in a grid of numbers?

Edges are gradients

Along a row, a sharp jump in brightness is a large difference between neighbouring pixels: a discrete derivative. Sobel x [[−1, 0, 1], [−2, 0, 2], [−1, 0, 1]] subtracts the left column from the right, giving extra weight to the middle row. Large positive or negative values mark vertical edges; Sobel y does the same for horizontal edges.

Strength and direction

Combine the two responses into the gradient magnitude √(Gx² + Gy²): how strong the edge is, whatever its direction. The angle atan2(Gy, Gx) gives the direction brightness increases. Threshold the magnitude to get an edge map.

Noise is the enemy

Differences amplify noise: two noisy neighbours differ even on a flat surface. Sobel's three-row design already averages a little; blurring first (often with a Gaussian) helps more. It is the image version of the warning that differentiating noisy data makes it noisier.

Common mix-ups

Open the Lite lesson: Edge detection with Sobel

3.5 Finding and measuring objects

A mask says which pixels are 'part'. But how many parts are there, and how big is each one?

Connected components

Scan the mask. When you meet an object pixel that has no label, give it a new label and flood outward: put it in a queue, and repeatedly take a pixel out and add its unlabelled object neighbours. When the queue empties, that whole blob is labelled. Continue the scan for the next blob.

Measuring blobs

For each blob: area is its pixel count; centroid is the mean row and mean column of its pixels; bounding box is the min and max row and column. With a known camera scale (mm per pixel) these become real sizes and positions a gripper can use.

Noise makes fake objects

Single noisy pixels above the threshold become tiny one-pixel 'objects', and a speck of shadow can split one object in two. Pipelines remove blobs below a minimum area, smooth or clean the mask first, and check counts against ground truth rather than trusting them.

Common mix-ups

Open the Lite lesson: Finding and measuring objects

Worked examples

Images are arrays of numbers: example 1

A greyscale camera is 1280 × 720 at 8 bits, 60 fps. What is the raw data rate?

Solution

1280 × 720 = 921,600 bytes per frame; × 60 = 55.3 MB/s. That is why the robot crops to the 200 × 200 region it actually needs (2.4 MB/s).

Thresholding: from picture to mask: example 1

Background pixels range 30–90; object pixels range 150–220. Suggest T and justify.

Solution

Anywhere from 91 to 150 separates them perfectly. The midpoint of the gap, about 120, leaves the most margin for unseen noise on either side.

Kernels: the moving average goes 2D: example 1

Apply Sobel x [[−1, 0, 1], [−2, 0, 2], [−1, 0, 1]] to the patch [10, 10, 80] [10, 10, 80] [10, 10, 80].

Solution

Row sums: (−10 + 80) + 2(−10 + 80) + (−10 + 80) = 70 + 140 + 70 = 280. A large positive value: brightness rises strongly to the right, so there is a vertical edge.

Edge detection with Sobel: example 1

At a pixel, Gx = 120 and Gy = −50. Find the edge strength.

Solution

√(120² + 50²) = √(14400 + 2500) = √16900 = 130.

Finding and measuring objects: example 1

A blob's pixels are at (row, col) (1,1), (1,2), (2,1), (2,2), (3,2). Area and centroid?

Solution

Area = 5. Mean row = (1 + 1 + 2 + 2 + 3)/5 = 1.8; mean column = (1 + 2 + 1 + 2 + 2)/5 = 1.6. Centroid (1.8, 1.6).

Interactive figures, in words

Figure 3.2 from Images are arrays of numbers

Choose the Bright square, then the Gradient. Click pixels to read their values: where is (row 1, column 1)? Which way do column numbers grow? Find the darkest and brightest pixel in the Noisy bar and explain why its 'flat' regions aren't flat.

The pixel diagram shows an 8 × 8 image as a grid of numbered squares. The Bright square image has value 200 in the central 4 × 4 block and 40 elsewhere; the Gradient rises by 30 per column from 20 to 230; the Noisy bar has a brighter band in columns 4 and 5 with random variation of up to ±45 and one bright speck.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. How many bytes is a 320 × 240 RGB image at 8 bits per channel?
    Answer it in “Images are arrays of numbers”
  2. A bright window shows as a block of pixels all exactly 255. What does that tell you?
    Answer it in “Images are arrays of numbers”
  3. Parts on the left of a conveyor are lit twice as brightly as on the right. A single threshold…
    Answer it in “Thresholding: from picture to mask”
  4. A pixel histogram has humps centred at 50 and 180, with very few pixels between 100 and 130. Where should T go?
    Answer it in “Thresholding: from picture to mask”
  5. A kernel's weights add up to 2. Applied to a flat grey region of 100, what does it output?
    Answer it in “Kernels: the moving average goes 2D”
  6. Sobel y responds strongly but Sobel x is near zero. The edge is…
    Answer it in “Edge detection with Sobel”
  7. Edge detection on a noisy image finds edges everywhere. What should you try first?
    Answer it in “Edge detection with Sobel”
  8. Two touching coins are counted as one object. Which statement is true?
    Answer it in “Finding and measuring objects”

Engineering applications

Inspection lines

A factory camera thresholds each part against a backlight, counts the blobs and measures their area. A part whose area is outside tolerance is pushed off the belt.

Lane keeping

Driver-assistance cameras look for strong edges in the lower part of the image, where lane markings should be. Filtering noise before edge detection keeps shadows from looking like lines.

Watch (optional)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

Glossary

Bits and bytes
A bit is a single binary digit, 0 or 1. A byte is 8 bits. n bits can represent 2^n different values. Field Guide
ADC resolution
An n-bit analogue-to-digital converter splits its reference voltage into 2^n steps; one step, the least significant bit, is the smallest change it can detect. Field Guide
Calibration
Calibration compares an instrument's readings with known references and builds a correction, often an offset and a gain, so that future readings are accurate. Field Guide

Project: Count and measure the parts

Create a small synthetic image of parts on a belt (a grid of numbers is enough). Threshold it, find connected objects, and report each one's area and centre. Then add noise and uneven lighting, and show what breaks and how you fixed it.

Deliverables

Write it up on paper or in your own notes. Lite never stores what you write.

References

← 2. Noise and filtering4. Search and planning →