Exercise: when one threshold is not enough
Before this unit: Choosing the threshold: Otsu & minimum error (previous unit); Day 1: Images, filters and frequencies.
See also: Day 3: Bit depth and noise; Day 2: Edges, blobs and ridges.
Goal
By the end of this exercise you should be able to:
- recognise when no global threshold can work, from numbers or a profile,
- correct the background by dividing or subtracting, and say which is right,
- compute mean − C and Niblack thresholds by hand, and predict where Niblack and Sauvola go wrong or right,
- choose a window size for a given image,
- run hysteresis by hand on a small grid with 4- and 8-connectivity.
Do the pen-and-paper part first, then the two demos. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.
Background
Objects are dark on a bright background in this unit (as in bright-field microscopy or text on paper): a pixel is object where I(x) < T(x).
| Method | Threshold |
|---|---|
| Background correction | threshold I/B (multiplicative illumination) or I - B (additive), B a smooth estimate of the background |
| mean − C | T = m - C, m = mean over the window |
| Niblack | T = m + k\,s, s = standard deviation over the window, k \approx -0.2 |
| Sauvola | T = m\,(1 + k(s/R - 1)), R = 128, k \approx 0.2–0.5 |
| Hysteresis | seeds > t_\text{high}; keep pixels > t_\text{low} connected to a seed |
| 4- / 8-connectivity | neighbours share a side / a side or a corner |
For bright objects, apply the same rules to the inverted image (or flip the inequalities). Borders are handled by replicating the edge pixel.
By hand
B1. In the lecture’s test image, the background has grey level about 79 at the left edge and 202 at the right edge; the dark discs are about 39 on the left and 90 on the right. (a) Show that no global threshold separates all objects from all background. (b) Divide each value by its local background. What are the corrected values of objects and background? Give one threshold that works on both sides. (c) Why is dividing right here, and not subtracting? Would subtracting also work for these four numbers?
B2. A 1 \times 10 profile on a rising background, with two dark objects: I = (100, 110, 80, 130, 140, 150, 160, 130, 180, 190). (a) A global threshold t = 125 (object where I < 125): which positions are object? Which of them are wrong? (b) Compute the local mean m with a window of 3 (borders replicated), and the mean − C threshold with C = 10. Which positions are object? (c) The local standard deviations are s = (4.7, 12.5, 20.6, 26.2, 8.2, 8.2, 12.5, 20.6, 26.2, 4.7). Compute the Niblack threshold m - 0.2\,s at positions 1, 3 and 8. Which positions does Niblack call object?
B3. Niblack and Sauvola in empty background: grey level 200, noise standard deviation 6, no objects in the window. (a) Niblack with k = -0.2: which fraction of the pixels becomes object? Does it depend on the noise level? (A normal variable is more than 0.2 standard deviations below its mean with probability 0.42.) (b) Sauvola with k = 0.3, R = 128: compute T. Is any background pixel below it? (c) Sauvola at an object edge where the window has m = 150 and s = 50: compute T. Is an object pixel of 90 found? A background pixel of 200?
B4. Window size. The image has dark discs with diameters from 8 to 45 pixels, and the illumination changes smoothly over the whole 256-pixel width. (a) What happens at the centre of a disc of diameter 45 with an 11 \times 11 window? Draw the mask you expect. (b) What happens with a 241 \times 241 window? (c) Suggest a window size.
B5. Hysteresis on a 6 \times 6 grid with t_\text{low} = 50 and t_\text{high} = 80 (object where I > threshold here: bright structures): \begin{bmatrix} 10&10&10&10&10&10\\ 10&90&60&10&10&10\\ 10&10&60&10&70&10\\ 10&10&10&60&10&10\\ 10&10&10&60&10&50\\ 10&70&10&10&10&60 \end{bmatrix} (a) Which pixels are seeds? Which are above t_\text{low}? (b) Run hysteresis with 4-connectivity: which pixels are kept? (c) The same with 8-connectivity. (d) Compare with single thresholds at 50 and at 80.
B6. Which remedy would you choose, and why? (a) A slide scanned with a strong shadow across one corner; the cells are round, 20 pixels across. (b) Retinal blood vessels that get thinner and fainter towards their ends. (c) Noisy bright nuclei on a flat background: the histogram has two peaks, but the masks are full of isolated wrong pixels.
B1. (a) Every object must be below t and every background pixel above it: t > 90 (the right objects) and t < 79 (the left background). Impossible. (b) Left: object 39/79 = 0.49, background 1; right: object 90/202 = 0.45, background 1. Any threshold between about 0.5 and 0.9, e.g. 0.75, works on both sides. (c) The light multiplies the scene: the objects are about half as bright as their background everywhere, but the difference background − object grows with the light (40 on the left, 112 on the right). Subtracting gives -40 and -112 for the objects: a threshold between -40 and 0 (e.g. -20) still works for these four numbers, but the margin on the dim side is small, and noise or fainter objects would break it. Dividing makes the contrast equal on both sides.
B2. (a) Positions 1, 2, 3 (100, 110, 80). Positions 1 and 2 are background on the dark side of the ramp (false positives), and the object at position 8 (130) is missed. (b) m = (103.3, 96.7, 106.7, 116.7, 140.0, 150.0, 146.7, 156.7, 166.7, 186.7) and T = m - 10 = (93.3, 86.7, 96.7, 106.7, 130.0, 140.0, 136.7, 146.7, 156.7, 176.7). Object where I < T: positions 3 (80 < 96.7) and 8 (130 < 146.7). Exactly the two objects. (c) Position 1: 103.3 - 0.94 = 102.4, and 100 < 102.4: object. Position 3: 106.7 - 4.1 = 102.6: object. Position 8: 156.7 - 4.1 = 152.6: object. Niblack finds both objects but also calls position 1 object: in its flat window (100, 100, 110) the threshold sits just below the mean, and a pixel slightly darker than its neighbours crosses it.
B3. (a) Object where I < 200 - 0.2 \cdot 6, i.e. more than 0.2 standard deviations below the mean: 42 % of the pixels, whatever the noise level (the threshold scales with s = \sigma_n). (b) T = 200\,(1 + 0.3(6/128 - 1)) = 142.8, which is 57.2/6 = 9.5 noise standard deviations below 200: no background pixel. (c) T = 150\,(1 + 0.3(50/128 - 1)) = 122.6. The object pixel (90 < 122.6) is found, the background pixel (200) is not.
B4. (a) The 11 \times 11 window around the centre lies entirely inside the disc: its mean is the disc’s own grey level, so the centre is not darker than its surroundings and is not object. Only a ring near the edge, where the window also sees background, is found: a hollow disc. (In the demo: Dice 0.602.) (b) The window covers almost the whole image: the threshold is nearly constant, a global threshold again, and on the dim side the background becomes object. (c) About twice the largest diameter, and well below the 256-pixel scale of the illumination: 51 \times 51 to 81 \times 81.
B5. (a) Seed: only the 90 at row 2, column 2 (rows and columns counted from 1). Above 50: the 90, the three 60s at (2,3), (3,3), (4,4), the 60 at (5,4), the 70 at (3,5), the 70 at (6,2) and the 60 at (6,6): 8 pixels (the 50 is not above 50). (b) 4-connectivity from the seed: (2,2) → (2,3) → (3,3). The 60 at (4,4) touches (3,3) only at a corner. Kept: 3 pixels. (c) 8-connectivity: also (4,4) (corner of (3,3)), then (5,4) below it, and the 70 at (3,5) (corner of (4,4)). Kept: 6 pixels. The 70 at (6,2) and the 60 at (6,6) have no path to the seed: rejected. (d) Single threshold 80: only the seed, 1 pixel; the diagonal structure is lost. Single threshold 50: 8 pixels, including the two isolated ones. Hysteresis with 8-connectivity keeps the structure and drops the isolated pixels.
B6. (a) Background correction (divide by a heavily blurred image or a fitted surface), or a local threshold with a window of about 40–60 pixels: larger than the cells, smaller than the shadow. (b) Hysteresis: the bright trunks give seeds, and the faint, thin ends are kept because they are connected to them. (c) Smoothing before thresholding, or a method in which neighbours agree (graph cuts); a local threshold does not help, since the problem is noise, not the background.
Math questions
B7. (math) Show that the local variance is s^2 = \text{box}(I^2) - \text{box}(I)^2. Check it for the window (100, 100, 110) of B2.
B8. (math) Model a flat background as I = \mu_b + n with Gaussian noise n \sim \mathcal N(0, \sigma_n^2), so that m \approx \mu_b and s \approx \sigma_n. Show that the fraction of background pixels that Niblack labels object is \Phi(k), independent of \mu_b and \sigma_n. For Sauvola, show that no background pixel is labelled object as long as \mu_b\,k(1 - \sigma_n/R) \gg \sigma_n.
B9. (math) An image I = L\,R + n with a smooth illumination L(x). Show that dividing by L makes the object/background contrast independent of x, and compute how the noise standard deviation of I/L depends on L. Where is the corrected image noisiest?
B10. (math) A running sum along a row with window 2r + 1: show S(x + 1) = S(x) + I(x + r + 1) - I(x - r), and count the additions needed for a whole N_x \times N_y image (rows, then columns). Why does it not depend on r?
B7. s^2 = \frac1n\sum_j(I_j - m)^2 = \frac1n\sum_j I_j^2 - 2m\frac1n\sum_j I_j + m^2 = \frac1n\sum_j I_j^2 - m^2. For (100, 100, 110): m = 103.33, \frac13(10\,000 + 10\,000 + 12\,100) = 10\,700, s^2 = 10\,700 - 10\,677.8 = 22.2, s = 4.71.
B8. Niblack: object if \mu_b + n < \mu_b + k\sigma_n, i.e. n/\sigma_n < k, probability \Phi(k) for a standard normal n/\sigma_n; \mu_b and \sigma_n drop out. Sauvola: T = \mu_b(1 + k(\sigma_n/R - 1)) = \mu_b - \mu_b k(1 - \sigma_n/R); a background pixel is below T only if n < -\mu_b k(1 - \sigma_n/R), which is negligible when that margin is many noise standard deviations.
B9. I/L = R + n/L: the object/background difference of R is the same everywhere. The noise term n/L has standard deviation \sigma_n/L(x): largest where the light is weakest (the dark side and the vignetted corners). Correction makes the contrast uniform, not the noise.
B10. S(x) = \sum_{j = x - r}^{x + r} I(j) and S(x + 1) = \sum_{j = x - r + 1}^{x + r + 1} I(j): the windows share all terms except I(x - r) (leaves) and I(x + r + 1) (enters). After the first sum each output costs 2 additions, so a row pass costs about 2N_x per row and the image 2N_xN_y; the column pass the same: 4N in total, independent of r.
Explore: local thresholds
The test image has dark discs of several sizes (ground truth known) on a bright background, lit by a light ramp (dim on the left) and a vignette, plus noise; or the micrograph with an artificial shading (no ground truth). Left: the mask (orange) of the selected method; click or drag on the image to move the blue row. Top right: the grey levels I along that row and the threshold T, with the true discs shaded. Bottom: the threshold surface T(x) as an image, and the readout: Dice against the ground truth (1 = perfect), false positives (FP) and false negatives (FN). window r sets a (2r + 1) \times (2r + 1) window; bg. scale is the size of the blur used to estimate the background.
E1. Preset global Otsu fails. Read Otsu’s threshold and Dice. Where are the errors? Set light ramp and vignette to 0: what happens? Then set the light ramp to 0.5.
E2. Preset divide by the background. Read Dice and the threshold. Change bg. scale to 10 and to 60. Why is each worse than 30?
E3. Choose mean − C with C = 10 and vary the window: r = 5, 12, 25, 40, 120 (windows 11 to 241). Record Dice and describe the masks. Which window is best? Compare with B4.
E4. Preset Niblack in empty background. Where are the false positives? Read FP. Change k to 0 and to -0.5. Explain with B3.
E5. Preset Sauvola fixes it. Read Dice, FP and FN. Change k to 0.1 and 0.5: which error grows in each case?
E6. Raise noise σ to 20 with Sauvola and with Niblack (k = -0.2). Which suffers more? Does a larger window help?
E7. Preset micrograph, shaded. Compare global Otsu with Sauvola by eye: which parts of the cell does each find on the dim left side?
E1. Otsu chooses t = 127 with Dice 0.701: 14 516 false positives, nearly all on the dim left side, where the background (about 79) is below the threshold; only 196 object pixels are missed. Without ramp and vignette Otsu works: t = 121, Dice 0.997. With a ramp of 0.5 it already drops to 0.820 (7513 false positives).
E2. Dice 0.982 with a threshold of 0.85 \times the background estimate. With bg. scale 10 the “background” follows the discs too closely (the blur is about the size of the discs), so the large discs pull the estimate down and their centres are lost: Dice 0.969, FN rises to 707. With 60 the estimate is too smooth to follow the vignette and the ramp near the corners: Dice 0.917, FP 3049.
E3. r = 5: 0.602, hollow large discs (FN 9259). r = 12: 0.879, the largest discs still hollow (FN 2961). r = 25: 0.973. r = 40: 0.975, the best. r = 120: 0.897, almost global: FP 3994 on the dim side. As in B4: larger than the discs, smaller than the illumination change.
E4. The false positives are speckle in the empty background, wherever the window contains no disc; FP = 3180 (Dice 0.913). Near the discs the window’s standard deviation is large and the threshold drops well below the background, so the speckle is confined to the empty stretches. With k = 0 (threshold = local mean) half of the empty background crosses: FP 5389, Dice 0.865. With k = -0.5: FP 1448 but FN 591, Dice 0.943. In empty background Niblack’s threshold sits |k| noise standard deviations below the mean, so a fixed fraction \Phi(k) of the background is always wrong (B3).
E5. Dice 0.976, FP 12, FN 797. With k = 0.1 the threshold sits closer to the mean: FP rises to 903 (Dice 0.971). With k = 0.5 it is far below the mean: FN rises to 3453 (Dice 0.890), the edges and the faint parts of the discs are lost.
E6. Sauvola falls to 0.882, Niblack to 0.789 (FP 7674): Niblack’s speckle grows with the noise, Sauvola’s margin m\,k(1 - s/R) stays large. A larger window does not remove pixel noise (it only stabilises m and s); smoothing the image first, or neighbours agreeing, would.
E7. Global Otsu (t = 160) labels the whole dim left third as object, empty background included, and on the bright right side only the darkest material. Sauvola keeps most of the empty background on the left as background and marks what is darker than its surroundings on both sides: the band of cytoplasm on the left, the nuclear envelope and dark clumps. Inside the large nucleus it finds only scattered texture, because there the window sees no background to compare with.
Explore: hysteresis
Top: a 1D profile: a structure that fades from bright to faint, a faint separate bump, and noise. Drag the two horizontal lines (t_\text{high} red, t_\text{low} blue). Red points are seeds, orange are kept (above t_\text{low} and connected to a seed along the line), blue are rejected. Bottom: a 128 \times 128 image of faint filaments that fade along their length (synthetic), with the hysteresis result (left) and the two single thresholds (right). 4-/8-connected chooses the neighbourhood.
H1. Preset hysteresis keeps both ends. On the 1D profile: which interval is kept? What happens to the faint bump around position 160, and why?
H2. Compare the presets high alone and low alone with hysteresis: the number of pixels in the final mask, and what the masks look like.
H3. Switch to 4-connected. How many more pixels are rejected? Where?
H4. Lower t_\text{low} to 50. What happens to the number of rejected pixels and to the final mask? Why is a too low t_\text{low} dangerous even with hysteresis?
H5. Preset edge strength of the micrograph (the Sobel magnitude, as in Canny on the edges day). Which edges survive? Raise t_\text{high}: what disappears first?
H1. Positions 25–110: the whole fading structure, from its bright start to where it sinks below t_\text{low} = 62. t_\text{high} alone breaks it into pieces (25–59, 61–73, 75–82 and a few single points) because noise dips below 105. The faint bump (about 150–175) is above t_\text{low} in several pieces but never above t_\text{high}: no seed, so it is rejected. Hysteresis cannot find a faint object that has no bright part.
H2. High alone: 621 pixels, only the bright halves of the filaments, broken into pieces. Low alone: 1412 pixels, the whole filaments plus scattered speckle. Hysteresis: 1311 pixels: the full filaments (to their faint ends), and 101 rejected pixels, mostly isolated speckle.
H3. 112 rejected instead of 101: 11 more. They are pixels on diagonal stretches of the thin filaments, connected to the rest only through a corner.
H4. 752 rejected and 1670 kept: the noise speckle next to the filaments now touches them and is kept, so the filaments grow ragged side branches. Hysteresis only rejects noise that is not connected to a seed; if t_\text{low} is so low that noise forms bridges to the real structure, the noise is kept.
H5. With t_\text{low} = 120, t_\text{high} = 220: 790 seeds, 3619 pixels kept, 821 rejected. The strong edges (the outline of the cell, the dark granules and membranes) are kept as connected networks, together with the weaker edges attached to them; isolated weak texture edges are rejected (blue). Raising t_\text{high} removes whole chains at once: first those that contain no very strong pixel.
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in thresholding/src/local_threshold/exercise.rs.
As in the exercises, objects are dark (object where I < T), and pixels outside the image copy the edge pixel.
C1. local_mean_std(img, r): the mean m and the standard deviation s over the (2r + 1) \times (2r + 1) window around every pixel, from two box sums (slide “Local mean and variance are box filters”), each made in two passes:
for every pixel (x, y): # pass 1: along the row
S1(x, y) = sum of I(x + d, y) for d = −r … r
S2(x, y) = sum of I(x + d, y)² for d = −r … r
for every pixel (x, y): # pass 2: along the column
n = (2r + 1)²
m(x, y) = (sum of S1(x, y + d) for d = −r … r) / n
s(x, y) = sqrt( (sum of S2(x, y + d) for d = −r … r) / n − m(x, y)² )
The checks are B2 (the means and standard deviations of the profile, window 3) and B7.
C2. rule_threshold(rule, m, s): the threshold of mean − C, Niblack or Sauvola for one pixel. The checks are B3 (a)–(c). C3. local_threshold(img, r, rule): object where I(x) < T(x). The checks are B2 (b) (mean − C finds positions 3 and 8) and B2 (c) (Niblack also position 1).
C4. hysteresis(img, low, high, eight), for bright structures:
kept = seeds = the pixels above t_high; put the seeds on a stack
while the stack is not empty:
take a pixel p from the stack
for every neighbour q of p (4 or 8):
if q is inside the image, not kept, and above t_low:
mark q kept; put q on the stack
The checks are B5 (b), (c) and (d): 3 pixels with 4-connectivity, 6 with 8.
Then cargo run -p thresholding -- local-threshold and open the pictures in out/local-threshold/. The program makes dark discs (radius 4 to 22) on a background lit from about 79 on the left to 202 on the right, with vignetting and noise (discs.png), and prints the false positives (FP) and false negatives (FN) of each method against the truth. It also runs hysteresis on faint filaments.
C5. The program tries every global threshold and keeps the best. How many errors remain, and where (global.png)? Compare with dividing by the background, and with mean − C for the windows 11 \times 11, 51 \times 51, 81 \times 81 and 241 \times 241 (mean-c-r5.png … mean-c-r120.png). Which window fails as in B4 (a), and which as in B4 (b)?
C6. Niblack and Sauvola with the same 51 \times 51 window: compare their false positives, and find them in niblack.png. Which question of the by-hand part predicts this?
C7. The filaments (filaments.png, thresholds 0.30 and 0.55): compare the pixel counts of the two single thresholds with hysteresis, and look at the three masks. Why does hysteresis with 4-connectivity keep fewer pixels than with 8?
The model solution is thresholding/src/local_threshold/solution.rs in the download.
C5. The best global threshold (60) misses 5357 object pixels and adds 154: only the discs on the dim left side are found, because on the bright side even the discs are brighter than 60. Dividing by the background (a 61 \times 61 mean) and thresholding the ratio at 0.85 gives 52 FP and 0 FN. Mean − C: 11 \times 11 gives 3808 FN, with the large discs as hollow rings (B4 (a)); 51 \times 51 (84 FP, 0 FN) and 81 \times 81 (142 FP, 0 FN) work; 241 \times 241 is nearly global again, and the dim left edge and the dark corners become object: 3435 FP (B4 (b)).
C6. Niblack: 6206 FP; Sauvola: 0 FP (and 1 FN). Niblack’s false positives are speckle in the empty background, away from the discs: there its threshold sits just below the local mean, and a fixed fraction of the noisy background falls below it (B3 (a)). Sauvola’s threshold lies far below the mean in flat regions (B3 (b)).
C7. Above the high threshold: 401 pixels, the filaments only on their bright halves; above the low threshold: 588, the whole filaments plus scattered noise pixels; hysteresis: 537 with 8-connectivity, the whole filaments without the isolated noise. With 4-connectivity it keeps 507: the thin curves step diagonally in places, and the pixels after such a step are not connected to a seed through a side.
Where this leads
Local thresholds and hysteresis still decide pixel by pixel. Graph cuts (day 27) let neighbouring pixels agree through an explicit energy, with thresholding as its \lambda = 0 case; the top-hat (day 13) gives a background estimate that is not pulled by the objects; and connected components (day 14) is the algorithm behind hysteresis. Next unit: how do we know a segmentation is good? We measure it against the ground truth.