A camera chip sends a dim, green, mosaic-patterned grid of numbers. Nine small stages turn it into a picture, and three loops keep it steady. Quantise the exposure to the flicker, and the pulsing stops.
Learn what an image signal processor does to every frame, in what order, and why. Then learn how auto exposure, auto white balance and auto focus watch the frames and steer the camera two or three frames late.
Switch the nine stages on one by one and watch an image form. Then switch off white balance, then gamma, and see what each one was quietly doing. After that we build, piece by piece, every stage and every loop.
You need to know that a picture is a grid of numbers, and a little patience with a few simple formulas. We build the rest from zero. The previous lesson, from sensor to CSI, shows how the raw numbers reach the chip.
Built from the Raspberry Pi Camera Algorithm and Tuning Guide (Raspberry Pi Ltd) and the open-source libcamera code. All pictures here come from small models that run in your browser. Sources are listed in the Field Guide.
A model, not a real chip. The scene is a 64 by 48 pixel toy with a 10-bit sensor model: black level 64 of 1023, a lens that darkens the corners to 55%, ten stuck pixels, and an illustrative daylight colour cast. Noise numbers are illustrative. The stage order, and why it is this order, are explained in Chapter 1.
Chapter 0
Follow a pulsing video back to a control loop that is two or three frames late, measuring a lamp that flashes 100 times a second
A small robot rolls down an office corridor. Its camera feeds a tracker. Under the ceiling tubes the video pulses: bright, normal, dark, bright, normal, dark. The tracker loses its target every third frame. Near a window, the same camera is steady.
You open the metadata of each frame. One field, ExposureTime, wobbles by a few percent. Nothing is broken. A control loop is doing its job, but the light it measures is itself flashing.
A camera chip collects light for a short time, then amplifies what it collected. The collection time is the exposure time, also called the shutter time. The amplifier setting is the gain. Together they set how bright the picture is: total exposure is roughly time multiplied by gain.
Auto exposure (AE) picks those two numbers for you. Think of a thermostat. The camera reads how bright the last frame was, compares it with a target, and nudges the exposure time and gain. The Raspberry Pi guide calls this algorithm AGC/AEC. It controls the shutter time, the gain inside the sensor, and a further digital gain inside the ISP.
An ISP (image signal processor) is the block of hardware or software that turns the sensor’s raw numbers into a picture. AE is one of three loops that run beside it. The other two are auto white balance (AWB), which fixes colour casts, and auto focus (AF). Together they are called the 3A loops.
The brightness of frame k is known only after the whole frame has been read out. By then frame k+1 is already collecting light. A new exposure setting has to travel to the sensor, and the sensor needs time to apply it.
The libcamera code lists this delay for each sensor. Its comment says that “2 frames delay” means that settings written during frame N take effect for frame N+2. For the Sony IMX477 sensor the table gives 2 frames for exposure and 2 for gain. Count it once: frame k is measured, the new setting is written during frame k+1, and it shows in frame k+3. This lesson calls that the loop delay: two to three frames, depending on how you count. At 30 frames per second, three frames is 100 ms.
Mains power swings from positive to negative, 50 times a second in much of the world and 60 times a second in the USA. A fluorescent tube lights on both halves of the swing, so it flashes at twice the mains rate: 100 Hz or 120 Hz. The time between flashes is the flicker period: 10 ms at 100 Hz, and 8.33 ms at 120 Hz. libcamera’s flicker control uses exactly these values: 10000 microseconds for 50 Hz mains, and 8333 for 60 Hz.
Your eye cannot see 100 Hz. Your camera can, because its exposure window is short. Say the window lasts 15 ms. It catches one and a half flashes, and the mix depends on when it opens. The next frame opens at a different moment in the cycle. The brightness of the frame now depends on timing, not on the scene.
There is a clean way out. If the window lasts exactly one flicker period, or two, or three, then it always catches the same amount of light, wherever it starts. Here is the maths. Let the lamp be 1 plus a small wave of depth m. The mean over a window of length T is:
Try it. The device below runs the whole loop for 140 frames at 30 frames per second. At frame 50 the room gets 1.6 times dimmer, so the loop must lengthen the exposure. Watch the brightness of the frames (top) and the exposure time the loop chooses (bottom).
Top: brightness of each frame, where 1.00 is the target. Bottom: the exposure time. Press Quantise to flicker on and off. Then lower the loop gain and watch the speed, not the pulse, suffer.
Illustrative loop: 30 frames per second, flicker depth 40%, the exposure must grow from 15 ms to 24 ms at frame 50, and the exposure time is capped at one frame (33.3 ms) with gain making up the rest. The averaging formula is exact. The loop updates the exposure by the measured brightness raised to the power minus loop gain, applied after the chosen delay.
With 50 Hz mains and no quantising, the brightness pulses with a period of three frames. The reason is the beat between the lamp and the frame rate. A frame lasts 33.3 ms, which is 3.33 flicker periods of 10 ms. So the window starts one third of a cycle later each frame, and the pattern repeats every three frames. Switch to 60 Hz and the pulse vanishes: 33.3 ms is exactly four periods of 8.33 ms, so every frame starts at the same phase. A camera tuned in one country can pulse in another.
Now the worked case. Take 50 Hz mains, so P is 10 ms, and an exposure of 15 ms. Then πT/P is 1.5π, the sine is −1, and the leak is 1/(1.5π) = 0.212. With a flicker depth of 0.4, each frame is off by up to 0.4 × 0.212 = 8.5%. Change the exposure to 10 ms or 20 ms and the sine is 0, so the leak is zero. At 5 ms the leak is 2/π = 0.64, and the pulse is large.
The pulse is in the frames themselves. The lamp flashed while the shutter was open, so the light is already in the pixels. Turn the loop gain down in the device. The exposure time wobbles less, but the picture still pulses by about the same amount, and the loop now takes longer to follow the dimmer room. Damping trades speed for a smaller wobble in the setting, and leaves the picture alone.
The fix works at the source. Make the exposure time a whole number of flicker periods and let the gain carry the remainder. The Raspberry Pi AGC code does exactly this. It divides the wanted exposure time by the flicker period, rounds down to a whole number, uses that many periods as the new time, and multiplies the gain by the ratio of old time to new time. The brightness stays right, and the leak is zero. The code only does this when the time is at least one full period and neither time nor gain is fixed by the application.
Symptom: brightness pulses at a steady beat under lamps, and the tracker drops frames at that beat. Measurement: log the mean brightness and the ExposureTime of every frame. Look for a repeating pattern whose period is the beat of the lamp against the frame rate. Fix: set the flicker period (10000 or 8333 microseconds in libcamera) so the loop quantises the exposure, and keep the loop gain below the limit you meet in Chapter 7.
Chapter 1
Follow one frame through nine stages and learn why swapping two of them makes the picture worse
A colleague hands you a raw file from a camera. You open it as a picture. It is dark, a little green, speckled with a fine grid, and the corners are darker than the middle. Nothing is wrong with the file. It is exactly what the sensor reported. Everything you expect from a photo was added after.
A sensor has millions of light-catching cells, called pixels. Each pixel sits behind a tiny coloured filter, red, green or blue. The filters repeat in a 2 by 2 block: red and green on one row, green and blue on the next. This is the Bayer pattern. Half the pixels are green, because the eye is most sensitive to green. So each pixel stores only one colour, as one number.
The number has 10 or 12 bits: 0 to 1023, or 0 to 4095. It is roughly proportional to how much light the pixel caught. Twice the light gives twice the number. We call this linear light. The tensor that enters the ISP is a single plane of numbers, shaped [height, width], not [height, width, 3]. The three colour planes are made inside the ISP.
Here is the rule of thumb. First fix the sensor, while each number is still one pixel’s own. Then make colour, while numbers still mean light. Last, encode for the eye. The hero at the top of the page runs exactly these nine stages.
| Stage | Works on | What it fixes | Mean shift if skipped |
|---|---|---|---|
| 1 Black level | mosaic | the pedestal the sensor adds to every pixel | +5.3 (dim room +17.4) |
| 2 Bad pixels | mosaic | stuck-bright or stuck-dark pixels | about 0 |
| 3 Lens shading | mosaic | dark corners from the lens | −4.7 |
| 4 Demosaic | mosaic to colour | one colour per pixel becomes three | no picture forms |
| 5 White balance | linear colour | the colour of the lamp | −2.5, but green leads by 27 |
| 6 Colour matrix | linear colour | the sensor’s own colour mixing | +1.0, colours wash out |
| 7 Denoise | linear colour | random grain | about 0 |
| 8 Gamma | linear to encoded | eye and 8-bit coding | −21.8, a dark image |
| 9 Sharpen | encoded colour | softness from lens and demosaic | about 0 |
Mean shift is the change in average display brightness, in points of 100, when only that stage is switched off in this lesson’s model (colour chart, daylight cast, all else on). Measured in the model, not on a real chip. The “27” is the green mean (66) minus the red mean (39).
Look at the last column. Three stages move the whole histogram: black level, lens shading and gamma. White balance moves the three colours apart instead. Bad pixels, denoise and sharpen leave the average alone. They change texture, not position.
Before the order, one picture helps. Imagine a factory line. The first workstations repair the raw material. The middle ones shape it. The last ones pack it for the customer. If you pack first and then try to repair, the repair tools no longer fit the box. The ISP is built like this, and each workstation expects its input in one particular form.
Each early stage protects a later one. Black level first, because later stages multiply. A pedestal that gets multiplied by a gain of 2 becomes a pedestal twice as big, and it tints the shadows. Bad pixels before demosaic, because demosaic spreads each pixel into its neighbours. The Raspberry Pi guide shows a bright dead pixel whose effect “spreads slightly because of the filtering operations”. Lens shading before white balance, because the statistics that choose the white balance gains must see an even image.
White balance and the colour matrix come while the numbers are still linear. Both are multiplications that assume doubling the light doubles the number. Gamma breaks that assumption on purpose, so these stages must come before it.
Denoise also belongs in linear light. Here the noise follows a simple law: bright pixels have bigger noise, in a known amount. The filter can look up that amount and set its threshold. After gamma, the law is bent and the threshold is wrong.
Here is the arithmetic. A power-law gamma of 1/2.2 turns a number x into x1/2.2. Its slope is (1/2.2) × x−0.545. At 1% grey the slope is 5.6. At 50% grey it is 0.66. The same noise therefore gets 8.4 times larger in the shadows than in the mid-tones. A filter after gamma must cope with noise whose size changes by that factor, using one threshold.
Same noisy colour chart, same filter strength. Left: denoise in linear light, then gamma. Right: gamma first, then denoise. Pick a dimmer light and read the grain in the darkest grey square, boxed in teal.
Toy model with illustrative noise (read noise 2 DN, shot noise 0.5 DN per DN of signal). The “before” filter sets its threshold from the signal level, as real ISPs do from a noise profile. The “after” filter uses one fixed threshold on the gamma-coded values. Grain is the standard deviation of the 8-bit code inside the box.
In the dim setting, the darkest square has grain of about 6.3 codes with no filter. Denoising before gamma cuts it to 2.5. Denoising after gamma leaves it at 5.9. Same filter, same strength, only the order differs.
Symptom: the denoised video is clean in bright areas but grainy in shadows, and raising the strength makes bright areas look plastic. Measurement: film a grey chart at low light. Take the standard deviation of one dark and one bright square after the whole pipeline. Fix: move the filter before gamma, or give it a threshold that depends on the level.
Chapter 2
Fix three facts about the sensor and the lens before any colour exists, and see what a wrong table does to the corners
Cover the lens with a cap and take a picture. A perfect camera would give zeros. Yours gives something near 64, on a scale to 1023, in every pixel. Now point it at a flat white wall. The middle reads 900, but the corners read 500. A few pixels read 1023 whatever you do. Three separate facts, three small stages.
A sensor adds a constant offset to every pixel so that noise below zero is not cut off. This offset is the black level, or pedestal. The sensor’s data sheet gives its value. A pixel at or below it means “no light”. Stage 1 subtracts it and rescales so that full scale stays full scale:
Worked example. A pixel reads 300 with B = 64 and F = 1023. Then v = (300 − 64) / (1023 − 64) = 236 / 959 = 0.246. The Raspberry Pi tuning file stores B in a 16-bit scale whatever the sensor’s own width. For a 10-bit sensor with black level 64, the guide computes 64 / 1024 × 65536 = 4096. Forget this scaling and the stage subtracts almost nothing.
If the stage is skipped, the damage is large after gamma. A black pixel keeps v = 64 / 1023 = 0.063. Gamma turns that into 0.0631/2.2 = 0.28. Black becomes 28% grey, and the whole picture looks hazy.
Some pixels are broken from the factory. A stuck pixel reads one value whatever the light. A weak pixel responds, but too much or too little. The Raspberry Pi ISP filters these “adaptively, without knowing in advance where they are”, and exposes only three settings: none, normal, strong.
The idea is simple. Compare each pixel with its four nearest neighbours of the same colour, two steps away on the grid. If the pixel is brighter than all four by a margin, or darker than all four, call it defective and replace it with their mean. Example: a pixel reads 1023 and its neighbours read 200, 210, 190 and 205. The largest neighbour is 210, and the margin we allow is 77 (8% of 959). Since 1023 > 287, we replace it with (200 + 210 + 190 + 205) / 4 = 201.
It must happen before demosaic. After demosaic, a bad pixel has already leaked into eight neighbours and in each of the three colours.
A lens does not spread light evenly. Rays at the edge arrive at a steeper angle and are partly blocked. The result is vignetting: dark corners. Colour can shift too, because the effect differs for red, green and blue. The ISP fixes it with a gain map: a grid of multipliers, large at the corners and 1 in the middle. The Pi guide describes a 16 by 12 grid on older chips and 32 by 32 regions on the Pi 5. Each pixel’s gain is interpolated from the four nearest grid values.
How do you get the grid? Photograph a flat, evenly lit surface, such as an LED video lamp with a diffuser. Average several shots to beat the noise. Divide the centre value by the value at each grid point. That ratio is the gain. The Pi guide corrects colour shading fully and luminance only partly, since full luminance correction multiplies noise in the corners.
The picture is a flat grey wall seen through the lens. The graph is one row across the middle: the lens loses light towards the sides (blue), the table gain (purple), and the corrected row (warm). Pick the lens, then pick whose table to use.
The table is fitted by the same recipe as above: 16 flat-field frames averaged, green pixels near each of the 17 by 13 grid points, centre divided by local value. Lens loss is a toy curve (brightness falls with the square of distance from the centre). Noise is illustrative.
Look at the numbers when the table matches the lens: the corner comes back to within a few percent of the centre. Now use the table from the other lens. If the real corner keeps 55% and the table assumes it keeps 75%, the table gives a gain of 1/0.75 = 1.33 where 1/0.55 = 1.82 is needed. The corner ends at 0.55 × 1.33 = 0.73 of the centre: 27% too dark. The device, which uses fitted tables, lands at about 25%.
Symptom: after a lens swap or a new batch of modules, the corners are darker or tinted, and a stitching or SLAM front end sees brightness change with image position. Measurement: photograph a flat field and compare the mean of a corner block with the centre block, per colour channel. Fix: refit the table for that lens. The Raspberry Pi guide has a lens-only mode, alsc_only.py, for the case where you changed the lens and nothing else, using flat-field images and no colour chart.
Chapter 3
Guess the two missing colours at every pixel, and see why a simple guess puts a zipper along an edge
Zoom far into a photo of a chain-link fence. Along the edge of each wire you see a row of tiny alternating dots, light, dark, light, dark, like the teeth of a zip. Some of the dots are the wrong colour, pink or cyan, where the real wire is grey. Nobody put them there. The camera guessed, and on an edge the guess was wrong.
Chapter 1 showed that each pixel holds one colour. A red pixel knows its red and nothing about green or blue. The ISP must fill the other two. Filling them is demosaicing, from the mosaic of colour filters. It turns a plane of shape [H, W] into three planes of shape [H, W, 3]. Two thirds of the final numbers are estimates.
Bilinear interpolation takes the plain average of the nearest pixels of the missing colour. At a red pixel, the four nearest greens are above, below, left and right. The guess for green is their mean. For a smooth patch it works well, because neighbours match.
Now put an edge through the patch. Say the pixel and the pixels above and below it sit on the dark side of a vertical edge: green 20, 20, 20. The green to its right is on the bright side: 200. The bilinear guess is (20 + 20 + 20 + 200) / 4 = 65. The true green at this pixel is 20. The error is 45, from one bright neighbour that never belonged to this pixel’s side of the edge.
The next pixel along the edge makes a different mix of neighbours. So the error alternates along the edge: too bright, right, too bright, right. That is the zipper.
An edge-aware method first asks which way the picture changes least. It measures two gradients, the difference left to right and the difference up to down. It then averages along the direction with the smaller gradient. In the example, the horizontal gradient is |20 − 200| = 180 and the vertical gradient is |20 − 20| = 0. The vertical one is smaller, so it averages above and below: (20 + 20) / 2 = 20. That is exactly right.
After green is complete, red and blue are filled by a second trick. Colour differences, such as red minus green, vary slowly, because most sharp edges are changes in brightness, not in hue. So we interpolate R − G over the neighbours, then add green back. This keeps red and blue edges lined up with the sharp green edge.
A 64 by 48 test image: a slanted red and cyan edge, a slanted black and white edge, a red disc, and grey bars three pixels wide. Choose how to see it. Switch on Show error to light every pixel by how far it is from the true scene.
Synthetic scene with no noise, bad pixels or lens shading, so only demosaic differs. Error is the mean absolute difference from the true scene after gamma, in percent of full scale. The edge-aware method here is a simple gradient-chooser plus colour differences, not any vendor’s algorithm.
Read the numbers. On the grey bars, bilinear is off by 12.1% of full scale and the edge-aware method by 5.5%. The bars are only three pixels wide, close to the limit of what a grid with one red pixel every two columns can see. On the red and cyan edge the two methods are close at 3.7% and 3.5%. Edge-aware is not a miracle. It helps where one direction is clearly smoother than the other.
When detail is finer than the grid can sample, no method can recover it. The red pixels sit two apart, so a pattern with a period shorter than four pixels cannot be seen in red at all. The camera invents a slower pattern in its place, and that shows up as coloured fringes, called false colour or moiré. Many cameras put a slight optical blur in front of the sensor for this reason: it removes detail the grid could not carry anyway.
Better guesses need wider windows, and wide windows cost memory. A streaming ISP reads pixels one row at a time. A filter that spans five rows must hold four earlier rows in line buffers. For a 1920-pixel-wide frame at 12 bits that is 4 × 1920 × 12 = 92,160 bits, about 11.5 kB of fast memory, just for this stage. A 3 by 3 window needs only two rows. That is the trade between a hardware demosaic and a software one.
Symptom: zipper dots or coloured fringes on high-contrast edges, worse after sharpening, and a feature-matcher that fires on the fringes. Measurement: photograph a slanted-edge chart and plot colour across the edge. A clean edge changes in one step. Zipper shows as a ripple. Fix: switch to an edge-aware demosaic, lower the sharpening that amplifies it, and keep the optical blur if you have one.
Chapter 4
Remove the colour of the lamp, mix the colours back to standard, and learn why a robot rig should not let two cameras decide alone
A robot has two cameras side by side, for stereo depth. A person in a red jacket steps into view of the left camera only. The left camera sees a lot of red. Its picture turns slightly blue, the red jacket looks calmer, and the grey floor looks cold. The right camera sees the same floor, still grey. Your stereo matcher compares colours between the two images and starts to fail. Your detector, which looks for a red cone, misses the cone in the left image.
A white wall under a candle looks orange, and the same wall under sky light looks blue. Your eye hides this. The Raspberry Pi guide calls it colour constancy: an object that looks orange outdoors still looks orange indoors, although a spectrometer would show it much redder or bluer. A sensor has no such magic. It records the lamp’s colour as part of the object.
The fix is a multiplication. If a grey wall reads red 0.50, green 1.00, blue 0.62 under a lamp, we want all three equal. Multiply red by 1/0.50 = 2.00 and blue by 1/0.62 = 1.61. Green stays at 1. These two numbers are the white balance gains. The Pi guide writes them exactly this way: normalise to r = R/G and b = B/G, then gainr = 1/r and gainb = 1/b. Under a tungsten bulb, which is warmer, the same wall might read 0.80, 1.00, 0.30. Then the gains are 1.25 and 3.33. A blue gain of 3.33 also multiplies the blue noise by 3.33.
The camera does not know the lamp. It must estimate it from the picture. The simplest method is grey-world: assume the average colour of the scene is grey, and choose gains that make the averages of the three channels equal. For a scene full of mixed colours this works. For a scene that is mostly one colour it fails, because it “corrects” the real colour away.
The Raspberry Pi code is smarter. It measures a grey chart under many lamps and plots r against b. The curve through the points is the colour temperature curve. For a new picture it asks: which lamp on this curve makes the colours in the picture most likely? It chooses by a Bayes calculation and applies that lamp’s gains. This stays close to real lamps, so a red jacket cannot easily pull it far away. It can still be tricked by a very large single-colour area.
Both cameras look at the same grey card. Camera A sees a little red wall. Drag to let camera B see more of it. Each camera runs grey-world. Then switch on Lock gains.
Toy model: the scene is neutral grey (0.18 reflectance) plus a red wall (0.58, 0.10, 0.07), under the daylight cast of this lesson (0.50, 1.00, 0.62). Grey-world sets gains from the frame mean, then the colour matrix and a 2.2 gamma run. Locked gains are the daylight ones, set once on a neutral scene.
At 10% red wall, camera B reads the grey card as (106, 118, 119) in 8-bit codes. At 70%, grey-world pushes the blue gain up to 2.17 and the red gain down to 0.83, and the card reads (60, 120, 139). Same card, same lamp. The camera moved the red code by 46. With the gains locked, both cameras read (117, 117, 117).
Symptom: two cameras that agree in a lab disagree in the field, depending on what each one sees, and matching or colour-based detection degrades. Measurement: log the colour gains of each frame. libcamera gives them as metadata. A rig shows gains that move apart when the scenes differ. Fix: on a rig, turn automatic white balance off and set the gains by hand, red then blue, from a calibration under the lamps you expect. In libcamera this means setting AwbEnable to false and then ColourGains. If the lamps change a lot, set one shared estimate for both cameras, not one each.
White balance makes grey right. It does not make saturated colours right. The coloured filters over the pixels overlap: a red filter also lets in some green and blue light. Pure red light gives a reading that is partly green and blue, so reds look washed out. A colour correction matrix (CCM) undoes the mixing with a 3 by 3 multiplication:
Worked example with this lesson’s sensor model. A true red patch (0.70, 0.12, 0.10) reaches the ISP, after white balance, as (0.583, 0.188, 0.127): paler than the truth. The matrix has rows (1.288, −0.237, −0.051), (−0.195, 1.352, −0.157) and (−0.025, −0.258, 1.284). Row one gives 1.288 × 0.583 − 0.237 × 0.188 − 0.051 × 0.127 = 0.751 − 0.045 − 0.006 = 0.700. The red is back. Real matrices look alike: the Pi guide shows a row of 1.80439, −0.73699, −0.06739, big on the diagonal and slightly negative beside it. The Pi code picks a matrix by the colour temperature AWB estimates, and interpolates between calibrated ones.
Chapter 5
Squeeze 10 or 12 bits of light into 8 bits of picture, and choose which detail to keep
A robot drives towards a warehouse door. Outside, the sky is blinding. Inside, the shelves are dim. You set the exposure for the shelves, and the sky turns into a flat white shape with no clouds. You set it for the sky, and the shelves turn into black. The detector needs the boxes on the shelves and the daylight beyond them. The sensor probably saw both. The tone curve decided what survived.
After Chapter 4, the numbers are still linear light. Twice the light is twice the number. The output usually has only 8 bits, which means 256 levels. If we spent those levels evenly in linear light, half of them would go to the brightest single stop of the scene, where the eye can barely tell neighbouring levels apart. Only a handful would remain for the shadows, where the eye is sharp. The result shows visible steps in the dark.
The eye judges ratios. The step from 1 to 2 looks as big as the step from 50 to 100. A gamma curve copies that: it stretches the dark end and squeezes the bright end. The simplest version raises the number to a power of 1/2.2, so 0.5 becomes 0.73 and 0.01 becomes 0.12. The Pi tuning guide notes that it is really an inverse gamma, shaped like y = x1/2.2, and that the “theoretical 2.2 gamma” is rarely used as it stands, because it gives washed-out, low-contrast pictures. Tuners bend the curve by hand.
The true sRGB curve adds one fix. A pure power curve has infinite slope at zero, so it would amplify the faintest noise without limit. sRGB replaces the first part with a straight line of slope 12.92 (below 0.0031308 in linear light) and then continues with 1.055x1/2.4 − 0.055.
Now count. Say the sensor sends RAW10, so there are 1023 input codes, and the output has 255 steps above zero. A straight linear map drops 2 bits everywhere: 4 input codes share each output code. With RAW12 it drops 4 bits. A gamma curve does not drop the same number everywhere. The number of input codes that share one output code is:
Work it for RAW10. At white (x = 1) the slope is 0.455, so n = 1023 / (255 × 0.455) = 8.8 codes and the stage discards log2 8.8 = 3.1 bits. At 50% grey the slope is 0.663, n = 6.05, and it discards 2.6 bits. At 10% grey: slope 1.60, n = 2.5, 1.3 bits. At 1% grey the slope is 5.6, n = 0.72, so nothing is discarded, and some output codes stay unused. For RAW12 add 2 bits everywhere: from about 1.5 bits in the deep shadows to 5.1 at white. The curve decides where the detail goes: the 8 output bits are spent in the shadows and the surplus is thrown away in the highlights.
Throwing bits away adds quantisation noise. If each output step is one code wide, the rounding error is uniform and its standard deviation is 1/√12 = 0.29 codes. The lesson quantisation noise derives this. What matters here is that gamma places the larger steps in the highlights, where the eye can tell them apart least.
The scene is a dim room with a bright window, 7 stops from darkest to brightest. Choose a curve and shift the exposure. Watch the histogram and the clipped share in the read-out.
Toy scene: a window of 3.0, a floor of 0.25, a wall of 0.12 and a dim room of 0.05, in linear units where 1.0 is the display white. The soft shoulder is linear to 0.5 and then rolls off to 1 at a slope of 0.3. Bits discarded come from the formula above, using the slope of the curve you drew.
With gamma 2.2 and a hard clip, the window is above 1.0, so every window pixel lands on 255: 14% of the picture holds no detail at all. Pick the soft shoulder. The window now rolls off towards 255 and keeps a gradient, and none of the picture sits at 255. Shift the exposure one stop down and the room gets darker too. The tone curve cannot make light that the sensor did not record, but it can choose which light to show.
Symptom: skies or lamps turn into flat white blobs, or shadows into flat black, and a detector loses objects at the edge of the range. Measurement: read the output histogram. A tall bar at 255 or at 0 means clipping. Fix: lower the exposure target, add a soft shoulder or a local tone map, or move to a sensor mode with a wider range. Do this before you retrain the detector.
Chapter 6
Trade grain against detail, then against ghosts, and see how sharpening spends what denoise saved
A robot patrols a warehouse at night. The video is full of grain. You switch on the denoiser and the grain melts. Then a forklift crosses the view. It drags a pale copy of itself behind it, three car lengths long. The pallet edges, once crisp, look softly painted. You turned a dial and bought clean pixels, and paid for them in two ways.
Light arrives as photons, one at a time. In a short exposure a pixel counts, say, 100 photons, but the true average is only about 100. The count wobbles by roughly the square root: 10. This is shot noise, and it comes from physics, not from the chip. The chip adds read noise too. The picture has a signal-to-noise ratio (SNR): signal divided by noise. 100 photons give 100 / 10 = 10. Ten thousand photons give 100 / 100 = 100. Dim scenes are grainy because the signal is small.
Averaging is the cure, and there are two things to average. You can average a pixel with its neighbours in the same frame. Or you can average it with itself in earlier frames. Averaging n independent noisy values divides the noise by the square root of n.
The Raspberry Pi guide describes the spatial filter as averaging pixels in a small neighbourhood: where pixels look “close enough”, they are averaged. The test “close enough” protects edges. A pixel across a sharp edge differs a lot, so it is left out. In a 3 by 3 window the best case is 9 similar pixels, so noise falls by 3. In practice it falls less, because few of the nine are always similar.
The guide adds a warning: denoising completely can leave a picture looking “artificial or plasticky”. So the filter has a strength that blends the denoised pixel with the original. A little grain looks better than none.
A still scene gives the same picture every frame, plus fresh noise. Average N frames and the noise falls by √N: 4 frames halve it, 9 frames cut it to a third, 16 frames to a quarter. The Pi hardware does this cheaply. It blends the newest pixel with the previous output, so only one old frame is stored. Where the two look similar, it averages. Where not, it takes the new one. The guide notes it works better after “several frames”.
That blend is a recursive filter. If the new frame has weight a, the noise falls by a factor of √(a / (2 − a)). With a = 0.25 that is √(0.25 / 1.75) = 0.38, as good as averaging about 7 frames.
The price is time. If the forklift moves 2 pixels per frame and you average 8 frames, the filter still holds the forklift’s old positions. They fade in a trail of (8 − 1) × 2 = 14 pixels. This is motion ghosting. The look-alike test removes some of it, but a slow or low-contrast object still smears.
A flat wall with a dark bar, plus a sharp step edge at the bottom. Raw noise is 6.0% of full scale. Let the bar move, then raise the frames averaged. Then raise sharpening and watch the edge.
Toy scene with illustrative Gaussian noise, a 6-pixel bar, and a step from 0.30 to 0.70. Frames averaged is a plain mean of the last N frames. Spatial strength is a 3 by 3 bilateral filter. Sharpen is a 3 by 3 unsharp mask. Noise is the standard deviation of a flat patch. Halo is how far the edge overshoots, as a share of the step.
At N = 1 the flat patch has noise of 6.0%. At N = 4 it is 3.2%, at N = 9 it is 2.0% and at N = 16 it is 1.5%, as the square-root rule predicts. Make the bar move at 2 pixels per frame and 16 frames leave a ghost 30 pixels long. Noise drops, but the thing you wanted to track is a smear.
Both denoisers soften edges, and so does demosaic. Sharpening adds the edge back. An unsharp mask blurs a copy, subtracts the blur from the original, and adds a multiple of the difference. On a step edge that difference is positive just on the bright side and negative on the dark side. The edge looks sharper, but it overshoots: a bright line on the bright side and a dark line on the dark side. These are halos. With the sharpen at 1.0, the toy edge overshoots by 31% of the step, and some of that is amplified noise.
The Raspberry Pi sharpen block therefore has three controls: a threshold below which pixels are not sharpened, a strength for how fast sharpening grows with contrast, and a limit for the maximum amount. Sharpening comes last, after denoise. If it came first, denoise would remove its work, and sharpening would turn grain into texture.
Symptom: a moving robot, or a moving subject, shows ghosts after you enabled temporal denoise. Measurement: film a sharp moving bar and measure the length of its fading trail in pixels. It should be about (N − 1) times the speed. Fix: lower N while the robot moves. Many systems use the wheel odometry or the IMU to switch temporal denoise down when the robot drives, and use a stronger spatial filter instead.
Chapter 7
Watch the numbers the ISP counts, the delay before a decision lands, and the exact gain at which a loop starts to hunt
While a frame streams through the nine stages, a small counter block watches it go by. It does not change a pixel. It adds things up: the brightness of each patch of the picture, a histogram of all the values, the colour balance in each patch, a measure of how sharp the picture is. When the frame ends, those few hundred numbers are ready. Software reads them, decides, and sends new settings back for a later frame. That is the whole 3A system.
On the Raspberry Pi 4 and earlier, the ISP produces the statistics. On the Pi 5, the camera front end does, and the heavy pixel work happens afterwards. In both cases the control software runs in a fixed pattern. After each frame, a Process step reads the statistics and starts new calculations. Before the next frame, a Prepare step writes the chosen values into the ISP. The sensor settings, exposure and gain, travel to the camera by the I2C control bus. Each algorithm leaves its results in a block of metadata that travels with the frame, so later algorithms and your application can read them.
libcamera calls the software pieces that do this IPA modules (image processing algorithms). They implement the 3A loops, run on the CPU, and close the control loop around the ISP. They may run in a separate sandboxed process, with no direct access to kernel camera devices, or in a thread beside libcamera. Either way, your application sees only controls going in and metadata coming out.
Auto exposure divides the picture into regions. On the Pi 5 there are 16 by 16 regions, each with a weight from 0 (ignore) to 15. It forms a weighted mean brightness and drives it towards a target. It also checks the histogram: for example, the brightest 2% of pixels must lie above 0.5, to keep a snowy scene from turning grey. Metering happens before gamma, in linear light. Auto white balance reads the colour of each region and uses the chain in Chapter 4. Auto focus moves the lens. The Pi has a manual mode, an auto mode that scans for the sharpest position, and a continuous mode that needs phase-detect pixels.
Chapter 0 counted the delay. Call it L frames from a measurement to the first frame that shows its fix. Suppose each correction adds a fraction α of the current error. This is the loop gain. At α = 1 the controller cancels the whole measured error each time. With no delay that is perfect. With a delay it is not, because the error you measured is old, and your earlier corrections are still on their way.
This recursion is stable only when α is below 2 · sin(π / (2(2L − 1))). Work it for each delay. With L = 1 the limit is 2. With L = 2 it is 1.00. With L = 3 it is 0.62. With L = 4 it is 0.45. I checked these by running the recursion: at 0.95 of each limit the error dies away, and at 1.05 it grows without bound. So a three-frame loop must keep α below 0.62, however well it measures. The Raspberry Pi AGC code defaults to a filter speed of 0.2, and speeds up to its square root, 0.45, when near the target. Both are under the limit for a delay of 3.
Top: when frame k is measured, its fix first shows in frame k+L. Bottom: frame brightness over 120 frames, with the lights dimming 1.6 times at frame 40. The ISP loop is on. Add an application loop on top and see the gains add.
Illustrative loop with no flicker. The ISP loop has gain 0.30. The application loop reads the same brightness but sees it the stated number of extra frames late. Both multiply the same exposure. The stability limit is 2 sin(π/(2(2L−1))), checked by running the recursion.
Leave the application gain at 0 and the loop settles after the light change in about 10 frames. Raise it to 0.40 with a 3-frame delay: the two gains add to 0.70, above the 0.62 limit, and brightness swings out. The application added a loop that is also late by its own extra frames, and neither loop knows about the other. Even a gain of 0.20, which keeps the sum under the limit, never settles when the application is two frames late.
Symptom: brightness pumps up and down every few frames after you added your own exposure code, although the camera was calm before. Measurement: plot the ExposureTime and AnalogueGain metadata against frame number, along with your own commands. Two controllers writing the same value is visible. Fix: let one loop own each quantity. If your code wants control, turn the ISP’s loop off and set the values yourself. If the ISP owns them, only change its target, such as an exposure compensation, and never fight its output.
Chapter 8
Measure a camera with four numbers, tune it with a chart and a flat lamp, and find out why one golden unit is not enough
You tune one camera module on the bench. The picture looks right. You ship a thousand robots with the same settings. A week later, three complaints arrive. One robot’s video is slightly green. Another has dark corners. A third is grainy in the same light as its neighbours. Nothing is broken. The units simply differ, and your numbers came from one of them.
Signal-to-noise ratio (SNR) says how clean a flat patch is. Take the mean of the patch and divide by its standard deviation. In decibels, SNR = 20 log10(mean / noise). A patch with mean 0.30 and noise 0.01 has a ratio of 30, which is 29.5 dB.
Dynamic range says how wide a span of light the camera holds at once, from the brightest level it records without clipping to the dimmest level above its noise. If full scale is 959 codes above black and the read noise is 2 codes, the ratio is 479.5. That is 53.6 dB, or 8.9 stops.
Sharpness is measured with the modulation transfer function (MTF): how much of the contrast of a detail survives, as a function of how fine the detail is. The standard is ISO 12233. It photographs a slightly tilted edge, so that the edge crosses the pixel grid at many positions and gives a finer sample than the pixel pitch. Software such as Imatest, and test charts and software from Image Engineering, follow that standard.
Colour accuracy uses a chart of known patches, such as the 24-patch Macbeth chart that the Raspberry Pi tuning tool looks for. Convert each patch to the Lab colour space, where distance means visible difference, and take the distance to the true value. This is ΔE. Worked example: a patch reads Lab (50, 23, 14) and should read (50, 20, 10). Then ΔE = √(02 + 32 + 42) = 5. Around 1 is about the smallest difference a careful viewer sees. 5 is plainly visible.
These four numbers pull against each other. Stronger denoise raises SNR and lowers the edge score. Stronger sharpening raises the edge score and lowers SNR. A good tune sits at a balance point for the job the robot does, and the metrics tell you where you are.
The Raspberry Pi pipeline keeps every parameter of every stage in one JSON tuning file: black level, defective pixel strength, noise profile, lens-shading tables, white balance curve, colour matrices, gamma, sharpening, and the AGC modes. The guide says the Camera Tuning Tool produces a working file “from a relatively small set of calibration images”. Start from an uncalibrated file, and then fix the black level to match your sensor’s data sheet, scaled to 16 bits.
You need two kinds of pictures. First, shots of a colour chart under a range of lamps, from about 2500 K up to 8000 K, each named with its colour temperature and light level. The tool measures noise profiles, green imbalance, white balance and the colour matrices from them. Second, shots of a completely flat, uniform surface for lens shading. The guide notes that the chart usually costs under 100 pounds, a colorimeter a few hundred, and a cheap LED video lamp with a diffuser can serve as the flat field.
The settings come from the golden unit. Pick the unit you actually received. Then switch on Per-unit calibration, which refits its lens table and white balance on that unit.
Toy units: the lens corner keeps 55% (golden), 48% (unit 17) or 62% (unit 42), and red and blue sensitivity differ by about 5% in opposite directions. Targets (marks on the meters) are illustrative, not a standard. The sharpness meter is the 10 to 90% edge rise across a chart edge, a simple proxy and not an ISO 12233 MTF. Colour error is ΔE (CIE 1976) over twelve patches.
Read the numbers. The golden unit scores a colour error of 1.2 and a corner 3.1% darker than the centre. The 3% is the table’s own fitting error at the very corner. Unit 17, with the golden settings, has a corner 13.4% darker and a colour error of 4.2. Unit 42 has a corner 7.2% brighter than the table expects and a colour error of 3.6. Switch on per-unit calibration and both fall back to about 1.2 and about 3% corner error. The cost is one calibration step per unit on the production line.
Symptom: units from one batch differ in colour cast, corner brightness or grain. Measurement: shoot the same chart and the same flat field with 20 units and plot the spread of each metric. Fix: decide which parts to calibrate per unit. The lens table depends on the lens and its mounting, so refit it for each lens. When you swap a lens alone, the Pi guide offers a lens-only retune and tells you to back up the tuning file before replacing a block, since a camera may fail to start if the file is invalid.
Chapter 9
Keep the numbers, the checklist and the core code, and see where this sits among the camera lessons
You can now follow a frame from the sensor to the screen and explain every stop on the way. Nine stages clean and colour the picture, in an order that keeps each stage in the numbers it assumes. Three loops watch statistics and steer the camera, always a few frames late. Most field problems come from one of three places: a stage in the wrong order, a loop with too much gain for its delay, or a table fitted to a different unit.
| What | Number | Why it matters |
|---|---|---|
| Black level, 10-bit sensor | 64 of 1023, stored as 4096 on the Pi’s 16-bit scale | Subtract it first, in the right units |
| Flicker, 50 Hz mains | 100 Hz, period 10 ms (libcamera: 10000 µs) | Exposure of whole periods has no flicker leak |
| Flicker, 60 Hz mains | 120 Hz, period 8.33 ms (libcamera: 8333 µs) | At 30 fps a frame is exactly 4 periods |
| Flicker leak | sin(πT/P) / (πT/P); 0.21 at T = 15 ms, P = 10 ms | Zero at whole periods |
| Sensor control delay, Sony IMX477 | exposure 2 frames, gain 2, vblank 3 | Loop delay of 2 to 3 frames |
| Loop gain limit by delay | L = 2: 1.00; L = 3: 0.62; L = 4: 0.45 | 2 sin(π/(2(2L−1))) |
| Pi AGC defaults | speed 0.2; 10 startup frames; 6 convergence frames | Slow and under the limit |
| AGC metering, Pi 5 | 16 by 16 regions, weights 0 to 15 | Where in the picture the loop looks |
| Lens shading grid | 16 by 12 gains (older Pi), 32 by 32 regions (Pi 5) | One table per lens |
| Colour matrix rows | sum to 1; example row 1.80439, −0.73699, −0.06739 | Greys stay grey |
| Gamma 2.2, RAW10 to 8 bits | discards 0 bits at 1% grey, 2.6 at 50%, 3.1 at white | The curve decides where the bits go |
| Gamma slope | 5.6 at 1% grey, 0.66 at 50% | Why denoise comes before gamma |
| Temporal denoise | noise ÷ √N; ghost length (N − 1) × speed | N = 4, 9, 16 gives ÷2, ÷3, ÷4 |
| Calibration lamps | about 2500 K to 8000 K | Cover the lamps the robot will meet |
Here is a small ISP and an exposure loop in Python and NumPy. It is a sketch: raw is a [H, W] RGGB mosaic, and measure stands for whatever returns the brightness of the frame you just got back. The comments name the chapter behind each line.
pythonimport numpy as np from collections import deque def box3(a): # sum over a 3x3 window p = np.pad(a, 1) h, w = a.shape return sum(p[i:i + h, j:j + w] for i in range(3) for j in range(3)) def mini_isp(raw, black=64, full=1023, gamma=2.2): v = np.clip((raw.astype(np.float32) - black) / (full - black), 0, None) # Ch 2: black level, [H, W] h, w = v.shape yy, xx = np.mgrid[:h, :w] masks = [(yy % 2 == 0) & (xx % 2 == 0), (yy + xx) % 2 == 1, (yy % 2 == 1) & (xx % 2 == 1)] rgb = np.empty((h, w, 3), np.float32) # Ch 3: demosaic to [H, W, 3] for c, m in enumerate(masks): num, den = box3(np.where(m, v, 0)), box3(m.astype(np.float32)) rgb[..., c] = np.where(m, v, num / den) # keep known pixels, average the rest means = rgb.reshape(-1, 3).mean(0) rgb *= means[1] / means # Ch 4: grey-world gains, green stays 1 return np.clip(rgb, 0, 1) ** (1 / gamma) # Ch 5: gamma for the eye and 8 bits def split(total_ms, flicker_ms, frame_ms=33.3): # Ch 0: the Pi's flicker rule t = min(total_ms, frame_ms) periods = int(t / flicker_ms) if periods: t = periods * flicker_ms # whole flicker periods only return t, total_ms / t # gain carries the remainder def run(frames, measure, target=1.0, alpha=0.3, delay=3, flicker_ms=10.0, total=15.0): cmd, pending, log = total, deque([total] * delay), [] # Ch 7: the queue is the loop delay for k in range(frames): t, gain = split(pending.popleft(), flicker_ms) y = measure(k, t, gain) cmd *= (target / y) ** alpha # the loop gain alpha, below the limit pending.append(cmd) log.append((t, gain, y)) return log
Run mini_isp on a synthetic Bayer image and you get the three planes of the hero. Run run with delay=3, alpha=0.3 and a 10 ms flicker period, and the exposure settles to a whole number of periods with the gain carrying the rest.
The previous lesson, from sensor to CSI, ends where raw numbers reach the chip. This lesson turns them into an image. The lessons that follow take the image further: the V4L2 buffer queue, multi-camera links and low-latency video. The loop-delay idea is the same one that limits a robot’s own control loops, as in real-time performance and sensor and actuator integration. A later lesson on the SoC and its interconnect, outside this series for now, explains why a hardware ISP and a software one use memory so differently.
Now press Teach and draw the pipeline from memory: nine stages in order, with the domain of each, and the 3A round trip with its delay. Then go back to the switches at the top. Turn white balance off, then gamma, and say out loud what each was quietly doing.