Level 3 Intelligent Robotic Systems · Term 3: Sensing and Perception
How sensors and cameras turn the world into numbers, why those numbers are uncertain, and how a machine can sample, filter, interpret and decide despite the uncertainty, using statistics, signals and probability.
In this file: 27 lessons across weeks 19–27, with 136 practice questions (questions only, no answers).
Design, model and evaluate simulated robotic systems that integrate computation, the mathematics of motion, perception and feedback, and compare them fairly against alternatives. Levels describe what you can do, not your age. About About 3–4 hours a week: 1.5 hours of lessons, 1–1.5 hours of coding or lab work and 30–60 minutes of analysis and writing..
Week 19: Sensor characteristics
This week you will
- Compare sensors by range, resolution, accuracy, precision, linearity and latency.
- Compute the step size of an n-bit converter and the bits needed for a target resolution.
- Build a two-point calibration and estimate the error caused by latency.
Range, resolution and the bits behind them
A 10-bit and a 16-bit sensor both measure 0–5 V. One sees changes 64 times smaller. Does that make it 64 times more accurate?
Why it matters
Every robot spec sheet lists range and resolution first, because they decide what a sensor can possibly see. Pick the range too small and the reading sticks at its limit exactly when it matters; pick too few bits and small changes vanish between steps. Engineers check both before they write a line of code.
Goals
- Define range, resolution and saturation for a sensor and its converter.
- Calculate the step size of an n-bit converter as range ÷ 2ⁿ, and the bits needed for a target step.
- Explain why finer resolution does not guarantee better accuracy.
Predict
An 8-bit converter spans 0–5 V. Roughly how small a change in voltage can it notice?
- About 5 mV
- About 20 mV
- About 0.6 V
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start at 4 bits and slide the true input slowly: the reading jumps in steps. Raise the bits and watch the staircase shrink. Then push the input past the top of the range, and finally add bow. Which problems do extra bits fix, and which don't they touch?
What the interactive shows, in words
The diagram plots the reported voltage against the true input as a staircase. With 4 bits the steps are 0.31 V tall on a 5 V range; with 12 bits they are 1.2 mV and the staircase looks like a straight line. Inputs above the top of the range all read the maximum code (saturation). Adding bow curves the staircase away from the straight line by up to bow × range ÷ 4, an error extra bits cannot remove.
Understand
Range: what it can see at all
The range is the span of inputs a sensor reports faithfully, for example 0–5 V or 2–400 cm. Outside it the output saturates: it sticks at the end value. A saturated reading is the most dangerous kind, because it looks like a normal number. Choose a range that covers the largest value you could meet, with some margin.
Resolution: the smallest step
A converter with n bits has 2ⁿ codes. Spread over the range, each step is range ÷ 2ⁿ wide (some datasheets divide by 2ⁿ − 1; the difference is tiny for large n). A 12-bit converter on 0–3.3 V has steps of 3.3 ÷ 4096 ≈ 0.81 mV. Every reading carries an extra uncertainty of up to one step, called quantisation error.
Resolution is not accuracy
Resolution says how finely the sensor divides the range. Accuracy says how close the reported value is to the truth. A sensor with a gain error, an offset or a bow in its response can report confidently in tiny steps and still be wrong by a lot. Extra bits help only when quantisation is the biggest error.
Reading a spec line
'Range 0–40 °C, resolution 0.01 °C, accuracy ±0.5 °C' tells you the readings move in hundredths but can be half a degree off. For a greenhouse that is fine; for a medical thermometer it is not. Always ask which number limits your task.
Explain it another way: intuitive
A ruler marked only in centimetres can't tell 3.2 cm from 3.4 cm: that is resolution. A ruler printed slightly stretched gives tidy millimetre marks that are all a bit wrong: that is accuracy.
Explain it another way: technical
An ideal n-bit ADC with full-scale range FSR maps an input to code ⌊V·2ⁿ/FSR⌋, clipped to 0…2ⁿ − 1. One LSB = FSR/2ⁿ; quantisation error is uniform over one LSB, with standard deviation LSB/√12 when the signal is busy enough.
Explain it another way: mathematical
Bits needed for a step no bigger than Δ over range R: 2ⁿ ≥ R/Δ, so n = ⌈log₂(R/Δ)⌉. For R = 5 V and Δ = 1 mV: log₂(5000) ≈ 12.3, so 13 bits.
Explain it another way: applied
Microcontrollers commonly have 10- or 12-bit ADCs. Designers often scale a small sensor signal with an amplifier so it fills the converter's range: a 0–0.5 V signal on a 0–5 V converter wastes over 90% of the codes.
Try these examples
Example 1
A 10-bit ADC spans 0–3.3 V. What is one step, and what code does 1.00 V give?
The worked solution is in the online lesson.
Example 2
A load cell's amplifier outputs 0–2 V and you want 0.1 mV steps. How many bits?
The worked solution is in the online lesson.
Common mix-ups
More decimal places on the display mean a more accurate sensor.
✓ Decimal places show resolution. Accuracy comes from calibration and the sensor's physics, and is stated separately on the datasheet.A sensor at the top of its range is just measuring a big value.
✓ It may be saturated: the true value could be anything above the limit.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A distance sensor's range is 2–80 cm. A wall is 120 cm away. What will it most likely report?
- 120 cm
- About 80 cm, its maximum
- 0 cm
- An error message, always
2. An 8-bit converter spans 0 to 10 V. Taking one step as range ÷ 2^n, how big is one step, in millivolts?
Answer: mV
3. How many distinct codes does a 12-bit converter have?
Answer:
4. A sensor has a ±2% gain error. Upgrading its converter from 10 to 16 bits will…
- remove the gain error
- make readings finer-grained but still up to 2% off
- make the readings less precise
5. A sensor outputs 0–0.5 V into a 10-bit converter spanning 0–5 V. How many of the 1024 codes can it actually use?
Answer: codes
Apply it
Pick a sensor for a line-following robot's distance check (obstacles from 5 cm to 1.5 m, needed to the nearest centimetre). Write the range and resolution you need, the bits required if the sensor outputs 0–3.3 V linearly, and one thing the spec must also tell you about accuracy.
Reflect
Describe a situation where a sensor's resolution is excellent but its readings are still useless for the task.
Accurate, precise, both or neither
Five readings that agree to the millimetre can all be 3 cm wrong. How would you ever know?
Why it matters
A robot gripper that repeatably closes 3 mm off-target is easy to fix with an offset. One that lands somewhere different each time needs a different fix entirely. Telling the two apart is the first step in improving any measurement.
Goals
- Distinguish accuracy (closeness to the truth) from precision (closeness of repeated readings).
- Link bias to accuracy and random scatter to precision.
- Explain why you need a reference value to measure accuracy, but not precision.
Predict
Readings cluster tightly but well away from the bullseye. What would help most?
- Take many more readings and average them
- Calibrate against a known reference and subtract the offset
- Buy a sensor with more bits
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Make all four combinations: accurate and precise, precise but biased, accurate on average but scattered, and neither. For each, note what you changed: bias or spread? Then switch to 40 readings. Which problem does more data fix?
What the interactive shows, in words
The target shows readings as dots around a bullseye. Bias sliders shift the whole cluster; the spread slider widens it. The orange cross marks the average. With bias 0 and spread 3 the cluster is tight and centred (accurate and precise); with bias 20 and spread 3 it is tight but off-centre (precise, biased); with bias 0 and spread 20 it is wide but centred; more readings move the cross closer to the cluster's true centre but never remove bias.
Understand
Two different questions
Accuracy: is the average reading close to the true value? Precision: do repeated readings agree with each other? They are independent. A bathroom scale that always reads 2 kg heavy is precise and inaccurate; a cheap thermometer whose readings jump around a correct average is accurate on average and imprecise.
Bias moves, noise spreads
A systematic error (bias) shifts every reading the same way: a zero offset, a mis-set gain, a sensor warmed by its own electronics. A random error scatters readings unpredictably: electrical noise, vibration, quantisation. Bias damages accuracy; noise damages precision.
You need the truth to see bias
You can measure precision from the readings alone: just look at their spread. Accuracy needs a reference: a known weight, a measured distance, a calibrated instrument. Without one, a biased sensor looks perfectly healthy. This is why calibration rigs exist.
Explain it another way: intuitive
Darts: a tight group in the corner is a good thrower with a bent sight. A wide scatter around the bullseye is a wobbly thrower with a true sight.
Explain it another way: technical
For readings xᵢ of a true value μ: bias = x̄ − μ (accuracy), and the sample standard deviation s measures precision. Total error of one reading combines both: its mean squared error is bias² + σ².
Explain it another way: applied
Industrial robots are specified separately for repeatability (precision, often a few hundredths of a millimetre) and absolute accuracy (often much worse). Many tasks only need repeatability, because the robot is taught positions by hand.
Try these examples
Example 1
A 100.0 g reference mass is weighed five times: 101.9, 102.1, 102.0, 101.8, 102.2 g. Describe accuracy and precision.
The worked solution is in the online lesson.
Common mix-ups
Precise readings must be accurate.
✓ A tight group can sit far from the truth. Only a reference reveals bias.Averaging fixes every kind of error.
✓ Averaging shrinks random error. Bias survives any amount of averaging.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Readings: 49.1, 50.8, 48.7, 51.5, 49.9 for a true value of 50. Which describes them?
- Accurate and precise
- Accurate on average, not very precise
- Precise but biased
- Neither
2. A 20.0 cm gauge block measures 20.6, 20.4, 20.5, 20.5 cm. What is the bias, in cm?
Answer: cm
3. Which can you measure without knowing the true value?
- Accuracy
- Precision
- Both
- Neither
4. A lidar's readings scatter randomly by ±4 cm around the right answer. Which fix targets that?
- Subtract a fixed offset
- Average several readings
- Recalibrate the gain
Apply it
Design a calibration check for a kitchen scale using objects of known mass (for example, unopened packets). Write the procedure, how many repeats you would take, and how you would report accuracy and precision separately.
Reflect
Which matters more for a robot that must stack boxes neatly on top of each other: accuracy or precision? Why?
Linearity, calibration and latency
A sensor is perfectly accurate, but its answer arrives 200 ms late. At 2 m/s, how far has the robot moved?
Why it matters
Raw sensor numbers are rarely in the units you want. Calibration turns them into centimetres or newtons, and knowing a sensor's latency tells you whether its answer still describes the world by the time you use it.
Goals
- Describe linearity and non-linearity in a sensor's response.
- Build a two-point calibration that converts raw readings to physical units.
- Explain latency and bandwidth and estimate the error latency causes on a moving robot.
Predict
A sensor reads 120 at 0 kg and 920 at 10 kg, and responds in a straight line. What does a reading of 520 mean?
- 5.2 kg
- 5.0 kg
- 4.0 kg
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, write calibrate(raw) for the load cell in the prediction: compute the gain and offset from the two calibration points, then test it on 120, 520 and 920. Add a check that warns when a reading falls outside the calibrated span.
What the interactive shows, in words
This lesson uses the Code Lab. Equivalent paper task: given calibration points (0 kg, 120 counts) and (10 kg, 920 counts), compute gain = 80 counts per kg, then convert readings 120, 520 and 920 to 0, 5 and 10 kg, and flag readings below 120 or above 920 as outside the calibrated span.
Understand
Linear response
A linear sensor's output is a straight line of its input: output = gain × input + offset. Many sensors are nearly linear over part of their range and curve near the ends. Linearity on a spec sheet says how far the real curve strays from the best straight line, often as a percentage of full scale.
Two-point calibration
Measure two known inputs and record the raw outputs. The gain is the change in raw reading per unit input: (r₂ − r₁) ÷ (x₂ − x₁). Then input = (raw − r₁) ÷ gain + x₁. Choose the two points near the ends of the span you care about, and check a third point in the middle to spot non-linearity.
Latency and bandwidth
Latency is the delay between something happening and the reading reflecting it: conversion time, filtering, communication. Bandwidth describes how fast a change the sensor can follow at all. A robot moving at speed v that acts on a reading with latency τ is acting on a world that has already moved v × τ.
Spec-sheet honesty
Most numbers on a datasheet hold only under stated conditions: temperature, supply voltage, warm-up time. Calibrate in conditions like the ones the robot will meet, and re-check after big changes.
Explain it another way: intuitive
Calibration is like learning a friend's accent: once you know how their 'raw' sounds map to words, you understand them perfectly. Latency is like hearing thunder after the lightning.
Explain it another way: technical
With calibration points (x₁, r₁), (x₂, r₂): gain k = (r₂ − r₁)/(x₂ − x₁), x = x₁ + (r − r₁)/k. Residuals at extra reference points estimate non-linearity. Position error from latency τ at speed v is approximately v·τ.
Explain it another way: mathematical
If the true response is r = k·x + c + b·x(X − x)/X (a bow of size b over span X), a two-point fit at x = 0 and x = X leaves an error that peaks at mid-span, x = X/2, of size b·X/4 in output units.
Explain it another way: applied
Line-scan cameras on conveyors trigger exposures from an encoder so latency is constant, then shift the reject actuator's timing by the known delay. Without that, a 50 ms delay at 1 m/s misses the part by 5 cm.
Try these examples
Example 1
An IR distance sensor reads 3.1 V at 10 cm and 0.8 V at 40 cm. Assuming linearity between them, what distance does 1.95 V mean?
The worked solution is in the online lesson.
Example 2
A camera pipeline has 80 ms latency and the robot drives at 1.5 m/s. How far does it travel before it can react?
The worked solution is in the online lesson.
Common mix-ups
Calibrating once at the factory is enough forever.
✓ Sensors drift with temperature, age and mounting. Critical systems re-check calibration regularly.If a sensor is accurate, its timing doesn't matter.
✓ A late reading of a moving world is wrong by speed × latency, however accurate it was when taken.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A pressure sensor reads 200 counts at 0 kPa and 3200 counts at 100 kPa. What is its gain in counts per kPa?
Answer: counts/kPa
2. Using that calibration (200 counts at 0 kPa, 30 counts per kPa), what pressure does a reading of 1700 counts mean, in kPa?
Answer: kPa
3. A drone flying at 6 m/s uses an altimeter with 50 ms latency. How far does it move during that latency, in metres?
Answer: m
4. Why check a third reference point in the middle after a two-point calibration?
- To double the resolution
- To reveal non-linearity the two end points cannot show
- Because two points are not enough to draw a line
5. A temperature probe takes 20 s to settle after being dipped in hot water. This mostly limits its…
- range
- resolution
- speed of response (bandwidth and latency)
- accuracy at steady state
Apply it
Extend your calibrate() function to take any number of reference points and report the largest residual from the best straight line through the end points. Test it on a sensor that bows by 2% at mid-span and say whether two-point calibration is good enough for ±1% accuracy.
Reflect
Which would you rather fix on a fast robot: a constant 3 cm offset or a 100 ms latency? Explain.
Week 20: Measurement uncertainty
This week you will
- Distinguish random from systematic error and predict how each behaves when integrated.
- Compute a mean, a sample standard deviation and the standard error σ/√n.
- Plan the number of readings for a target uncertainty and draw honest error bars.
Random and systematic error
A wheel that measures 1% too big makes a robot think it has driven 101 m after 100 m. After a kilometre, where is it?
Why it matters
Robots that dead-reckon (count wheel turns or integrate speed) carry tiny systematic errors that add up every step. Cameras carry random noise that does not accumulate. Fusion systems exist to let one sensor's strengths cover the other's weakness, and they only work if you know which error is which.
Goals
- Classify an error source as random or systematic and predict its effect over time.
- Explain why a small systematic error in a rate sensor grows without limit when integrated.
- Choose a strategy that suits each kind of error.
Predict
Odometry has a small constant speed bias; the camera has big random noise but no bias. After 20 seconds, which is likely further from the truth?
- The camera, because its noise is bigger
- The odometry, because its bias keeps adding up
- Both the same
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Hide the fused estimate and compare camera readings with odometry. Set odometry bias to +2 cm/s and noise to 0: watch the drift. Then set bias to 0 and raise camera noise. Which error grows with time, and which just jitters?
What the interactive shows, in words
The fusion lab plots true position, camera readings, odometry and a fused estimate over 20 seconds. With odometry bias +2 cm/s and no noise, the odometry line drifts steadily away from the truth, 40 cm after 20 s. With camera noise 8 cm and no bias, camera crosses scatter around the true line but do not drift.
Understand
Systematic error repeats
A systematic error is the same, or follows the same pattern, every time: a wheel diameter set 1% too large, a thermometer mounted next to a warm motor, a camera that is slightly tilted. Repeating the measurement repeats the error, so averaging cannot reveal or remove it.
Random error varies
A random error differs unpredictably each time, scattering readings around their average: electrical noise, vibration, the exact pixel where an edge falls. Independent random errors partly cancel when you average, which is why taking more readings helps.
Integration grows systematic error
Odometry adds up small steps. A constant speed bias b adds b × Δt of position error each step, so after time t the error is b × t: it grows forever. Random step errors also accumulate, but more slowly (like √t). That is why dead-reckoning robots drift and need an absolute reference such as a camera, GPS or a landmark.
Different errors, different cures
Fight systematic error with calibration against a reference and with good design (move the thermometer away from the motor). Fight random error with averaging, filtering and better sensors. Fusion combines a sensor that drifts with one that is noisy but unbiased.
Explain it another way: intuitive
Walking with your eyes shut and one slightly shorter leg, you curve the same way every step: that's systematic. A gusty wind pushes you randomly left and right: that's random. After a long walk, the leg matters more.
Explain it another way: technical
Model a reading as x = μ + b + ε, with bias b and zero-mean noise ε of standard deviation σ. The mean of n readings has expected value μ + b and standard deviation σ/√n: noise shrinks, bias does not.
Explain it another way: mathematical
Integrated odometry with speed bias b and independent per-step noise of standard deviation σ per step of Δt: position error after N steps has mean b·N·Δt and standard deviation σ·Δt·√N. The bias term grows like N, the noise term like √N.
Explain it another way: applied
Rovers on Mars periodically re-localise against landmarks in camera images because wheel slip on sand adds systematic error to odometry that no amount of averaging can remove.
Try these examples
Example 1
A robot's odometry overestimates speed by 0.5 cm/s. How far off is its position estimate after 2 minutes?
The worked solution is in the online lesson.
Common mix-ups
If readings look steady, the measurement is good.
✓ Steady readings can share a large systematic error. Only a reference check reveals it.Random errors add up just like systematic ones when integrated.
✓ Independent random errors partly cancel, so they grow like √t; a constant bias grows like t.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A digital thermometer is mounted 2 cm from a voltage regulator that runs warm. Its error is mainly…
- random
- systematic
- quantisation
2. A speed bias of 1.5 cm/s is integrated for 40 s. What is the position error, in cm?
Answer: cm
3. Vibration from a motor makes an accelerometer's readings jump around their correct average. That is…
- random error
- systematic error
- saturation
4. A camera is mounted 2° tilted, so every measured height is 3% low. What is the best fix?
- Average more frames
- Measure the tilt against a reference and correct for it
- Use a faster camera
Apply it
In the fusion lab, find an odometry bias that makes dead-reckoning more than 20 cm wrong after 20 s. Then turn on the Kalman filter with camera dropouts at 30%. Describe, with numbers, how the fused estimate behaves during a dropout and after the camera returns.
Reflect
Name one systematic and one random error in a measurement you have made yourself, and how you could reduce each.
Mean, spread and the histogram
Ten readings of the same distance never match. Which single number should the robot believe, and how much should it trust it?
Why it matters
A single reading hides its own uncertainty. Repeating it and summarising the results with a mean and a standard deviation tells you both the best estimate and how much it wobbles: the two numbers every honest measurement report needs.
Goals
- Compute the mean and the sample standard deviation of a set of readings.
- Read a histogram of repeated measurements and estimate its centre and spread.
- Explain why the sample standard deviation divides by n − 1.
Predict
A sensor with noise σ = 4 gives 64 readings. Roughly how wide is the middle two-thirds of the histogram?
- About 1 unit
- About 8 units (σ either side of the mean)
- About 64 units
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Stay on 'One batch'. Take 64 readings with σ = 4 and look at the histogram's shape. Compare the sample standard deviation with σ. Now try n = 4 several times with new data: how much does the estimate of σ itself jump around?
What the interactive shows, in words
The diagram draws a histogram of readings from a sensor with adjustable noise σ and bias. With n = 64 and σ = 4, the bars form a hump centred near the true value plus bias, about 16 units wide in total; the readout lists the readings, the mean and the sample standard deviation, which comes out close to 4.
Understand
The mean: best single estimate
The mean x̄ = (x₁ + x₂ + … + xₙ) ÷ n. When errors are random and unbiased, it is the best single guess of the true value. It is sensitive to outliers: one glitch reading of 9999 drags it badly, which is why spikes are often removed first.
Standard deviation: typical distance
The sample standard deviation s = √(Σ(xᵢ − x̄)² ÷ (n − 1)) measures how far readings typically sit from their mean. Same units as the readings. For bell-shaped (normal) noise, about 68% of readings fall within ±s of the mean and about 95% within ±2s.
Why n − 1?
The deviations are measured from x̄, which was computed from the same readings, so they come out a little smaller than deviations from the true value would. Dividing by n − 1 instead of n corrects that on average. With 3 readings it matters a lot; with 300 it barely matters.
Histograms show the shape
A histogram counts readings in equal bins. A single tall, symmetric hump suggests random noise. Two humps suggest two different conditions mixed together; a long tail on one side suggests occasional glitches. Always look before you average.
Explain it another way: intuitive
The mean is the balance point of the readings on a seesaw. The standard deviation is how far, typically, each reading sits from that balance point.
Explain it another way: technical
x̄ = Σxᵢ/n, s² = Σ(xᵢ − x̄)²/(n − 1). For independent normal noise of standard deviation σ, s is an estimate of σ whose own uncertainty is roughly σ/√(2(n − 1)).
Explain it another way: mathematical
Σ(xᵢ − x̄)² = Σ(xᵢ − μ)² − n(x̄ − μ)². Its expected value is nσ² − σ² = (n − 1)σ², so dividing by n − 1 gives an unbiased estimate of σ².
Explain it another way: applied
Datasheets often quote noise as an RMS value (a standard deviation) and sometimes as peak-to-peak, which is several times larger for the same sensor. Know which you are reading before comparing two sensors.
Try these examples
Example 1
Readings: 10.2, 9.8, 10.4, 9.6, 10.0 cm. Find x̄ and s.
The worked solution is in the online lesson.
Common mix-ups
More readings make the histogram narrower.
✓ More readings fill in the histogram's shape; its width is set by the sensor's noise. It is the mean that becomes more certain.Standard deviation and range (max − min) are the same.
✓ Range depends on the two most extreme readings and grows with n; standard deviation summarises them all.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Readings 4.1, 3.9, 4.3, 3.7 V. What is the mean, in volts?
Answer: V
2. A distance sensor gives these repeated readings (cm): 98, 98, 102, 102.5. What is their mean, in cm?
Answer: cm
3. A distance sensor gives these repeated readings (cm): 48.5, 48.5, 47.5, 46, 45. What is their sample standard deviation (divide by n − 1), in cm?
Answer: cm
4. Noise is bell-shaped with mean 50 and s = 2. About what share of readings lie between 46 and 54?
- About 50%
- About 68%
- About 95%
- All of them
5. A histogram of a robot's distance readings has two separate humps. What should you suspect first?
- The noise is very large
- Two different conditions are mixed (for example, two surfaces or two targets)
- The mean is the best estimate
Apply it
Write a Python function summary(readings) that returns the mean, sample standard deviation and the share of readings within ±2s. Test it on the readings from the diagram with n = 64, and compare the share with 95%.
Reflect
Why should a measurement report give a spread, not just a mean?
The standard error: how sure is the average?
To make an average twice as trustworthy, do you need twice as many readings, or four times?
Why it matters
Engineers report a mean with an uncertainty so others can judge whether two results really differ. The standard error is that uncertainty for an average, and its square-root law tells you how much testing a result is worth.
Goals
- Distinguish the spread of readings (σ) from the spread of their mean (σ/√n).
- Derive and use the standard error SE = σ/√n, including finding n for a target SE.
- Draw and interpret honest error bars, and state what they leave out.
Predict
Readings have σ = 4. How does the spread of the mean of 16 readings compare?
- Still 4
- 1, a quarter as big
- 0.25, a sixteenth as big
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Switch to 'Means of 200 batches'. With σ = 4, compare n = 1, 4, 16 and 64: write down the spread of the means each time next to σ ÷ √n. Then add a bias of +5. What happens to the means' centre, and to their spread?
What the interactive shows, in words
In 'Means of 200 batches' mode the histogram shows 200 averages. With σ = 4: n = 1 gives a spread of about 4, n = 4 about 2, n = 16 about 1 and n = 64 about 0.5, matching σ ÷ √n. Adding bias +5 shifts the whole histogram 5 units right without changing its width.
Understand
Two spreads, two jobs
σ (or its estimate s) describes one reading: use it to judge how far a single measurement might be off. SE = σ/√n describes the average of n readings: use it to judge how well you know the true value. Mixing them up is one of the most common errors in lab reports.
Error bars that mean something
An error bar must say what it shows: ±1 SE, ±2 SE or ±1 s. Roughly, the true value lies within ±2 SE of the mean about 95% of the time, if errors are random, independent and unbiased. State n alongside it so readers can convert.
What standard error cannot see
SE only measures random scatter. A miscalibrated sensor gives a beautifully small SE around the wrong value. Readings taken too quickly may not be independent (the same vibration affects several), and then the real uncertainty is larger than σ/√n.
Explain it another way: intuitive
One person's guess of a jar of sweets can be wildly off. The average of a hundred guesses is far better, but not a hundred times better: about ten times.
Explain it another way: technical
For independent, identically distributed errors with variance σ², Var(x̄) = σ²/n. In practice σ is estimated by s, giving SE ≈ s/√n; for small n a t-distribution widens the confidence interval slightly.
Explain it another way: mathematical
SE ∝ n^(−1/2). On log–log axes, SE against n is a straight line of slope −1/2: every factor of 100 in n buys a factor of 10 in SE.
Explain it another way: applied
Test plans in engineering use n = (σ/SE)² to budget trials: if each drop test of a gripper's grasp force varies by σ = 2 N and you need the mean to ±0.25 N (1 SE), you need 64 tests.
Derivation: Why the mean wobbles by σ/√n
Each reading is xᵢ = μ + εᵢ, where the errors εᵢ are independent, have mean 0 and variance σ² (variance is the standard deviation squared).
The mean is x̄ = (x₁ + … + xₙ)/n = μ + (ε₁ + … + εₙ)/n.
For independent errors, variances add: Var(ε₁ + … + εₙ) = nσ².
Dividing a quantity by n divides its variance by n²: Var(x̄) = nσ²/n² = σ²/n.
Take the square root: the standard deviation of the mean, the standard error, is SE = σ/√n.
Rearranged for planning: to reach a target SE you need n = (σ/SE)², rounded up. Halving SE needs four times the readings.
Bias b adds to every reading, so x̄ = μ + b + (noise): the mean's centre stays shifted by b however large n is.
Try these examples
Example 1
A gyroscope's drift rate is measured 25 times: mean 0.84 °/s, s = 0.30 °/s. Report the result.
The worked solution is in the online lesson.
Common mix-ups
Doubling the data halves the uncertainty.
✓ Uncertainty in a mean shrinks like 1/√n: doubling the data cuts it to about 71%.A small standard error means the answer is right.
✓ It means the random scatter is well averaged. Bias is untouched.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. σ = 6 mm and you average 9 readings. What is the standard error, in mm?
Answer: mm
2. One reading has standard deviation 1.2 °C. What is the smallest number of independent readings n whose mean has a standard error of at most 0.1 °C?
Answer: readings
3. One reading of a temperature sensor has standard deviation 2 °C. You average n = 36 independent readings. What is the standard error of the mean, in °C?
Answer: °C
4. Your mean has SE = 0.4 from 10 readings. How many readings for SE = 0.2?
- 20
- 40
- 100
5. You want to know how far a single future reading might be from the truth. Which spread do you quote?
- The standard error of the mean
- The standard deviation of the readings
- Neither
6. 1000 readings give a mean of 20.03 ± 0.01 °C (1 SE), but a reference thermometer reads 21.0 °C. What is the likely explanation?
- Bad luck: the SE was underestimated
- A systematic error of about 1 °C that SE cannot detect
- Too few readings
Apply it
Plan a test: a lidar's noise is σ = 3 cm and you must report a wall's distance to ±0.5 cm at about 95% (±2 SE). How many independent readings do you need? Then explain what extra test would show whether the readings are really independent.
Reflect
Why do you think the square-root law makes 'just collect more data' an expensive habit?
The RC time constant, from measurements
A capacitor charging through a resistor never quite finishes. So how can engineers say exactly how long it 'takes'?
Why it matters
RC circuits are everywhere in electronics: the power-on reset that holds a microcontroller still until its supply settles, the debounce filter on a button, the low-pass filter that smooths a noisy sensor, the timing in a 555 timer. Each one depends on one number, the time constant τ = RC. Measuring τ from a real curve is also how you find the value of a capacitor whose label has rubbed off.
Goals
- Calculate the time constant τ = RC with correct units.
- Use v(t) = V(1 − e^(−t/τ)) and the 63 % and 5τ landmarks to describe charging.
- Estimate τ (and an unknown capacitance) from measured points on a charging curve.
- Find the time for a charging capacitor to reach a threshold voltage.
Predict
A 1,000 µF capacitor charges from 9 V through 1 kΩ (τ = 1 s). Roughly what is its voltage after 1 second?
- 4.5 V (half way)
- About 5.7 V (63 % of the way)
- 9 V (full)
- About 1 V (it has only just started)
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Run the default circuit (9 V, 1,000 Ω, 1,000 µF) and read the voltage at t = τ from the results. Then double the resistance and run it again: what happens to τ and to the time to reach 90 %? Finally switch to discharge and check that after one τ the voltage is 37 % of where it started.
What the interactive shows, in words
The RC experiment plots capacitor voltage and current against time for a battery charging a capacitor through a resistor. Inputs set the battery voltage (1–12 V), resistance (100 Ω to 100 kΩ), capacitance (1–2,200 µF), charge or discharge, and how many time constants to run. Results list τ = RC, the voltage at t = τ, the fraction of the way at τ (about 0.632) and the time to reach 90 %. With the defaults (9 V, 1 kΩ, 1,000 µF) τ is 1 s, the voltage at 1 s is about 5.69 V and 90 % takes about 2.3 s. The voltage rises quickly at first and then more and more slowly; the current starts at V/R and decays the same way.
Understand
Why it slows down
At switch-on the capacitor is empty, so the whole supply voltage sits across the resistor and a big current I = V/R flows. As charge builds up, the capacitor's voltage rises, the resistor's share falls, and the current shrinks. Less current means slower charging. The voltage approaches the supply ever more slowly: it never quite arrives, but it gets close very quickly.
The curve and its landmarks
The charging voltage is v(t) = V(1 − e^(−t/τ)) with τ = R·C. Ohms times farads gives seconds (and kΩ × µF gives milliseconds). After 1τ the capacitor is at 63.2 % of V, after 2τ 86.5 %, after 3τ 95 %, after 5τ 99.3 %. Engineers usually call it 'charged' after about 5τ. Discharging follows v = V·e^(−t/τ): 36.8 % left after one τ.
Measuring τ from data
On a measured curve, the quickest estimate is the time at which the voltage reaches 63 % of its final value. A better one uses every point: rearrange to τ = −t / ln(1 − v/V), compute it at several times and average. If ln(1 − v/V) plotted against t is a straight line, the circuit really is first-order, and the slope is −1/τ. Knowing R, the capacitance follows as C = τ/R.
Hitting a threshold
Many circuits care about when the capacitor crosses a voltage, such as a chip's reset threshold. Solve v = V(1 − e^(−t/τ)) for t: t = −τ·ln(1 − v/V). Crossing half the supply takes τ·ln 2 ≈ 0.69τ; crossing 90 % takes τ·ln 10 ≈ 2.3τ. Thresholds near the supply voltage take much longer and are sensitive to component tolerances.
Explain it another way: intuitive
Filling a balloon through a thin straw: at first air rushes in, but the fuller the balloon, the harder it pushes back and the slower it fills. A thinner straw (bigger R) or a bigger balloon (bigger C) both make it slower.
Explain it another way: technical
Kirchhoff's voltage law gives V = i·R + v and the capacitor law i = C·dv/dt, so RC·dv/dt + v = V: a first-order linear ODE whose step response is v = V(1 − e^(−t/RC)). Real parts add capacitor leakage, equivalent series resistance and the source's internal resistance, and electrolytic capacitors often have ±20 % tolerance, so a measured τ is the honest way to know the circuit.
Explain it another way: mathematical
Example: 9 V, R = 1 kΩ, C = 1,000 µF, τ = 1 s. v(1 s) = 9 × (1 − e^(−1)) ≈ 5.69 V. Time to reach 5 V: t = −1 × ln(1 − 5/9) ≈ 0.811 s. If you measure 6.0 V at 1.1 s, τ ≈ −1.1/ln(1 − 6/9) = 1.1/1.0986 ≈ 1.001 s, which agrees.
Explain it another way: applied
A microcontroller reset pin often uses a 10 kΩ resistor and a 100 nF capacitor: τ = 1 ms, so the chip stays in reset for about a millisecond while the supply settles. Button debouncing picks τ longer than the contact bounce (a few milliseconds) but short enough to feel instant.
Derivation: Solving the charging equation
Around the loop: V = i·R + v. The capacitor's current is i = C·dv/dt, so R·C·dv/dt = V − v.
Separate variables: dv/(V − v) = dt/(RC).
Integrate from v = 0 at t = 0: −ln(V − v) + ln V = t/(RC), so ln((V − v)/V) = −t/(RC).
Exponentiate: (V − v)/V = e^(−t/RC), so v(t) = V(1 − e^(−t/τ)) with τ = RC.
At t = τ: v = V(1 − e^(−1)) ≈ 0.632·V. Taking logs of the same line gives the measurement formula τ = −t/ln(1 − v/V).
Try these examples
Example 1
With 9 V, 1 kΩ and 1,000 µF, find τ, the voltage at 0.5 s and 2 s, and the time to reach 5 V.
The worked solution is in the online lesson.
Example 2
A capacitor of unknown value charges from 9 V through 1 kΩ. You measure 6.0 V at 1.1 s. Estimate C.
The worked solution is in the online lesson.
Common mix-ups
The time constant is how long the capacitor takes to charge fully.
✓ τ is the time to reach about 63 %. 'Fully' (99 %) takes about 5τ, and mathematically it never quite finishes.A bigger supply voltage makes the capacitor charge faster.
✓ τ = RC does not depend on V. A bigger supply reaches any fixed voltage sooner, but the shape and the 63 % time stay the same.The capacitor value printed on the can is exact.
✓ Electrolytic capacitors often have ±20 % tolerance. Measuring τ and dividing by R gives the real value in your circuit.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. After exactly one time constant, how far has a charging capacitor got towards the supply voltage?
- 50 %
- About 63 %
- About 90 %
- 100 %
2. A 2.2 kΩ resistor charges a 470 µF capacitor. What is the time constant τ, in seconds? (3 decimal places)
Answer: s
3. A 6 V supply charges an empty 220 µF capacitor through 10 kΩ. What is the capacitor voltage after 3.96 s, in volts? (2 decimal places)
Answer: V
4. A reset circuit charges an empty 1000 µF capacitor from 5 V through 47 kΩ. A chip starts when the capacitor reaches 3.55 V. How long after power-on does that happen, in seconds? (3 decimal places)
Answer: s
5. In the RC experiment a 4.7 kΩ resistor charges a capacitor of unknown value from 12 V. You measure 9.81 V at t = 0.08 s after switching on, starting from empty. Estimate the capacitance, in µF.
Answer: µF
6. In the experiment you double the resistance and keep the capacitor. What happens to the time it takes to reach 90 % of the supply?
- It halves
- It stays the same
- It doubles
- It quadruples
Apply it
Design a power-on delay: a chip should start when its enable pin, charged from 3.3 V through a resistor, reaches 2.0 V, between 40 and 60 ms after power-on. Choose R and C from common values, calculate the delay with t = −RC·ln(1 − v/V), then check how far it moves if C is 20 % high or low. Try your values in the RC experiment.
Reflect
You measured τ from a curve instead of trusting the labels on the parts. Where else in engineering is measuring the whole system more trustworthy than adding up the datasheet values?
Week 21: Noise and signals
This week you will
- Explain where sensor noise comes from and how dwell time affects it.
- Read amplitude, frequency and period from a signal and compute a signal-to-noise ratio.
- Combine measurements with inverse-variance weights, and explain why averaging reduces noise but not bias.
Where noise comes from
Run a sorting belt faster and the same colour sensor starts making mistakes. Nothing about the sensor changed. What did?
Why it matters
Noise is not a defect you can order away; it is physics. Engineers trade it against speed, cost and power. The sorting machine makes that trade visible: faster belts mean shorter looks at each part and noisier decisions.
Goals
- Name common sources of sensor noise: thermal, quantisation, interference, vibration and motion.
- Explain how less measurement time per item increases the noise in each reading.
- Tune a threshold and a speed together to meet an accuracy target on unseen data.
Predict
A colour sensor averages light for as long as a part is in view. Doubling belt speed halves that time. Roughly what happens to the noise in each reading?
- It halves
- It rises by about √2 (about 41%)
- It doubles
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the sorting machine at Level 3. Keep the default thresholds and run the belt at three speeds. Note accuracy and parts per minute each time. Then tune the red threshold and size limit to reach 96% at 120 parts per minute or more.
What the interactive shows, in words
In the sorting machine, parts ride past colour sensors, a light gate and a metal detector. At slow belt speeds readings are steady and nearly all parts are sorted correctly; at fast speeds colour readings scatter more and some red parts fall below the red threshold, so accuracy drops below 95% at 1 m/s.
Understand
Physics makes noise
Thermal noise: electrons in every resistor jiggle with heat, so every voltage wobbles a little. Shot noise: light and current arrive as discrete particles, so a dim signal flickers. Quantisation: the converter rounds to its nearest step. These set a floor no software can go below.
The world adds more
Interference: motors, mains wiring and radios couple into sensor wires. Vibration: a shaking mount moves the sensor. Motion: a part passing a sensor is seen for a short time and at a slightly different spot every time. Good wiring, shielding and mounting reduce these at the source, which is always cheaper than filtering later.
Time buys quietness
Many sensors average internally over an exposure or integration time. Longer exposure means more averaging and less noise, at the cost of speed and latency. This is why a camera's photos get grainier in dim light at fast shutter speeds, and why the sorter gets less accurate as the belt speeds up.
Explain it another way: intuitive
Guessing someone's height from a glimpse through a moving train window is harder than from a long look. Less time to look means a noisier guess.
Explain it another way: technical
If a sensor's reading is the mean of N independent samples, its noise scales as 1/√N. With a fixed sample rate, N is proportional to the dwell time t = (sensor window length) ÷ (belt speed), so noise ∝ √speed.
Explain it another way: applied
Industrial vision systems on fast lines often add bright strobed lighting: more light in the same short exposure raises the signal relative to shot noise, instead of slowing the line.
Try these examples
Example 1
A sensor gives noise σ = 3 units at 0.4 m/s. Estimate σ at 1.6 m/s.
The worked solution is in the online lesson.
Common mix-ups
A better sensor has no noise.
✓ Every sensor has noise; better ones have less, often by using more time, more light or more power.Software can always filter noise away.
✓ Filtering trades noise for lag and blurring, and cannot recover information the noise destroyed.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A light sensor's readings jump every time a nearby motor starts. The most likely source is…
- thermal noise
- electrical interference
- quantisation
- bias
2. Noise is 2.0 at 0.5 m/s. If noise scales with √speed, what is it at 2.0 m/s?
Answer:
3. Which is usually the cheapest way to deal with interference?
- A heavy software filter
- Better wiring, shielding and grounding at the source
- A more expensive converter
4. Why does the sorting machine check your settings on two batches you haven't seen?
- To slow you down
- Settings tuned to one batch's noise can fail on new parts; unseen batches test whether they generalise
- Because the first batch is wrong
Apply it
Record accuracy at four belt speeds with your tuned thresholds and plot accuracy against parts per minute. Mark the fastest setting that still meets 96%, and write two sentences on what limits it.
Reflect
If you were paid per part sorted but fined per mistake, how would you choose the belt speed?
Signals: amplitude, frequency, period and SNR
A heartbeat, a wobbling arm and a humming motor all draw wiggly lines. Which three numbers describe each wiggle?
Why it matters
Sensors rarely report a single steady number; they report signals that change. Describing those changes with amplitude and frequency is the language of vibration monitoring, audio, motor control and everything about sampling that comes next week.
Goals
- Read amplitude, frequency, period and phase from a sinusoidal signal and its equation.
- Convert between frequency and period.
- Compute a signal-to-noise ratio and explain what it predicts about detecting a signal.
Predict
A signal repeats every 20 ms. What is its frequency?
- 20 Hz
- 50 Hz
- 200 Hz
Write down your guess and your reason. The reveal is in the online lesson.
Discover
With sampling off, change amplitude and frequency and watch the period marker. Set f = 4 Hz and count the cycles in one second. Then add noise: at what σ does the wave become hard to see with A = 1? Note the SNR at that point.
What the interactive shows, in words
The signal scope draws A·sin(2πft) over one second. With A = 1 and f = 4 Hz there are four full cycles; the green markers show the amplitude and one 250 ms period. Adding noise σ makes the trace fuzzy; at σ = 0.7 the SNR is about 0 dB and the wave is hard to pick out by eye.
Understand
The sine wave
x(t) = A·sin(2πft + φ). Amplitude A is the swing from the middle to a peak (peak-to-peak is 2A). Frequency f is cycles per second, in hertz (Hz). Period T = 1/f is the time for one cycle. Phase φ shifts the wave in time. Most real signals are sums of sine waves at different frequencies.
Frequency tells you the source
A motor at 3000 rpm turns 50 times a second, so it shakes its mount at 50 Hz and its multiples. A walking robot's body bobs at its step rate. Knowing the frequency of the signal you want, and of the noise you don't, is the starting point for choosing a sample rate and a filter.
Signal-to-noise ratio
SNR compares the size of the signal with the size of the noise. Using RMS values (a sine's RMS is A/√2): SNR = RMS signal ÷ RMS noise, often quoted in decibels as 20·log₁₀(that ratio). 20 dB means the signal is 10× the noise; 0 dB means they are equal, and the signal is hard to see in a single look.
Explain it another way: intuitive
Amplitude is how hard a swing goes, frequency is how often it swings, period is how long one swing takes. Noise is someone jostling the swing at random.
Explain it another way: technical
x(t) = A sin(2πft + φ), angular frequency ω = 2πf rad/s. RMS of a sine = A/√2. SNR(dB) = 20 log₁₀(A_rms/σ_noise) = 10 log₁₀(P_signal/P_noise).
Explain it another way: mathematical
Average power of A sin(ωt) over a period: (1/T)∫A² sin²(ωt) dt = A²/2, so RMS = A/√2. For white noise of standard deviation σ, power is σ², giving SNR = A²/(2σ²).
Explain it another way: applied
Condition-monitoring systems on wind turbines and factory motors watch for new frequencies appearing in vibration signals: a bearing defect often shows up as a small peak at a characteristic frequency long before it fails.
Try these examples
Example 1
x(t) = 0.3·sin(2π·25t) V with noise σ = 0.05 V. Find T, peak-to-peak and SNR in dB.
The worked solution is in the online lesson.
Common mix-ups
Amplitude is the distance from the lowest point to the highest.
✓ That is peak-to-peak, which is twice the amplitude.A signal with lower SNR is a weaker signal.
✓ SNR is a ratio: a strong signal with even stronger noise has low SNR.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A vibration has frequency 125 Hz. What is its period, in milliseconds?
Answer: ms
2. A motor spins at 1800 rpm. At what frequency does an unbalance make it vibrate, in Hz?
Answer: Hz
3. For x(t) = 2·sin(2π·5t), which is correct?
- Amplitude 5, frequency 2 Hz
- Amplitude 2, frequency 5 Hz, period 0.2 s
- Amplitude 2, frequency 10π Hz
4. A signal's RMS is 100 times its noise RMS. What is the SNR in decibels?
Answer: dB
5. Two sensors give the same signal; sensor B's SNR is 6 dB higher. What does that mean?
- B's signal is 6 times bigger
- B's noise is about half of A's, relative to the signal
- B samples 6 times faster
Apply it
A robot arm wobbles at 3 Hz with a 2 mm amplitude, and its position sensor has 0.5 mm RMS noise. Compute the SNR in dB, then decide whether a single reading can tell you which way the arm is moving. Justify with numbers.
Reflect
Give an example of a signal in your own surroundings and estimate its frequency.
Combining measurements: averaging, fusion and the module check
A camera says 52 cm ± 4. Odometry says 48 cm ± 2. Is the best answer 50?
Why it matters
Robots almost never trust a single sensor. Blending two imperfect measurements correctly gives an answer better than either, but only if each is weighted by how much it deserves to be trusted. This is the seed of the Kalman filter used in drones, phones and rovers.
Goals
- Combine two independent measurements by weighting each by 1/σ², and compute the combined uncertainty.
- Explain why averaging and fusion reduce random noise but not bias.
- Review weeks 19–21: sensor characteristics, error types, mean, spread and standard error.
Predict
Camera: 52 ± 4 cm. Odometry: 48 ± 2 cm (both ±1σ, independent, unbiased). Where should the best combined estimate be?
- 50 cm, halfway
- Closer to 48 cm, because odometry is more certain
- 52 cm, because cameras are better
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose the Kalman filter. With camera noise 8 cm and odometry noise 2 cm/s, watch the uncertainty band. Then raise odometry bias to 3 cm/s: does the fused line stay honest? Finally set camera dropout to 50% and watch the band widen while the camera is blind.
What the interactive shows, in words
The fusion lab plots a fused position estimate with a ±2σ band. With camera noise 8 cm the camera readings scatter widely, but the Kalman estimate stays close to the truth with a narrow band. During camera dropouts the band widens steadily until the camera returns. With odometry bias 3 cm/s the fused estimate is pulled off the truth during dropouts.
Understand
Inverse-variance weighting
For two independent, unbiased measurements x₁ ± σ₁ and x₂ ± σ₂, the best combination weights each by 1/σ²: x = (x₁/σ₁² + x₂/σ₂²) ÷ (1/σ₁² + 1/σ₂²). Its uncertainty is σ = 1/√(1/σ₁² + 1/σ₂²), always smaller than either input. Averaging n equal readings is the special case that gives σ/√n.
Fusion over time
A Kalman filter does this repeatedly. It predicts where the robot is from its motion (uncertainty grows), then updates with a new measurement, weighting by the gain K = P/(P + R), where P is the prediction's variance and R the measurement's. When the camera drops out, only prediction runs and uncertainty widens.
Bias breaks the promise
Every formula above assumes unbiased, independent errors. A biased sensor pulls the fused answer off while the reported uncertainty stays small: confidently wrong. Fusion helps most when sensors fail in different ways.
Module check: what you should now be able to do
State a sensor's range, resolution and step size; separate accuracy from precision; classify an error as random or systematic; compute a mean, a sample standard deviation and a standard error; plan n for a target SE; and combine two measurements with inverse-variance weights. The practice below mixes all of these.
Explain it another way: intuitive
Asking two friends for directions: you lean towards the one who knows the area better, but you still listen to both. If one always confuses left and right, though, listening more carefully doesn't help.
Explain it another way: technical
Minimum-variance unbiased combination of independent Gaussian measurements: weights wᵢ ∝ 1/σᵢ². Kalman update: K = P/(P + R), x̂ ← x̂ + K(z − x̂), P ← (1 − K)P.
Explain it another way: mathematical
Minimise Var(w x₁ + (1 − w) x₂) = w²σ₁² + (1 − w)²σ₂² over w: the derivative is zero at w = σ₂²/(σ₁² + σ₂²), which is the inverse-variance weight, and the minimum variance is σ₁²σ₂²/(σ₁² + σ₂²).
Explain it another way: applied
Phones fuse GPS (unbiased but noisy and slow) with accelerometers and gyros (smooth but drifting) to give a smooth, steady position on a map.
Try these examples
Example 1
Two thermometers read 20.6 ± 0.3 °C and 21.0 ± 0.6 °C. Combine them.
The worked solution is in the online lesson.
Common mix-ups
The best combination of two readings is always their simple average.
✓ Only when they are equally certain. Otherwise weight each by 1/σ².Adding a worse sensor can only make the estimate worse.
✓ If its errors are independent and unbiased, it always helps a little; if it is biased, it can hurt.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Two independent sensors have σ₁ = 3 cm and σ₂ = 4 cm. What is the uncertainty of their best combination, in cm?
Answer: cm
2. Combine 10.0 ± 1 and 13.0 ± 2 with inverse-variance weights. What is the estimate?
Answer:
3. One reading of a temperature sensor has standard deviation 2 °C. You average n = 36 independent readings. What is the standard error of the mean, in °C?
Answer: °C
4. A sensor's output spans 0 to 10 V and you need steps no bigger than 10 mV. Taking one step as range ÷ 2^n, what is the smallest whole number of bits n that works?
Answer: bits
5. Fusing a biased sensor with an unbiased one gives an estimate that is…
- unbiased, because fusion averages the bias away
- pulled towards the biased sensor, often with an uncertainty that looks too small
- always worse than either sensor alone
6. Review: a sensor reads 0.2 V high every time and also jitters by ±0.05 V. Which statement is right?
- Bias 0.2 V hurts accuracy; jitter 0.05 V hurts precision
- Both hurt only precision
- Averaging will remove both
Apply it
In the fusion lab, find settings where the complementary filter beats Kalman and settings where Kalman clearly wins. Report both with the RMS error the lab shows, and explain the difference in terms of bias and noise.
Reflect
Which idea from weeks 19–21 do you think engineers most often forget, and what goes wrong when they do?
Week 22: Sampling and aliasing
This week you will
- Choose a sample rate from the Nyquist rate with a practical margin.
- Calculate the apparent frequency of an aliased signal and explain the wagon-wheel effect.
- Prevent aliasing with filtering before sampling or decimation.
Sampling and the Nyquist rate
A computer can't watch a signal continuously; it takes snapshots. How many snapshots a second are enough to catch a 50 Hz hum?
Why it matters
Every digital sensor reading is a sample. Choosing how often to sample is a real design decision: too slow and the data lies about what happened; too fast and you waste power, memory and processor time. The Nyquist rate is where that decision starts.
Goals
- Describe sampling as measuring a signal at regular intervals 1/fs apart.
- State the Nyquist rate (2 × the highest frequency) and why sampling must exceed it.
- Choose a practical sample rate with a margin above the Nyquist rate.
Predict
You sample a 10 Hz sine wave at exactly 10 Hz. What do the samples look like?
- A perfect 10 Hz wave
- A constant value: the wave seems to have vanished
- A 20 Hz wave
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Turn on sampling. Set f = 4 Hz and slowly lower fs from 40 Hz. Watch the dashed curve that fits the samples. At what fs does it stop matching the true wave? Repeat for f = 7 Hz. What is the rule?
What the interactive shows, in words
The signal scope samples a sine wave at a chosen rate. For f = 4 Hz, sample rates above 8 Hz give orange dots that follow the wave, and the dashed best-fit curve matches it. Below 8 Hz the dashed curve becomes a slower, different wave: at fs = 6 Hz the samples look like a 2 Hz wave.
Understand
Samples, not signals
A sampler measures the signal every Tₛ = 1/fₛ seconds, where fₛ is the sample rate in hertz. Between samples the computer knows nothing. Any two signals that agree at every sample instant are indistinguishable afterwards, however different they were in between.
The Nyquist rate
To capture a sine wave of frequency f, you need more than two samples per cycle: fₛ > 2f. For a signal whose highest frequency is f_max, the Nyquist rate is 2·f_max. Equivalently, a given fₛ can faithfully represent frequencies only up to fₛ/2, called the Nyquist frequency.
Margins in practice
Exactly 2f is a knife edge: sampled at the wrong phase, a wave right at the limit can vanish. Engineers sample with a comfortable margin, often 5–10 times the highest frequency of interest for control and monitoring, and use an analogue filter to remove anything above fₛ/2 before sampling.
Explain it another way: intuitive
Photographing a spinning fan once per turn makes it look still. Photograph it a few times per turn and you can see which way it spins.
Explain it another way: technical
Sampling x(t) gives x[k] = x(k/fₛ). The Nyquist–Shannon sampling theorem: a signal containing no frequencies at or above fₛ/2 is completely determined by its samples and can be reconstructed exactly in principle.
Explain it another way: mathematical
sin(2πf·k/fₛ) depends only on f/fₛ modulo 1 (and its sign), so frequencies f and f ± m·fₛ give identical samples. Only the band 0 ≤ f < fₛ/2 is unambiguous.
Explain it another way: applied
Audio CDs sample at 44.1 kHz because human hearing reaches about 20 kHz; 2 × 20 kHz = 40 kHz, plus a margin for a practical filter.
Try these examples
Example 1
A wheel encoder produces pulses at up to 300 Hz. What is the Nyquist rate, and what would you choose?
The worked solution is in the online lesson.
Common mix-ups
Sampling at exactly twice the frequency is enough.
✓ You need more than twice; at exactly 2f a wave can vanish if sampled at its zero crossings.Sampling faster always gives better data.
✓ Above a comfortable margin it mostly adds cost, and noise above the band of interest still needs filtering.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. You must capture a wheel encoder whose pulses repeat up to 120 Hz. What is the Nyquist rate (twice the highest frequency) you must sample above, in Hz?
Answer: Hz
2. A data logger samples at 250 Hz. What is the highest frequency it can represent unambiguously (the Nyquist frequency), in Hz?
Answer: Hz
3. A 40 Hz vibration is sampled at 1 kHz. How many samples fall in each cycle?
Answer:
4. A temperature is sampled once a minute. A heater spike lasting 10 seconds happens between samples. What does the log show?
- A short spike
- Nothing at all
- A spike stretched to a minute
5. Why sample well above the Nyquist rate in practice?
- The theorem is wrong
- Real anti-aliasing filters are not perfectly sharp, and more samples per cycle make shapes and timing clearer
- To use more memory
Apply it
A walking robot's leg sensors should capture gait (about 2 Hz) and foot impacts (energy up to 80 Hz). Pick a sample rate, justify it from the Nyquist rate with a margin, and estimate how many bytes per minute you'd log for six 16-bit sensors.
Reflect
Describe something in everyday life that is 'sampled' (photos, register at school, a weekly weigh-in) and what it could miss.
Aliasing: when samples tell lies
In films, car wheels sometimes spin backwards while the car speeds forwards. The camera isn't broken. What is it doing?
Why it matters
Aliasing is not noise you can average away: it is a false signal that looks completely real. A vibration sensor sampled too slowly can report a gentle wobble when the machine is shaking itself apart. Knowing how to predict an alias is how engineers avoid trusting it.
Goals
- Explain aliasing as a high frequency appearing as a lower one after sampling.
- Calculate the apparent (alias) frequency |f − k·fₛ| for a given f and fₛ.
- Explain the wagon-wheel effect and name ways to prevent aliasing.
Predict
A 9 Hz signal is sampled at 10 Hz. What frequency do the samples seem to show?
- 9 Hz
- 1 Hz
- 19 Hz
- 0 Hz
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Set 6 spokes at 24 fps. Find a wheel speed where the wheel seems to stand still, one where it creeps forwards and one where it creeps backwards. Step frame by frame. Then use the readout to predict the next 'stand still' speed before you find it.
What the interactive shows, in words
The wagon-wheel explorer shows six consecutive film frames of a spoked wheel. With 6 spokes at 24 fps: at 4 rev/s every frame looks identical (stand-still); at 3.8 rev/s the spokes step slightly backwards each frame; at 1 rev/s they step forwards by 15 degrees per frame. The readout gives the pattern frequency, the alias and the apparent speed.
Understand
Aliasing in one sentence
When a signal contains frequencies above fₛ/2, sampling folds them down into the range 0 to fₛ/2, where they look exactly like genuine low-frequency signals. After sampling, nothing can tell them apart: the information is gone.
The wagon-wheel effect
A spoked wheel looks identical after turning by one spoke gap. If, between frames, it turns almost exactly one gap, it looks almost still; slightly less than a gap, it seems to creep backwards. Films at 24 fps, strobe lights and LED lighting that flickers at a fixed rate all create this illusion with real machines.
Preventing aliasing
Prevent it before sampling: an analogue anti-aliasing filter removes frequencies above fₛ/2, or you raise fₛ above twice the highest frequency present. A digital filter after sampling is too late: the alias is already mixed into the band you care about.
Explain it another way: intuitive
A clock's second hand photographed once every 59 seconds seems to tick slowly backwards round the dial. The camera saw it at the 'wrong' moments.
Explain it another way: technical
Sampling maps frequency f to the folded frequency f_a = |f − fₛ·round(f/fₛ)| ∈ [0, fₛ/2]. The spectrum of the sampled signal is the original spectrum repeated every fₛ; overlap of these copies is aliasing.
Explain it another way: mathematical
Signed alias a = f − fₛ·round(f/fₛ) ∈ (−fₛ/2, fₛ/2]. For the wheel, apparent rev/s = a(N·r, F)/N. Stand-still happens whenever N·r is a whole multiple of F: r = k·F/N.
Explain it another way: applied
Safety standards for rotating machinery warn about the stroboscopic effect, where flickering lights make a spinning saw blade or lathe chuck appear stationary.
Derivation: Where the alias frequency comes from
Sample x(t) = sin(2πft) at instants t = k/fₛ: the samples are x[k] = sin(2πf·k/fₛ).
Add any whole number m of sample rates to the frequency: sin(2π(f + m·fₛ)·k/fₛ) = sin(2πf·k/fₛ + 2πmk). Since mk is a whole number, the extra 2πmk changes nothing.
So f, f ± fₛ, f ± 2fₛ, … all give identical samples: they are aliases of each other.
Also sin(−θ) = −sin(θ), so a frequency −a gives the same samples as +a with the phase flipped. Frequencies are indistinguishable from their mirror images too.
The sampler shows the alias closest to zero: f_alias = |f − k·fₛ|, where k·fₛ is the whole multiple of fₛ nearest to f. It always lies between 0 and fₛ/2.
Example: f = 23 Hz, fₛ = 10 Hz. The nearest multiple is 20 Hz, so f_alias = |23 − 20| = 3 Hz.
Wagon wheel: N identical spokes at r rev/s make a pattern repeating at N·r Hz. Filmed at F fps, it appears to turn at (signed alias of N·r at F) ÷ N rev/s. A negative alias means it seems to turn backwards.
Try these examples
Example 1
A 130 Hz vibration is sampled at 100 Hz. What frequency appears?
The worked solution is in the online lesson.
Example 2
A 5-spoke wheel turns at 4.6 rev/s, filmed at 24 fps. What do you see?
The worked solution is in the online lesson.
Common mix-ups
Aliasing is a kind of random noise.
✓ It is a deterministic false signal, perfectly repeatable, which is what makes it so convincing.You can remove aliasing with a digital filter afterwards.
✓ Once folded, the alias sits inside the band you want. It must be filtered out before sampling.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A 70 Hz signal is sampled at 50 Hz. What is the alias frequency, in Hz?
Answer: Hz
2. A 46 Hz vibration is sampled at 20 Hz with no anti-aliasing filter. At what frequency does it appear in the samples, in Hz?
Answer: Hz
3. A 55 Hz vibration is sampled at 50 Hz with no anti-aliasing filter. At what frequency does it appear in the samples, in Hz?
Answer: Hz
4. An 8-spoke wheel is filmed at 24 fps. What is the slowest non-zero speed at which it appears perfectly still, in rev/s?
Answer: rev/s
5. Your logged vibration shows a 30 Hz peak you suspect is an alias. What is the most convincing test?
- Average more data
- Change the sample rate: a real 30 Hz stays at 30 Hz, an alias moves
- Apply a digital low-pass filter at 40 Hz
Apply it
A drone's motors spin at 6000 rpm and its flight controller samples the gyro at 1 kHz without an anti-aliasing filter. Compute the motor frequency, check whether it aliases, and predict the false frequency the controller would 'see' if the sample rate dropped to 90 Hz.
Reflect
Why is an alias more dangerous than noise of the same size?
Choosing a sample rate for a real robot
Sampling at 10 kHz is safe but drains the battery. Sampling at 20 Hz is cheap but might lie. How do you pick?
Why it matters
In a real robot, every sensor competes for processor time, bus bandwidth and battery. Good engineers sample each signal just fast enough, with the right filter in front, and can explain the choice to the rest of the team.
Goals
- Choose a sample rate from the signal's highest frequency, the filter available and the system's budget.
- Demonstrate aliasing in code and show that a pre-filter or faster sampling removes it.
- Estimate the data and processing cost of a sampling choice.
Predict
A balance controller must react to tilts that change at up to 5 Hz, but the IMU also picks up motor vibration at 180 Hz. Which plan is safest?
- Sample at 20 Hz: that's above 2 × 5 Hz
- Low-pass filter below 180 Hz, then sample at a few hundred hertz
- Sample at 10 Hz exactly
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, generate one second of a 3 Hz 'tilt' plus a 47 Hz 'vibration'. Sample it at 50 Hz and at 500 Hz and print the dominant frequency you see in each. Then apply a 9-sample moving average to the 500 Hz data before keeping every 10th sample. What happened to the vibration?
What the interactive shows, in words
Code Lab task, described: a 3 Hz tilt plus a 47 Hz vibration sampled at 50 Hz shows a false 3 Hz component from the vibration (|47 − 50| = 3 Hz) on top of the real tilt, so the two are confused. At 500 Hz both frequencies are seen correctly. Averaging 9 samples at 500 Hz before keeping every 10th sample strongly reduces the 47 Hz vibration, leaving the 3 Hz tilt.
Understand
Start from the frequencies
List what the signal contains: the frequencies you want (the tilt, the heartbeat, the wall getting closer) and the ones you don't (motor vibration, mains hum at 50 or 60 Hz, switching noise). The sample rate must exceed twice the highest frequency that reaches the sampler, wanted or not.
Filter, then sample
An analogue low-pass filter in front of the converter cuts unwanted high frequencies so they can't alias. A common digital pattern is oversample, filter, decimate: sample fast, low-pass filter digitally, then keep every Mth sample. The filter must run on the fast samples, before you throw any away.
Count the cost
Data rate = channels × sample rate × bytes per sample. Six 16-bit channels at 1 kHz is 12 kB/s, about 43 MB an hour. Processing cost scales the same way. Control loops also need the delay between sample and action to be small compared with the system's response time.
Explain it another way: intuitive
Before photographing a race with a slow camera, close the curtains on the flashing lights behind it: remove what you can't sample properly, then sample what's left.
Explain it another way: technical
Choose fₛ > 2·f_c, where f_c is the frequency above which the anti-alias filter has attenuated signals below the noise floor. Decimation by M requires first low-pass filtering to below fₛ/(2M).
Explain it another way: mathematical
A k-point moving average has zeros in its frequency response at multiples of fₛ/k, so it strongly attenuates those frequencies. With fₛ = 500 Hz and k = 10 its first zero is at 50 Hz.
Explain it another way: applied
Many flight controllers sample gyros at several kilohertz and filter digitally before running the control loop more slowly, precisely so propeller vibration cannot alias into the attitude estimate.
Try these examples
Example 1
Mains hum at 50 Hz leaks into a sensor sampled at 52 Hz. What appears?
The worked solution is in the online lesson.
Common mix-ups
Choose the sample rate from the signal you want only.
✓ Everything that reaches the sampler counts, including vibration and interference you don't want.Keeping every 10th sample is a harmless way to save memory.
✓ It is sampling at a tenth of the rate and aliases unless you filter first.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A heart-rate sensor's useful content is below 8 Hz, and an anti-alias filter removes everything above 15 Hz. Which sample rate is the sensible minimum?
- 16 Hz
- Just over 30 Hz
- 1 kHz
2. A 46 Hz vibration is sampled at 20 Hz with no anti-aliasing filter. At what frequency does it appear in the samples, in Hz?
Answer: Hz
3. Four 12-bit sensors (stored as 2 bytes each) sampled at 400 Hz. How many bytes per second?
Answer: B/s
4. Mains hum at 50 Hz is sampled at 45 Hz. At what frequency does it appear, in Hz?
Answer: Hz
5. You sample at 1 kHz and want to keep only every 10th sample. When must you low-pass filter?
- After keeping every 10th sample
- Before keeping every 10th sample
- Filtering is not needed
Apply it
Write a one-paragraph sampling plan for a line-following robot with a light sensor array (line edges pass at up to 40 Hz at full speed) and a motor current sensor (PWM ripple at 20 kHz). Give each a sample rate, a filter, and the data rate.
Reflect
Which costs more if you get it wrong: sampling too slowly or too fast? Give an example of each.
Week 23: Introductory digital filtering
This week you will
- Implement a moving-average and an exponential filter.
- Measure the noise–lag trade-off of each, and use a median filter against spikes.
- Explain how filter lag inside a feedback loop affects control.
The moving average and the noise–lag trade-off
Average the last 20 readings and the jitter melts away. So why does the robot now brake late?
Why it matters
The moving average is the first filter almost every engineer writes, and it teaches the deepest rule of filtering: you cannot remove noise for free. Smoother means slower, and for a robot slower can mean a crash.
Goals
- Compute the output of a k-sample moving-average filter.
- Explain that a wider window reduces noise (about √k) but adds lag (about (k − 1)/2 samples).
- Choose a window for a stated noise and response requirement.
Predict
A distance reading steps suddenly from 0 to 1. With a 9-sample moving average, how many samples until the output reaches 1?
- 1 sample
- About 4 samples
- 9 samples
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Use the Step signal and hide the EMA and median. Try windows of 1, 5, 15 and 25. For each, write down the 'noise left' and the 'lag' from the readout. Plot the two numbers against each other in your notes: what shape does the trade-off make?
What the interactive shows, in words
The filter tuner plots 120 noisy samples of a step from 0 to 1 at sample 40. A moving average with k = 1 follows the noise exactly; with k = 5 noise drops by about √5 and the step takes about 5 samples to rise; with k = 25 the line is very smooth but takes about 23 samples to reach 90% of the step.
Understand
How it works
A moving average of window k outputs the mean of the most recent k readings: yₙ = (xₙ + xₙ₋₁ + … + xₙ₋ₖ₊₁) ÷ k. Each new reading pushes the oldest out. It is cheap: keep a running sum, add the new value, subtract the one leaving.
Noise falls like √k
If the noise in each reading is independent with standard deviation σ, averaging k of them leaves about σ/√k. A window of 4 halves the noise; 16 quarters it. Noise that is not independent (a slow drift, a vibration at a steady frequency) is reduced less, or not at all.
Lag grows like k
The output describes the average of the last k samples, centred about (k − 1)/2 samples in the past. After a sudden change it takes k samples to catch up fully. At 100 samples a second, a 21-sample window responds about 0.1 s late, which at 2 m/s is 20 cm.
Explain it another way: intuitive
Judging the weather from the last week's average temperature is steady but slow to notice a sudden cold snap. Judging from today alone is quick but jumpy.
Explain it another way: technical
The moving average is a finite impulse response (FIR) filter with k equal weights 1/k. Its group delay is (k − 1)/2 samples, and for white noise its output variance is σ²/k.
Explain it another way: mathematical
Var(yₙ) = Var((1/k)Σxᵢ) = (1/k²)·k·σ² = σ²/k, so the noise standard deviation is σ/√k. For a unit step, yₙ = min(n + 1, k)/k: a straight ramp lasting k samples.
Explain it another way: applied
Battery monitors often use long moving averages because charge changes slowly and smooth numbers matter more than speed; obstacle sensors use short ones because a late answer is worse than a noisy one.
Try these examples
Example 1
Readings: 12, 15, 11, 18, 14. Window k = 3. What is the latest output?
The worked solution is in the online lesson.
Common mix-ups
A bigger window is always better because it is smoother.
✓ Every extra sample of smoothing is extra delay; the right window depends on how fast the signal really changes.A moving average removes all noise eventually.
✓ It reduces independent noise by √k and leaves slow drifts and bias untouched.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Readings 4, 8, 6, 10. What does a k = 2 moving average output now?
Answer:
2. A filter keeps the mean of the last k = 5 readings. The readings so far, oldest first, are: 35, 16, 15, 35, 38, 10. What does the filter output now?
Answer:
3. A filter keeps the mean of the last k = 5 readings. The readings so far, oldest first, are: 26, 28, 27, 23, 15, 12, 32. What does the filter output now?
Answer:
4. Raw noise is σ = 6 mm. Roughly what noise remains after a 9-sample moving average (independent noise)?
Answer: mm
5. A 21-sample moving average runs at 50 samples per second. Using a delay of (k − 1)/2 samples, how late is its output, in seconds?
Answer: s
6. An obstacle sensor must react within 0.05 s at 100 samples/s. Which window is the largest you could use?
- k = 5
- k = 11
- k = 21
Apply it
Write movingAverage(readings, k) in Python using a running sum (no re-adding the whole window). Test it on a step with noise and measure, in samples, the noise left and the 90% rise time for k = 3, 9 and 27. Compare with the diagram.
Reflect
Where in a robot would you accept lag for smoothness, and where never?
The exponential filter: one number of memory
A filter that remembers just one number can still 'remember' every reading it has ever seen. How?
Why it matters
Microcontrollers with tiny memories filter thousands of sensors with exactly this line of code. It needs no buffer, runs in constant time and has a single knob to tune, which makes it the default smoother in embedded systems.
Goals
- Apply one step of an exponential moving average y ← y + α(x − y).
- Show that the EMA weights past readings by a geometric sequence.
- Relate α to smoothing and lag, and compare the EMA with a moving average.
Predict
y = 20, a new reading of 30 arrives, and α = 0.2. What is the new output?
- 30
- 22
- 26
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Hide the moving average. Sweep α from 1 down to 0.05 on the Step signal and record noise left and lag. Then find the moving-average window k that gives about the same noise as α = 0.2. Which of the two reaches 90% of the step sooner?
What the interactive shows, in words
With the EMA alone on the step signal, α = 1 follows the noise exactly; α = 0.3 smooths it and reaches 90% of the step in about 7 samples; α = 0.05 is very smooth and takes about 45 samples. The EMA reacts immediately to the step and then curves towards the new level, unlike the straight ramp of the moving average.
Understand
One line of code
y = y + alpha * (x - y). The output moves a fraction α of the way towards each new reading. α = 1 copies the input (no filtering); α near 0 barely moves (heavy smoothing). Only one number, y, is stored.
Fading memory
Unrolled, the EMA is a weighted average of all past readings, with weights shrinking by a factor (1 − α) per step. Recent readings matter most; old ones fade but never quite disappear. That gives a smooth response with a quick initial reaction to a change.
Choosing α
Smaller α: less noise, more lag. A rough match to a k-sample moving average is α ≈ 2/(k + 1). If readings arrive every Δt seconds, the filter's time constant is about Δt/α; changes much faster than that are smoothed away.
Start-up and units
Initialise y with the first reading, not zero, or the output will spend many steps climbing from nothing. If the sample rate changes, α must change too to keep the same time constant.
Explain it another way: intuitive
Your opinion of a friend: each new thing they do shifts it a little. Recent behaviour counts most, but last year still leaves a faint trace.
Explain it another way: technical
The EMA is a first-order infinite impulse response (IIR) low-pass filter, the discrete version of an RC circuit, with time constant τ ≈ Δt/α for small α.
Explain it another way: mathematical
yₙ = Σₘ α(1 − α)ᵐ xₙ₋ₘ. Step response 1 − (1 − α)ⁿ⁺¹; white-noise variance ratio α/(2 − α).
Explain it another way: applied
The complementary filter used to estimate a drone's tilt is built from exponential filters: a low-pass on the accelerometer's angle and a high-pass on the integrated gyro.
Derivation: Unrolling the exponential filter
Start from yₙ = yₙ₋₁ + α(xₙ − yₙ₋₁) = αxₙ + (1 − α)yₙ₋₁.
Substitute the same rule for yₙ₋₁: yₙ = αxₙ + (1 − α)[αxₙ₋₁ + (1 − α)yₙ₋₂].
Keep going: yₙ = αxₙ + α(1 − α)xₙ₋₁ + α(1 − α)²xₙ₋₂ + α(1 − α)³xₙ₋₃ + …
Each older reading's weight is (1 − α) times the next newer one's: a geometric sequence. The weights add to α × 1/(1 − (1 − α)) = 1, so the output is a true weighted average.
Old readings never quite vanish, but they fade: after m steps a reading's weight has shrunk by (1 − α)ᵐ. With α = 0.2, after 10 steps it is 0.8¹⁰ ≈ 0.11 of its starting weight.
For a unit step the output after m samples is 1 − (1 − α)ᵐ. It reaches 90% when (1 − α)ᵐ = 0.1, so m = ln(0.1)/ln(1 − α): about 10.3 samples for α = 0.2.
For independent noise σ, the output's noise is σ·√(α/(2 − α)). α = 0.2 gives about 0.33σ, similar to a 9-sample moving average (σ/3). The two are roughly matched when k ≈ 2/α − 1.
Try these examples
Example 1
α = 0.5, y starts at 10. Readings 20, 20, 20. Outputs?
The worked solution is in the online lesson.
Common mix-ups
An EMA forgets readings older than some window.
✓ Every past reading keeps a (shrinking) weight; there is no hard edge.α is a fixed property of the filter regardless of sample rate.
✓ The same α at a faster sample rate gives a shorter time constant; adjust α when you change the rate.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. y = 50, new reading 40, α = 0.1. What is the new output?
Answer:
2. An exponential filter uses y_new = y_old + α·(x − y_old) with α = 0.2. Its last output was 26.5 and the new reading is 21.8. What is the new output?
Answer:
3. An exponential filter uses y_new = y_old + α·(x − y_old) with α = 0.25. Its last output was 20.4 and the new reading is 21.8. What is the new output?
Answer:
4. With α = 0.25, what weight does the reading from 2 steps ago carry in the current output?
Answer:
5. Which α roughly matches the smoothing of a 9-sample moving average?
- α = 0.9
- α = 0.2
- α = 0.02
6. A temperature EMA starts with y = 0 °C, but the room is 21 °C. What happens?
- Nothing: the first reading fixes it
- The output climbs slowly from 0 and reports far too cold for a while
- The filter becomes unstable
Apply it
Write an EMA class with a time constant in seconds (not α) and a sample interval. It should compute α = Δt/(τ + Δt) internally. Show that changing the sample rate from 50 Hz to 200 Hz leaves the step response in seconds roughly unchanged.
Reflect
When would you choose an EMA over a moving average on a small microcontroller, and when the reverse?
Spikes, median filters and filtering inside a controller
One glitch reading of 85 °C in a greenhouse at 18 °C. An average says 24 °C. What does the plant actually feel?
Why it matters
Real sensor logs have spikes: a dropped bit, a loose connector, a reflection. A controller that trusts a spike can switch a heater on for nothing; one that smooths too heavily reacts late to a real problem. This lesson puts filtering inside a working control loop.
Goals
- Use a median filter to reject isolated spikes, and explain why averages cannot.
- Explain how filter lag inside a feedback loop can make control worse.
- Tune a thermostat with noisy readings, comparing smoothing with hysteresis.
Safety: Simulation only. Real greenhouse heaters are mains-powered and must be wired by a qualified person.
Predict
Readings 18.0, 18.1, 85.0, 18.2, 17.9. What does a 5-sample median give?
- 31.4
- 18.1
- 85.0
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the smart greenhouse at Level 3. First run the night with the default thermostat and count the switches. Then try heavy smoothing with a narrow gap, and finally no smoothing with a 1.5–2 °C gap. Which actually solves the chattering, and what does heavy smoothing do during the open-vent dip?
What the interactive shows, in words
In the greenhouse simulator, the default thermostat switches 348 times in a night because noisy readings cross its narrow thresholds repeatedly. Heavy smoothing reduces the switching but delays the reaction to the open vent, letting the temperature dip below 16 °C. A gap of about 1.5–2 °C (for example on below 16.5, off above 18.5, no smoothing) keeps the plants in range with about 62 switches.
Understand
The median ignores outliers
A median filter outputs the middle value of the last k readings. A spike shorter than half the window lands at one end of the sorted list and is ignored, while real steps still pass through (after a delay of about half the window). Averages, by contrast, spread a spike's error over the whole window.
Filters live inside loops
In a feedback loop the controller acts on the filtered reading. Lag in the filter means the controller sees the world late: it keeps heating after the target is reached and overshoots. A filter that looks perfect on a recorded log can make a live loop oscillate.
Smoothing versus hysteresis
An on/off thermostat near its setpoint chatters as noise crosses the threshold back and forth. Heavy smoothing reduces chatter but adds lag. Hysteresis (switch on below one temperature, off above a higher one) stops chatter without lag, because noise smaller than the gap cannot cross both thresholds.
Explain it another way: intuitive
Asking five people the time and taking the middle answer ignores the one whose watch is broken. Averaging all five lets the broken watch drag the answer.
Explain it another way: technical
The median filter is non-linear: it preserves edges and rejects impulses up to ⌊k/2⌋ samples long. Filter group delay adds directly to the loop's dead time, which reduces the gain margin of a feedback controller.
Explain it another way: applied
Ultrasonic range sensors occasionally return a wildly wrong echo; robot code commonly runs a 3- or 5-sample median before any averaging so one bad echo can't trigger an emergency stop or hide a real obstacle.
Try these examples
Example 1
A 3-sample median over readings 5, 5, 40, 6, 6. Outputs from the third reading onward?
The worked solution is in the online lesson.
Common mix-ups
Every filter is a kind of average.
✓ The median is not an average; it is a ranking, which is why it can ignore outliers that averages can't.If a filter makes the plot look nicer, the controller will work better.
✓ Inside a loop, lag can make control worse even when the trace looks smoother.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. What is the median of 12, 97, 11, 13, 12?
Answer:
2. For the same readings 12, 97, 11, 13, 12, what is the mean?
Answer:
3. A 5-sample median filter faces a glitch that lasts 4 samples. What happens?
- It is removed completely
- It gets through, because it fills most of the window
- The filter crashes
4. Adding a heavy filter to a heater's temperature reading most likely causes…
- faster warm-up
- more overshoot, because the controller sees changes late
- lower energy use, always
5. An exponential filter uses y_new = y_old + α·(x − y_old) with α = 0.5. Its last output was 19 and the new reading is 11.7. What is the new output?
Answer:
Apply it
Finish Level 3 of the greenhouse: no more than 10 minutes outside 16–24 °C and at most 80 switches all night. Record your on/off temperatures and smoothing, the switch count and the energy, then explain in two sentences why the gap beats smoothing here.
Reflect
When would you put a median filter before an average, and why in that order?
Week 24: Image representation
This week you will
- Represent a greyscale and a colour image as arrays of numbers and size them in bytes.
- Segment an image by thresholding and choose a threshold from a histogram.
- Explain why HSV often beats raw RGB for colour thresholds.
Images are arrays of numbers
To a robot, your face is a grid of about two million numbers. Which number is your nose?
Why it matters
Every vision algorithm, from a barcode reader to a self-driving car, starts by treating a picture as a table of numbers. Once you see it that way, image processing becomes arithmetic on arrays: the same skills you used on sensor logs.
Goals
- Represent a greyscale image as a 2D array of brightness values and a colour image as three channels.
- Index a pixel by row and column and compute an image's memory size.
- Connect pixel values to sensor sampling and quantisation.
Predict
How many bytes does one uncompressed 640 × 480 colour image take with 8 bits per channel?
- About 300 kB
- About 920 kB
- About 7 MB
Write down your guess and your reason. The reveal is in the online lesson.
Discover
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.
What the interactive shows, in words
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.
Understand
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.
Explain it another way: intuitive
An image is like a mosaic of tiny tiles, each painted one shade from black to white. Write the shade number on every tile and you have what the computer sees.
Explain it another way: technical
A W × H image with C channels of b bits is a W·H·C array of integers in [0, 2ᵇ − 1]. Libraries such as NumPy index it img[y, x, c] with y down the rows.
Explain it another way: mathematical
Pixel pitch p and lens focal length f set the angle each pixel sees: about p/f radians. A 3 µm pixel behind a 4 mm lens sees about 0.75 mrad, or 0.75 mm at 1 m.
Explain it another way: applied
Industrial inspection cameras are often monochrome because a single channel at higher resolution, with controlled lighting, measures edges more precisely than colour would.
Try these examples
Example 1
A greyscale camera is 1280 × 720 at 8 bits, 60 fps. What is the raw data rate?
The worked solution is in the online lesson.
Common mix-ups
A camera records what the eye sees.
✓ It records numbers: sampled, quantised, noisy and clipped, through a lens and a colour filter. Vision algorithms see only those numbers.Coordinates in images work like maths graphs, with y going up.
✓ Image rows usually count down from the top; mixing the conventions flips results.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. How many bytes is a 100 × 80 greyscale image at 8 bits per pixel?
Answer: bytes
2. How many bytes is a 320 × 240 RGB image at 8 bits per channel?
Answer: bytes
3. In img[row][col] with row 0 at the top, which pixel is img[2][5]?
- Third row from the top, sixth column from the left
- Second row from the bottom, fifth column
- Fifth row, third column
4. A bright window shows as a block of pixels all exactly 255. What does that tell you?
- The window is exactly at brightness 255
- Those pixels are saturated: the true brightness is at least that high and detail is lost
- The camera is broken
5. A 16-bit converter spans 0 to 5 V. Taking one step as range ÷ 2^n, how big is one step, in millivolts?
Answer: mV
Apply it
Load a small greyscale photo in Python as a 2D list or array. Print its size, the brightest and darkest values and their positions, then crop the central quarter and save its mean brightness. Explain in one sentence what that mean would tell a robot.
Reflect
Which of the sensor ideas from weeks 19–23 do you think matters most for cameras, and why?
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?
Why it matters
Thresholding is the simplest decision a vision system makes, and it is everywhere: line-following robots, barcode readers, bottle-fill checks. It is also where you first meet the core trade-off of every classifier: wherever you draw the line, some pixels land on the wrong side.
Goals
- Segment an image into a binary mask with a brightness threshold.
- Choose a threshold from a histogram of pixel values.
- Explain why noise and uneven lighting break a single global threshold.
Predict
An object is about 200 bright on a background of about 40, both with noise ±45. Which threshold separates them best?
- T = 60
- T = 120
- T = 230
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose Threshold. On the Bright square, sweep T from 0 to 255 and note the range that gives a perfect mask. Switch to the Noisy bar: is there still a perfect threshold? Count the mistakes at T = 100, 120 and 140.
What the interactive shows, in words
In threshold mode the right-hand grid shows the mask: 255 for pixels at or above T, 0 below. For the Bright square any T from 45 to 200 gives a perfect 4 × 4 block. For the Noisy bar, background pixels (around 60 ± 45) and bar pixels (around 170 ± 45) overlap, so every threshold misclassifies a few pixels; values near 115 make the fewest mistakes.
Understand
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.
Explain it another way: intuitive
Sorting a pile of grey pebbles into 'light' and 'dark': most are easy, but the in-between ones depend exactly where you draw the line, and in dim light everything looks darker.
Explain it another way: technical
Global thresholding is pixel-wise classification on intensity. Otsu's method maximises the between-class variance of the histogram split; adaptive thresholding compares each pixel with a local mean minus a constant.
Explain it another way: applied
Line-following robots threshold an infrared reflectance reading; they still need recalibrating when moved from a bright classroom to a dim hall, because ambient light shifts both humps.
Try these examples
Example 1
Background pixels range 30–90; object pixels range 150–220. Suggest T and justify.
The worked solution is in the online lesson.
Common mix-ups
There is always a perfect threshold if you search hard enough.
✓ When the value ranges of object and background overlap, every threshold makes some mistakes; you can only choose which ones.Thresholds tuned on one image work everywhere.
✓ Lighting, camera settings and surfaces change; test thresholds on images you didn't tune on.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. With T = 128, what does a pixel of value 128 become?
- Object (1)
- Background (0)
- Undefined
2. A 4-pixel row has values 30, 140, 200, 90. With T = 100, how many pixels are object?
Answer:
3. Parts on the left of a conveyor are lit twice as brightly as on the right. A single threshold…
- works fine if chosen carefully
- will tend to miss dark-side parts or over-detect bright-side background
- becomes more accurate
4. A pixel histogram has humps centred at 50 and 180, with very few pixels between 100 and 130. Where should T go?
- At 50
- In the valley, around 115
- At 180
Apply it
In Python, threshold a greyscale image of coins or pieces of paper on a dark table at three values. For each, count the object pixels and describe the mistakes. Then write a function that picks T as the midpoint between the two most common brightness levels and compare it with your best manual choice.
Reflect
Think of a situation where it would be better to wrongly mark background as object than the reverse.
Colour spaces, HSV and the module check
A red ball in sunlight and the same ball in shadow have very different RGB values. How can a robot say 'red' for both?
Why it matters
Colour is one of the fastest cues a robot has: red parts, green lights, a yellow ball. But brightness changes every channel at once. Separating 'what colour' from 'how bright' makes colour thresholds survive a passing cloud.
Goals
- Explain why raw RGB values change with lighting and why hue is more stable.
- Convert simple RGB colours to hue, saturation and value, and threshold on hue.
- Review weeks 22–24: sampling, aliasing, filtering, images and thresholds.
Predict
A red part reads RGB (200, 40, 40) in light and (100, 20, 20) in shade. What stays the same?
- The red value
- The ratios between channels, so the hue
- Nothing
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, use Python's colorsys.rgb_to_hsv on the two red readings from the prediction, plus a dim orange (120, 60, 0) and a grey (90, 90, 90). Print hue in degrees, saturation and value for each. Then write is_red(r, g, b) that works for both reds and rejects the others.
What the interactive shows, in words
Code Lab task, described: RGB (200, 40, 40) and (100, 20, 20) both have hue 0° and saturation 0.8, with value 0.78 and 0.39. Orange (120, 60, 0) has hue 30°; grey (90, 90, 90) has saturation 0, so its hue is undefined. A rule 'hue under 15° or over 345°, saturation above 0.4, value above 0.15' accepts both reds and rejects the others.
Understand
Why RGB is fragile
Each RGB channel measures how much light of one colour reaches the pixel, so dimming the light scales all three together. A rule like 'red if R > 150' fails in shadow. Ratios between channels survive dimming far better than the raw values do.
Hue, saturation, value
HSV re-describes a colour as hue (which colour, an angle round a colour wheel: red near 0°, green 120°, blue 240°), saturation (how vivid versus grey) and value (how bright: the largest of R, G, B). A colour threshold on hue, with a minimum saturation, ignores most brightness changes.
Its weak spots
Hue wraps around: red sits at both 0° and 360°, so 'red' is hue < 15° or > 345°. For greys and very dark pixels saturation is near zero and hue is meaningless noise, so always require a minimum saturation and value. Coloured lighting still shifts hue.
Module check: weeks 22–24
You should be able to: state the Nyquist rate and compute an alias; choose a sample rate with a filter in front; compute moving-average, EMA and median outputs and explain the noise–lag trade-off; size an image in bytes; and choose and defend a threshold. The practice mixes them.
Explain it another way: intuitive
A red jumper is still red in a dim room: your brain judges colour from the mix, not the brightness. HSV lets a computer do something similar.
Explain it another way: technical
V = max(R, G, B), S = (V − min)/V, and hue is computed from which channel is largest and the differences between the others, giving an angle in [0°, 360°).
Explain it another way: mathematical
Scaling (R, G, B) by any k > 0 leaves H and S unchanged and multiplies V by k, which is exactly why hue thresholds are robust to uniform dimming.
Explain it another way: applied
The sorting machine's colour sensors are simplified 'how red' readings; real recycling sorters often use hue-like features or even near-infrared spectra to tell plastics apart.
Try these examples
Example 1
Find H, S and V for RGB (200, 40, 40) on a 0–255 scale.
The worked solution is in the online lesson.
Common mix-ups
HSV makes colour detection immune to lighting.
✓ It handles brightness changes well, but coloured light, shadows from coloured objects and camera white balance still shift hue.Hue thresholds work on any pixel.
✓ Hue is only meaningful when saturation and value are high enough.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. On a 0–255 scale, what is the value V (as a number 0–255) of RGB (60, 180, 90)?
Answer:
2. What is the saturation S of RGB (60, 180, 90), as a decimal?
Answer:
3. Which rule correctly selects reds using hue in degrees?
- hue < 15
- hue > 345
- hue < 15 or hue > 345
- hue between 15 and 345
4. A 62.5 Hz vibration is sampled at 50 Hz with no anti-aliasing filter. At what frequency does it appear in the samples, in Hz?
Answer: Hz
5. A filter keeps the mean of the last k = 3 readings. The readings so far, oldest first, are: 23, 11, 29, 27, 24, 24, 15, 13. What does the filter output now?
Answer:
6. Why require a minimum saturation in a hue-based colour detector?
- To make it faster
- Grey and very dark pixels have almost no saturation, so their hue is meaningless and noisy
- Saturation is always zero for red
Apply it
Extend is_red to a function that returns a mask for a whole image (as nested lists). Test it on a picture of something red taken in bright light and in shade. Report the share of object pixels detected in each and the settings you chose.
Reflect
Of weeks 22–24, which idea surprised you most, and where could it catch out a robot you might build?
Week 25: Computer vision fundamentals
This week you will
- Apply convolution kernels for blurring, sharpening and edge detection.
- Find and measure objects with connected-component labelling.
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?
Why it matters
Kernels are the workhorse of image processing and the building block of the convolutional neural networks behind modern vision. Once you can apply one by hand, blurs, sharpening and edge detection stop being magic buttons.
Goals
- Apply a 3×3 kernel to a pixel neighbourhood by multiplying matching positions and adding.
- Explain the box blur as a 2D moving average, and what sharpening kernels do.
- Handle image edges and value ranges sensibly.
Predict
A box blur (nine weights of 1/9) is applied to a single bright pixel of 90 surrounded by zeros. What is the output at that pixel?
- 90
- 10
- 0
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose Kernel. On the Noisy bar, compare Identity with Box blur: click a pixel and check the readout's sum by hand. Then try Sharpen on the Bright square. What happens at the square's edges, and why can values go above 255 or below 0?
What the interactive shows, in words
In kernel mode the diagram shows the input grid and the filtered grid. Clicking a pixel lists the nine weight × value products and their sum. On the Noisy bar, the box blur evens out the random variation and spreads the bright bright speck into a dimmer 3 × 3 patch; sharpening the Bright square makes its edge pixels brighter and the surrounding background darker.
Understand
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.
Explain it another way: intuitive
Each pixel asks its eight neighbours for their opinion and blends them with its own, using the kernel as the voting rules.
Explain it another way: technical
2D discrete correlation g(x, y) = Σᵢⱼ k(i, j)·f(x + i, y + j); convolution uses k(−i, −j). Cost is 9 multiply-adds per pixel for 3×3; separable kernels like the box and Gaussian can be done as a row pass then a column pass.
Explain it another way: mathematical
A kernel whose weights sum to s scales flat regions by s. The box blur reduces the variance of independent noise by Σk² = 9 × (1/9)² = 1/9.
Explain it another way: applied
Convolutional neural networks learn their own kernel weights from data; the first layer of a trained network often ends up containing kernels that look like blurs and edge detectors.
Derivation: Applying a kernel to one pixel
Take the 3×3 neighbourhood centred on the pixel, values p(i, j) for i, j ∈ {−1, 0, 1}.
Take the kernel weights k(i, j) in the same layout.
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.)
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.
Example patch rows [10, 20, 30] [40, 50, 60] [70, 80, 90] with a box blur: sum = 450, output = 450 ÷ 9 = 50.
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.
Weights summing to 1 keep average brightness; weights summing to 0 (edge kernels) give 0 on flat regions.
Try these examples
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].
The worked solution is in the online lesson.
Common mix-ups
Blurring removes noise without losing anything.
✓ It averages noise down and also smears real edges; it is the image version of the noise–lag trade-off.Kernel outputs always stay between 0 and 255.
✓ Kernels with negative weights or sums above 1 can go outside the range; keep the true values and clip only for display.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Box blur (all weights 1/9) on a patch whose nine values add to 1080. What is the output?
Answer:
2. Apply the box blur (all nine weights 1/9) kernel to the centre pixel of this 3×3 patch by multiplying matching positions and adding. Patch rows: [210, 50, 40] [210, 230, 0] [250, 10, 70]. What is the output value?
Answer:
3. Apply the sharpen [[0,−1,0],[−1,5,−1],[0,−1,0]] kernel to the centre pixel of this 3×3 patch by multiplying matching positions and adding. Patch rows: [130, 150, 140] [110, 40, 10] [180, 250, 170]. What is the output value?
Answer:
4. A kernel's weights add up to 2. Applied to a flat grey region of 100, what does it output?
- 100
- 200
- 0
5. Why write filter results into a new image rather than overwriting the input as you go?
- It is faster
- Later pixels would use already-filtered neighbours, giving the wrong result
- Images can't be modified
Apply it
Write apply_kernel(img, k) in Python with nested loops and nearest-pixel edges. Test it against two hand-worked patches, then blur a noisy test image and measure how much the standard deviation of a flat region falls.
Reflect
How is a box blur like a moving average, and how is it different?
Edge detection with Sobel
Outlines are where brightness changes fastest. How do you measure 'change' in a grid of numbers?
Why it matters
Edges outline objects, mark lane lines and show where a part ends. Edge detectors are some of the oldest and most reliable tools in robot vision, and they are a direct use of a derivative on sampled data.
Goals
- Explain an edge as a large brightness gradient and how Sobel kernels estimate it.
- Combine x and y responses into a gradient magnitude.
- Explain why blurring before edge detection helps with noise.
Predict
Sobel x is applied to a perfectly flat grey region. What is the output?
- 0
- 255
- The grey value
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose Kernel then Sobel x on the Bright square: which edges light up? Switch to Sobel y. Then try both on the Gradient and on the Noisy bar. Click a pixel on an edge and one inside the square and compare the sums.
What the interactive shows, in words
With Sobel x on the Bright square, the output is large at the square's left and right sides (positive on the left edge, where brightness rises to the right, and negative on the right edge) and 0 inside and outside. Sobel y responds to the top and bottom edges instead. On the Gradient, Sobel x gives a constant 240 (8 × the slope of 30 per column) except at the borders.
Understand
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.
Explain it another way: intuitive
Run your finger across a page in the dark: edges are where the height suddenly changes. Sobel feels for sudden brightness changes.
Explain it another way: technical
Sobel = (smoothing [1, 2, 1]ᵀ) ⊗ (central difference [−1, 0, 1]). Gradient magnitude |∇I| ≈ √(Gx² + Gy²); the Canny detector adds blur, thinning and two-level thresholding on top.
Explain it another way: mathematical
For a linear ramp I(x) = a·x, Sobel x gives (1 + 2 + 1) × (a·(x + 1) − a·(x − 1)) = 8a: proportional to the slope a.
Explain it another way: applied
Lane-keeping assistants have used edge detection on road images to find painted lines; rain, glare and worn paint are exactly the noise and contrast problems this lesson describes.
Try these examples
Example 1
At a pixel, Gx = 120 and Gy = −50. Find the edge strength.
The worked solution is in the online lesson.
Common mix-ups
Edge detectors find objects.
✓ They find brightness changes: shadows, reflections and texture produce edges too. Deciding which edges belong to objects is a later step.A negative Sobel value means no edge.
✓ The sign gives the direction of the change; the size gives its strength.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Gx = 30 and Gy = 40 at a pixel. What is the gradient magnitude?
Answer:
2. Apply the box blur (all nine weights 1/9) kernel to the centre pixel of this 3×3 patch by multiplying matching positions and adding. Patch rows: [210, 50, 40] [210, 230, 0] [250, 10, 70]. What is the output value?
Answer:
3. Sobel x on a ramp that rises by 10 per column (each row the same). What is the output?
Answer:
4. Sobel y responds strongly but Sobel x is near zero. The edge is…
- vertical
- horizontal
- diagonal
5. Edge detection on a noisy image finds edges everywhere. What should you try first?
- Lower the edge threshold
- Blur the image slightly before detecting edges
- Use a bigger image
Apply it
Run Sobel x and y on a photo of a doorway, compute the magnitude, threshold it at three values and report how many edge pixels each leaves. Repeat after a 3×3 blur and explain the difference.
Reflect
Where in a real scene would strong edges appear that do not belong to any object?
Finding and measuring objects
A mask says which pixels are 'part'. But how many parts are there, and how big is each one?
Why it matters
Counting parts on a tray, measuring a seedling, finding where to grip: all of these turn a mask into a list of objects with sizes and positions. It is the step where pixels become things a robot can act on.
Goals
- Group mask pixels into objects with connected-component labelling (flood fill).
- Measure each object's area, centroid and bounding box.
- Explain how 4- versus 8-connectivity and noise change the count.
Predict
Two square blobs touch only at one corner. With 4-connectivity (up, down, left, right), how many objects are there?
- 1
- 2
- It depends on the threshold
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, write label(mask) that scans a 2D list of 0s and 1s and floods each unvisited 1 with a queue (breadth-first), giving each blob a new label. Return, for each blob, its pixel count and centroid. Test on a mask with two blobs that touch at a corner, using both 4- and 8-connectivity.
What the interactive shows, in words
Code Lab task, described: a mask containing two 2 × 2 squares that touch only at one corner gives 2 objects with 4-connectivity (each of area 4) and 1 object of area 8 with 8-connectivity. Each blob's centroid is the mean row and column of its pixels.
Understand
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.
Explain it another way: intuitive
Pour paint onto one pixel of a blob and let it spread into every touching object pixel: everything that gets painted is one object.
Explain it another way: technical
Connected-component labelling via BFS/DFS flood fill runs in O(W·H). Two-pass union–find algorithms do the same with better memory locality. Moments (area, centroid, second moments) summarise shape.
Explain it another way: mathematical
Centroid (r̄, c̄) = (Σr/A, Σc/A) over the blob's pixels. Converting area to real units multiplies by (mm per pixel)², so a 2× error in scale is a 4× error in area.
Explain it another way: applied
Seed-sorting and pill-counting machines count blobs on a conveyor camera and reject anything whose area is outside the expected range, catching broken or doubled items.
Try these examples
Example 1
A blob's pixels are at (row, col) (1,1), (1,2), (2,1), (2,2), (3,2). Area and centroid?
The worked solution is in the online lesson.
Common mix-ups
Number of blobs = number of objects.
✓ Noise adds specks, touching objects merge, and shadows split objects. Counts must be checked against ground truth.The centroid is always inside the object.
✓ For a C or ring shape the centroid lies in the gap, which matters if a gripper aims for it.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A blob covers 340 pixels and each pixel is 0.5 mm × 0.5 mm. What is its area, in mm²?
Answer: mm²
2. A blob has pixels in columns 4, 5, 5, 6, 10. What is its centroid column?
Answer:
3. A tray of 12 parts is counted as 19. Seven of the extra 'objects' are 1–3 pixels big. Best fix?
- Lower the threshold
- Ignore blobs below a minimum area chosen from real part sizes
- Use 8-connectivity
4. Two touching coins are counted as one object. Which statement is true?
- Switching to 4-connectivity always fixes it
- Labelling cannot separate objects that genuinely touch in the mask; you need another cue such as shape, size or edges
- Raise the minimum area
5. A defect detector is tested on labelled parts: TP = 77, FP = 18, FN = 1, TN = 272. What is its recall, as a percentage?
Answer: %
Apply it
Combine this week's functions into a pipeline: threshold → remove blobs under a minimum area → label → measure. Run it on three images of small objects, hand-count each, and report the counted versus true number of objects.
Reflect
Where would a robot's gripper go wrong if it trusted centroids without checking shape?
Week 26: Decision-making under uncertainty
This week you will
- Express a detector's reliability as a confusion matrix, precision and recall.
- Apply Bayes' rule with a base rate, from a frequency table.
- Choose an action and a decision threshold by expected cost.
Confusion matrices, precision and recall
A defect detector is '95% accurate'. It might still miss every faulty part. How?
Why it matters
Every perception system that makes yes/no decisions makes two kinds of mistake. Engineers must report both, because the cost of a false alarm and the cost of a miss are rarely the same: a scrapped good part versus a faulty brake reaching a customer.
Goals
- Build a confusion matrix (TP, FP, FN, TN) from labelled test results.
- Compute precision and recall and explain what each protects against.
- Choose a decision threshold by weighing false positives against false negatives.
Predict
5 in 100 parts are faulty. A detector says 'good' to every part. What is its accuracy?
- 5%
- 50%
- 95%
Write down your guess and your reason. The reveal is in the online lesson.
Discover
On the tuning batch, slide the threshold from 0 to 100 and watch the four boxes. Find a threshold with recall at least 90%, then one with precision at least 90%. Can you get both at once? Write down the threshold you'd pick for a brake-part line and for a cheap plastic clip.
What the interactive shows, in words
Sixty parts are drawn on a score strip: faulty parts as triangles that tend to score high, good parts as circles that tend to score low, with overlap in the middle. A threshold line splits them into flagged and passed. The table shows TP, FN, FP and TN; at a threshold of 50 on the tuning batch most faulty parts are flagged and a handful of good parts are wrongly flagged.
Understand
Four outcomes
With 'faulty' as the positive class: TP faulty and flagged; FN faulty but passed (a miss); FP good but flagged (a false alarm); TN good and passed. The confusion matrix lays these out as a 2×2 table of counts, rows for the truth and columns for the decision.
Precision and recall
Precision = TP ÷ (TP + FP): when it says faulty, how often is it right? Low precision wastes good parts. Recall = TP ÷ (TP + FN): of the faulty parts, how many does it catch? Low recall lets faults through. Accuracy = (TP + TN) ÷ total, which is dominated by the common class.
The threshold trade-off
Lowering the threshold flags more parts: recall rises and precision usually falls. Raising it does the opposite. Where to set it is not a maths question but an engineering one: what does each kind of mistake cost? Next lessons put numbers on that.
Explain it another way: intuitive
A smoke alarm that goes off for toast has poor precision; one that stays quiet in a real fire has poor recall. You would rather have the toast problem.
Explain it another way: technical
Recall is also called sensitivity or the true-positive rate; the false-positive rate is FP/(FP + TN). Sweeping the threshold traces a precision–recall curve or an ROC curve, summarising performance across all thresholds.
Explain it another way: mathematical
F1 = 2PR/(P + R), the harmonic mean of precision and recall, is one way to combine them, but it silently assumes both mistakes cost the same.
Explain it another way: applied
Medical screening tests are tuned for high recall (miss few cases) and followed by a second, more precise test, because a missed illness costs far more than an extra check.
Try these examples
Example 1
TP = 40, FP = 10, FN = 20, TN = 930. Find precision, recall and accuracy.
The worked solution is in the online lesson.
Common mix-ups
High accuracy means a good detector.
✓ When positives are rare, a detector can be highly accurate and still miss most of them. Report precision and recall.There is one correct threshold.
✓ The best threshold depends on the costs of each mistake, which depend on the application.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A detector flags 25 parts, of which 20 are really faulty. What is its precision, as a percentage?
Answer: %
2. A defect detector is tested on labelled parts: TP = 23, FP = 33, FN = 8, TN = 108. What is its recall, as a percentage?
Answer: %
3. A defect detector is tested on labelled parts: TP = 37, FP = 21, FN = 24, TN = 251. What is its precision, as a percentage?
Answer: %
4. You lower the detection threshold. What usually happens?
- Recall rises, precision falls
- Precision rises, recall falls
- Both rise
5. For an airport bag scanner, which matters most?
- Precision
- Recall
- Accuracy
Apply it
Using the tuning batch, list the confusion matrix at thresholds 40, 50, 60 and 70. Pick one for a line where a missed fault costs ten times as much as a scrapped good part, and justify it with the counts. Then check it on the fresh test batch.
Reflect
Describe a detector in everyday life where you would accept many false alarms, and one where you wouldn't.
Conditional probability, Bayes and base rates
A detector catches 90% of faults and false-alarms only 5% of the time. A part is flagged. Is it probably faulty?
Why it matters
Perception systems turn evidence into beliefs: 'a pedestrian is probably there', 'this part is probably faulty'. Bayes' rule is the arithmetic of doing that honestly, and forgetting the base rate is one of the most common reasoning errors made by people and machines alike.
Goals
- Use event notation and compute conditional probabilities from a frequency table.
- Derive Bayes' rule from counts and apply it with a base rate.
- Explain why a rare condition makes even a good detector's alarms mostly false.
Predict
1% of parts are faulty. The detector flags 90% of faulty parts and 5% of good ones. A part is flagged. Roughly how likely is it to be faulty?
- About 90%
- About 50%
- About 15%
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start at base rate 1%, sensitivity 90%, false positives 5%. Read the counts in each branch and check the answer by hand. Then raise the base rate to 20%. Then go back to 1% and halve the false-positive rate. Which change helps the flags most? Finally, try 'tested a second time'.
What the interactive shows, in words
The base-rate tree splits 10,000 parts by base rate into faulty and good, then each into flagged and not flagged. At base rate 1%, sensitivity 90% and false positives 5%: 100 faulty (90 flagged, 10 missed) and 9,900 good (495 flagged, 9,405 passed). P(faulty | flagged) = 90 ÷ 585 ≈ 15.4%. A second independent flag raises it to about 77%.
Understand
Events and conditions
An event is something that does or doesn't happen: 'faulty', 'flagged'. P(F) is its probability over all parts. A conditional probability P(F | +) restricts attention to the cases where + happened. Reading '|' as 'among those that' keeps it straight: the share faulty among those that were flagged.
Count, don't juggle formulas
The safest way to apply Bayes' rule is a frequency tree: pick a population (10,000 is convenient), split it by the base rate, then split each branch by the detector's rates, and finally compare the branches that match the evidence. The formula and the counts give the same answer; the counts are harder to get wrong.
Base rates rule
When the condition is rare, false alarms from the huge 'good' group can outnumber real detections from the tiny 'faulty' group. Two remedies: reduce the false-positive rate, or confirm a flag with a second, independent check, using the first answer as the new base rate. Independence is an assumption: two sensors fooled by the same glare are not independent.
Explain it another way: intuitive
If you hear hoofbeats in a British town, think horses, not zebras: even if a sound is 'zebra-like', zebras are so rare there that horses are still the better bet.
Explain it another way: technical
P(F | +) = P(+ | F)P(F) / [P(+ | F)P(F) + P(+ | ¬F)P(¬F)]. In odds form: posterior odds = prior odds × likelihood ratio, where the likelihood ratio is P(+ | F)/P(+ | ¬F) = 0.9/0.05 = 18 for this detector.
Explain it another way: mathematical
Prior odds 1:99, times 18, gives 18:99 ≈ 0.18, a probability of 18/117 ≈ 15.4%. A second independent flag multiplies again: 324:99, about 77%.
Explain it another way: applied
Sensor fusion and robot localisation are repeated Bayesian updates: each new reading multiplies the robot's belief about where it is, then motion spreads that belief out again.
Derivation: Bayes' rule from a frequency table
Events: F = 'part is faulty', + = 'detector flags it'. P(A | B) means 'the probability of A among the cases where B happened'.
Imagine N parts. Faulty: N·P(F). Of those, flagged: N·P(F)·P(+ | F).
Good: N·(1 − P(F)). Of those, flagged: N·(1 − P(F))·P(+ | not F).
Among all flagged parts, the share that are faulty is P(F | +) = N·P(F)·P(+ | F) ÷ [N·P(F)·P(+ | F) + N·(1 − P(F))·P(+ | not F)].
N cancels. The denominator is P(+), the overall chance of a flag. So P(F | +) = P(+ | F)·P(F) ÷ P(+): Bayes' rule.
Numbers: P(F) = 0.01, P(+ | F) = 0.9, P(+ | not F) = 0.05: P(F | +) = 0.009 ÷ (0.009 + 0.0495) = 0.009 ÷ 0.0585 ≈ 0.154.
P(F | +) and P(+ | F) are different questions: 15% versus 90%. Confusing them is called the base-rate fallacy.
Try these examples
Example 1
Base rate 10%, sensitivity 80%, false positives 10%. P(faulty | flagged)?
The worked solution is in the online lesson.
Common mix-ups
If a test is 95% accurate, a positive result is 95% likely to be right.
✓ That depends on the base rate. For rare conditions a positive can still be more likely wrong than right.Two checks always multiply the evidence.
✓ Only if their errors are independent. Checks fooled by the same cause add little.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Out of 1000 parts, 20 are faulty and flagged and 60 are good but flagged. What is P(faulty | flagged), as a percentage?
Answer: %
2. 1% of parts on a line are faulty. A camera check flags 99% of faulty parts and wrongly flags 1% of good parts. A part is flagged. What is the probability, as a percentage, that it is really faulty?
Answer: %
3. 2% of parts on a line are faulty. A camera check flags 95% of faulty parts and wrongly flags 5% of good parts. A part is flagged. What is the probability, as a percentage, that it is really faulty?
Answer: %
4. P(flagged | faulty) = 0.95. Which statement follows?
- P(faulty | flagged) = 0.95
- Nothing about P(faulty | flagged) without the base rate and false-positive rate
- P(faulty | flagged) = 0.05
5. Base rate 0.5%, sensitivity 95%, false positives 4%. Which change most raises P(faulty | flagged)?
- Sensitivity to 99%
- False-positive rate to 0.5%
- Testing more parts
Apply it
BUILD 003 Level 4 asks how often a majority vote of three sensors is wrong when each is wrong 10% of the time. Work it out with a probability tree, then use Bayes' rule to find P(part is really red | majority says red) for a line where 30% of parts are red. Say which assumption could fail.
Reflect
Explain the base-rate effect to someone who has never studied probability, using a frequency tree.
Expected value: deciding when you can't be sure
A part is 15% likely to be faulty. Ship it, scrap it or check it again? There's a calculation for that.
Why it matters
A perception system's output is a probability; a machine must still act. Expected value connects the two: it turns 'probably faulty' and 'a return costs £200' into a decision rule and a threshold you can defend.
Goals
- Compute the expected cost of each action as Σ probability × cost.
- Find the break-even probability between two actions.
- Explain what expected value ignores and when worst-case thinking matters more.
Predict
A part is 15% likely to be faulty. Shipping a faulty part costs £200; scrapping any part costs £20. Which is cheaper on average?
- Ship: most parts are fine
- Scrap: 15% × £200 = £30 is more than £20
- They cost the same
Write down your guess and your reason. The reveal is in the online lesson.
Discover
With the default costs, sweep p from 0 to 100% and note where the best action changes. Read the break-even points from the chart and check them by hand. Now make re-inspection free, then expensive. When is checking again worth it?
What the interactive shows, in words
The chart plots expected cost against the probability of a fault for three actions: shipping (a line rising from £0 to £200), scrapping (flat at £20) and re-inspecting (rising gently from £8 to £28). With the defaults, shipping is cheapest below about 4%, re-inspecting between about 4% and 60%, and scrapping above about 60%.
Understand
Expected value
For an action with possible outcomes, expected cost = Σ (probability of outcome × cost of outcome). Shipping a part that is faulty with probability p: p × (return cost) + (1 − p) × 0. Compute it for every action and choose the smallest. It is the average cost per decision over many similar decisions.
Thresholds from costs
Ship beats scrap while p × C_miss < C_scrap, so the decision threshold is p* = C_scrap ÷ C_miss. With £20 and £200 that is 10%: scrap anything more than 10% likely to be faulty. This is how a probability from Bayes' rule becomes an action, and why the 'right' detector threshold depends on costs.
The value of a second look
Re-inspection costs something but removes uncertainty: expected cost = C_check + p × C_scrap (scrap only if it really is faulty). It wins in the middle range of p, where you are genuinely unsure, and loses when you're already nearly certain either way.
What averages hide
Expected value treats a 1% chance of a £10,000 disaster like a certain £100 loss. When outcomes include injury or irreversible harm, engineers add constraints (never ship above some risk, whatever the average) instead of just minimising expected cost.
Explain it another way: intuitive
Taking an umbrella: if rain is only 20% likely but getting soaked ruins your day, you take it anyway, because the bad outcome is so much worse than carrying an umbrella.
Explain it another way: technical
Bayes decision rule: choose the action a minimising Σₛ P(s | evidence)·L(a, s), where L is the loss table. For two actions and two states it reduces to a threshold on P(s | evidence) set by the loss ratio.
Explain it another way: mathematical
Ship vs scrap: p·M = S gives p* = S/M. Check vs ship: C + p·S = p·M gives p = C/(M − S). Check vs scrap: C + p·S = S gives p = 1 − C/S.
Explain it another way: applied
Autonomous vehicles weigh the cost of an unnecessary emergency brake against a missed obstacle. Because a miss can injure someone, designers set hard safety constraints rather than relying on average cost alone.
Try these examples
Example 1
p = 30%, miss £200, scrap £20, re-inspect £8. Which action?
The worked solution is in the online lesson.
Common mix-ups
If something is more likely good than bad, treat it as good.
✓ When the costs of mistakes are unequal, the best action can be the 'unlikely' one.Expected value predicts what will happen this time.
✓ It is a long-run average; any single decision can turn out better or worse.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Shipping a part with a 4% chance of being faulty, where a faulty shipment costs £300. What is the expected cost of shipping, in pounds?
Answer: £
2. A part has a 5% chance of being faulty. Shipping a faulty part costs £400; shipping a good part costs £0. Scrapping any part costs £5. What is the expected cost of shipping it, in pounds?
Answer: £
3. Shipping a faulty part costs £200; scrapping any part costs £15. Above what probability of a fault (as a percentage) does scrapping have the lower expected cost?
Answer: %
4. p = 20%, scrap cost £25, re-inspection £6 (assumed perfect; scrap only if faulty). What is the expected cost of re-inspecting, in pounds?
Answer: £
5. A robot's choice has a 0.1% chance of injuring someone. Why isn't expected cost alone the right tool?
- Because 0.1% is too small to matter
- Because some outcomes are unacceptable whatever the average, so they need hard limits
- Because expected value can't handle small probabilities
Apply it
Combine this week: take the Bayes posterior for a flagged part (base rate 2%, sensitivity 90%, false positives 5%) and the costs £200 miss, £20 scrap, £8 re-inspection. Decide what to do with flagged and unflagged parts, and compute the expected cost per 1,000 parts of your policy.
Reflect
Where in your own life have you made an expected-value decision without calling it that?
Week 27: Perception system project
This week you will
- Build and evaluate a small perception pipeline that turns noisy sensor or image data into a decision.
- Report its performance on held-out data and its failure modes with evidence.
Designing a perception pipeline
Sense, filter, segment, measure, decide. Which stage of the pipeline fails first when the lights flicker?
Why it matters
Real perception systems are chains of the steps you have learned, and their failures are usually at the joins: a filter that adds too much lag for the threshold after it, a threshold tuned in one light level. Designing the chain on paper, then testing it like a scientist, is the term's final skill.
Goals
- Lay out a perception pipeline as stages with stated inputs, outputs and parameters.
- Design a controlled investigation of one parameter's effect on reliability.
- Plan the term project: data, ground truth, conditions and metrics.
Predict
You want to know whether belt speed affects sorting accuracy. Which test design is fairest?
- Run once at each speed with different batches
- Run each speed several times on the same test batch, changing nothing else
- Run the fastest speed many times
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the sorting machine at Level 5. Choose one question (belt speed versus accuracy, or how much majority voting helps as glare increases). Change one setting across at least four recorded runs on the same test batch, holding everything else fixed.
What the interactive shows, in words
Sorting machine Level 5, described: you choose one setting, such as belt speed, and record at least four runs on the same test batch with everything else fixed. The server recomputes each run's accuracy and throughput; you write a short report with a hypothesis, method, results and limitations, which a person reviews.
Understand
Stages and interfaces
Write the pipeline as boxes: sense (camera or sensor, sample rate) → condition (filter, calibrate) → segment (threshold, colour rule) → measure (label, area, position) → decide (rule, threshold from costs). For each stage state its input, output, units and parameters. That list is your design, and also your debugging map.
One question at a time
A good investigation asks a focused question, changes one variable, holds the others fixed, repeats runs to see the spread, and chooses its metric (recall, precision, throughput) before looking at results. Record everything, including runs that look wrong.
Planning the term project
The project, 'Count the parts, honestly', needs: a set of images with hand-counted ground truth; separate tuning and test images; at least three conditions (normal, changed lighting, added noise or occlusion); a metric per condition; and one mitigation tried and measured. Plan the data before writing code.
Explain it another way: intuitive
A pipeline is a relay race: each runner hands the baton to the next. If one drops it, the team loses, however fast the others are.
Explain it another way: technical
Perception pipelines are evaluated end to end (final decision versus ground truth) and per stage (for example segmentation accuracy per pixel), so failures can be located. Parameters are tuned on one data split and evaluated on another.
Explain it another way: applied
Industrial vision suppliers validate a new inspection line on a fixed 'golden' set of known good and bad parts under controlled lighting before going live, and repeat it after any change.
Try these examples
Example 1
Write a one-line research question and method for the sorting machine.
The worked solution is in the online lesson.
Common mix-ups
If the final number looks right, every stage works.
✓ Errors can cancel. Check stage outputs too, especially under changed conditions.Tuning on the test images is fine if you're careful.
✓ Any tuning on test data makes the test optimistic. Keep test images untouched until the end.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which change would make a belt-speed comparison unfair?
- Using the same test batch for every speed
- Re-tuning the thresholds separately at each speed without saying so
- Repeating each speed three times
2. Why choose the metric before running the tests?
- It saves time
- So you can't pick, after the fact, whichever metric makes your favourite setting look best
- Metrics change during testing
3. One reading of a temperature sensor has standard deviation 2 °C. You average n = 36 independent readings. What is the standard error of the mean, in °C?
Answer: °C
4. Your parts counter is wrong only in dim images. The threshold mask looks fine in bright images but patchy in dim ones. Which stage should you fix first?
- The decision rule
- Segmentation (thresholding) or the lighting before it
- Labelling
Apply it
Submit your Level 5 investigation with hypothesis, method, a results table and limitations. Then write your term-project plan: pipeline diagram with parameters, the image set and how you will hand-count ground truth, the three conditions and the metric for each.
Reflect
Which stage of your planned pipeline do you expect to fail first, and what evidence would show it?
Evaluating honestly: held-out tests and failure modes
Your threshold scores 98% on the images you tuned it on. On new images it scores 81%. Which number goes in the report?
Why it matters
A perception system that works only on the data it was tuned on is a demo, not a product. Honest evaluation, on held-out data and under deliberately hard conditions, is what lets other engineers trust your numbers. It is also the core of the term assessment.
Goals
- Separate tuning data from test data and explain why test results are lower.
- Report a perception system's precision and recall per condition, with counts.
- Describe failure modes with evidence and measure one mitigation.
Predict
A threshold is chosen to give the best accuracy on a tuning batch. On a fresh batch from the same machine, its accuracy will most likely be…
- the same
- a bit lower
- higher
Write down your guess and your reason. The reveal is in the online lesson.
Discover
On the tuning batch, find the threshold with the highest accuracy and write down precision and recall. Switch to the fresh test batch without moving the slider. What changed? Is there a threshold that does well on both, and how would you have found it without peeking?
What the interactive shows, in words
The confusion-matrix diagram has a tuning batch and a fresh test batch of 60 simulated parts each. A threshold chosen to maximise accuracy on the tuning batch usually gives a slightly different, often lower, accuracy, precision and recall on the test batch, because the two batches' random overlap differs.
Understand
Tune on one set, test on another
Split data before you start: a tuning (or training) set for choosing parameters and a test set touched once, at the end. Any decision made by looking at test results, even choosing between two thresholds, leaks information and inflates the score. With little data, keep at least a small test set sacred.
Report by condition, with counts
Give precision and recall for each condition (normal, dim, noisy, occluded), with the underlying TP/FP/FN counts and the number of items. 'Recall 90% (27 of 30)' tells a reader how much to trust it; '90%' alone does not. Say how ground truth was obtained.
Failure modes are findings
A failure mode is a describable situation where the system goes wrong: touching parts merge, glare saturates pixels, shadows split objects. Show an example, explain the cause using this term's ideas, try one mitigation, and measure it on the test set. A report that hides its failures is less useful, and less trustworthy, than one that explains them.
Explain it another way: intuitive
Practising a spelling test with the exact words that will be tested tells you little. The real test is new words.
Explain it another way: technical
Selecting the maximum of many noisy scores is biased upwards (a winner's curse). Held-out evaluation removes that bias; cross-validation rotates the split when data is scarce, but the final reported test set must stay unseen.
Explain it another way: mathematical
With n test items and a true recall of R, the measured recall has a standard error of about √(R(1 − R)/n). For R = 0.9 and n = 30 that is about 0.055, so 90% ± 5.5%: small test sets give wide error bars.
Explain it another way: applied
Regulators and customers in industrial and medical vision ask for performance on independent test data, broken down by condition, before a system is accepted.
Try these examples
Example 1
Test results: normal light TP 28, FN 2, FP 1; dim light TP 19, FN 11, FP 0. Summarise.
The worked solution is in the online lesson.
Common mix-ups
Reporting the tuning-set score is fine if it's labelled.
✓ Label it, but the headline must be the held-out test score; the tuning score describes how well you fitted, not how well it works.Failures make a project look bad.
✓ Well-explained, measured failures show you understand the system and help others avoid them.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A defect detector is tested on labelled parts: TP = 60, FP = 0, FN = 21, TN = 394. What is its recall, as a percentage?
Answer: %
2. A defect detector is tested on labelled parts: TP = 23, FP = 33, FN = 8, TN = 108. What is its recall, as a percentage?
Answer: %
3. Recall is 0.8 measured on 100 faulty test parts. Using √(R(1 − R)/n), what is its standard error (as a decimal)?
Answer:
4. You compare two thresholds on the test set and report the better one's score. What is wrong?
- Nothing
- Choosing on the test set makes it part of tuning, so the reported score is optimistic
- You should have compared three
5. Which failure-mode statement is most useful?
- 'It sometimes doesn't work.'
- 'In 6 of 10 dim images, parts below brightness 90 were missed; adaptive thresholding cut misses to 2 of 10.'
- 'Dim images are hard for computers.'
Apply it
Term assessment: deliver your 'Count the parts, honestly' project. Include the tested pipeline, a ground-truth table, precision, recall and count error per condition on held-out images with counts, a failure-mode report with one measured mitigation, and a paragraph on what you would test next.
Reflect
Looking back over the term, which source of uncertainty (noise, aliasing, lighting, base rates) would you now check first in any sensing system, and why?