Exercise: histograms and a global threshold

Goal

By the end of this exercise you should be able to:

  • compute a histogram, its normalised and cumulative versions, and threshold a small image by hand,
  • read the mask area and a percentile threshold off the cumulative histogram,
  • explain why a threshold in a deep valley is robust and one in a shallow valley is not,
  • predict what noise, smoothing and the number of bins do to the histogram and to the mask.

Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.

Background

Word Meaning
Binary mask B(x) = 1 (object) where I(x) > t, else 0 (background)
Histogram h_i = number of pixels with grey level i (or in bin i)
Normalised histogram p_i = h_i / N, N = number of pixels; \sum_i p_i = 1
Cumulative histogram P(t) = \sum_{i \le t} p_i: the fraction of pixels a threshold at t calls background
Mask area 1 - P(t)
Percentile threshold the t with P(t) = 1 - q: keep the brightest fraction q
Ground truth the true mask (known for synthetic images, drawn by hand for real ones)

By hand

B1. A 5 \times 5 image with grey levels 0–7: I = \begin{bmatrix} 0&1&1&2&1\\ 1&6&7&6&2\\ 1&7&5&6&1\\ 2&6&6&3&0\\ 1&2&1&0&4 \end{bmatrix} (a) Draw the histogram h_i, the normalised histogram p_i and the cumulative histogram P(t). (b) Threshold at t = 3 and at t = 4 (object where I > t). How many object pixels does each give, and which pixels change? Why is the change small? (c) Compare t = 1 with t = 2. Which threshold would you trust more, and why?

B2. A 256 \times 256 image: background grey level 50 (75 % of the pixels), objects 110 (25 %), plus Gaussian noise with standard deviation \sigma_n = 20. The threshold is t = 80. (a) Which fraction of the background pixels ends up above t, and of the object pixels below t? How many wrong pixels is that in total? (A normal variable lies more than 1.5 standard deviations above its mean with probability 0.0668.) (b) The image is smoothed first with a 3 \times 3 mean. What is the noise now, and roughly how many wrong pixels remain? (More than 4.5 standard deviations: probability 3.4 \cdot 10^{-6}.) (c) Which pixels does (b) ignore, that will in fact be wrong after smoothing?

B3. A 12-bit camera stores its images in a 16-bit container (grey levels 0–4095 out of 0–65 535). (a) You make a histogram with 256 equal bins over 0–65 535. How many bins contain data? (b) Suggest two better choices of bins.

B4. In a 512 \times 512 fluorescence image, spots cover about 2 % of the pixels. The cumulative histogram gives P(100) = 0.950, P(110) = 0.968, P(120) = 0.980, P(130) = 0.988. (a) Which threshold keeps the brightest 2 %? How many pixels is that? (b) In the next image of the series the cells are more active and spots cover 4 %. What does the same percentile rule do now?

B5. In the demo’s synthetic image (25 % objects) the mask area is 25.8 % at t = 100 and 22.3 % at t = 130. After adding strong noise (\sigma_n = 35) it is 33.8 % and 20.5 %. (a) How many pixels per thousand change label per grey level of t in each case? (b) Which image’s segmentation depends more on the exact choice of t, and by what factor? What does that tell you about its histogram between 100 and 130?

B6. A 3 \times 3 window of a dark background contains one hot pixel: 50, 52, 48, 51, 250, 49, 50, 53, 47 (the 250 in the centre). (a) Compute the mean and the median of the window. (b) The image is thresholded at t = 60 after a 3 \times 3 mean. What happens around the hot pixel? And after a 3 \times 3 median?

B7. You shuffle the pixels of an image to random positions. Which of these change: the histogram, the mask area at t = 100, the shape of the mask, the best threshold according to a method that uses only the histogram?

B1. (a) Counts h = (3, 8, 4, 1, 1, 1, 5, 2) for grey levels 0–7 (sum 25). Normalised: p = (0.12, 0.32, 0.16, 0.04, 0.04, 0.04, 0.20, 0.08). Cumulative: P = (0.12, 0.44, 0.60, 0.64, 0.68, 0.72, 0.92, 1.00). (b) t = 3: the 9 pixels with grey level 4–7 (the 3 \times 3 bright block except the 3, plus the 4 in the bottom-right corner). t = 4: 8 pixels; only the single 4 in the corner changes. The change is small because there is only one pixel at grey level 4: t moves inside the valley of the histogram (levels 3, 4, 5 have one pixel each). (c) t = 1 gives 14 object pixels, t = 2 gives 10: the four 2s change, the edge of the dark peak. A threshold in the valley (3 or 4) is more trustworthy: moving it by one changes one pixel, not four.

B2. (a) 80 is 1.5 standard deviations from both means: 6.68 % of each class is wrong. That is 0.0668 \cdot 49\,152 = 3284 background pixels and 0.0668 \cdot 16\,384 = 1095 object pixels: about 4378 wrong pixels, scattered as salt and pepper. (b) The mean of 9 independent noise values has \sigma = 20/3 = 6.7. Now 80 is 4.5 standard deviations away: 3.4 \cdot 10^{-6} \cdot 65\,536 \approx 0.2, so essentially no pixel inside the objects or the background is wrong. (c) The pixels near the edges: their 3 \times 3 window contains both object and background, so their mean lies between 50 and 110 (partial volume). Those near 80 can go either way; the boundary becomes less precise.

B3. (a) The bin width is 65\,536/256 = 256, so 0–4095 fall into the first 4096/256 = 16 bins; the other 240 bins are empty. The histogram has 16 coarse bars: any valley is invisible. (b) One bin per grey level over 0–4095 (4096 bins), or 256 bins over the actual range of the data [\min, \max] (width 16 for the full 12-bit range). With few pixels per bin, prefer fewer bins.

B4. (a) P(t) = 1 - 0.02 = 0.98 at t = 120. That keeps 0.02 \cdot 262\,144 \approx 5243 pixels. (b) It still keeps the brightest 2 %, i.e. about half of the spot pixels: the threshold rises into the spots. The percentile rule assumes the object fraction, so it is only safe when that fraction is known and stable.

B5. (a) Clean: (25.8 - 22.3)\,\% / 30 = 0.117\,\%, i.e. 1.2 pixels per thousand per grey level. Noisy: (33.8 - 20.5)\,\% / 30 = 0.443\,\%, i.e. 4.4 per thousand. (b) The noisy one, 3.8 times as sensitive. The change of the area per grey level is the histogram at t: the clean histogram has a deep valley between 100 and 130, the noisy one has pixels everywhere there.

B6. (a) Mean 650/9 = 72.2, median 50. (b) After the mean, every window that contains the hot pixel (the 9 windows around it) has a mean near 72: a 3 \times 3 object appears around the hot pixel. The mean spreads the outlier instead of removing it. After the median every window gives about 50: the hot pixel disappears.

B7. Unchanged: the histogram (the same grey levels), hence the mask area at any t and the threshold of any histogram method. Changed: the shape of the mask, which becomes scattered pixels instead of blobs.

Math questions

B8. (math) Show that \sigma^2 = \sum_i (i - \mu)^2 p_i = \sum_i i^2 p_i - \mu^2. Compute \mu and \sigma^2 for the image of B1.

B9. (math) Noise values n_1, \dots, n_n are independent with variance \sigma^2, and \bar n = \sum_k w_k n_k with \sum_k w_k = 1. Show that \operatorname{Var}(\bar n) = \sigma^2 \sum_k w_k^2, and that among all weights with \sum_k w_k = 1 the equal weights w_k = 1/n make it smallest.

B10. (math) Let A(t) = 1 - P(t) be the mask area. Show that A(t) - A(t + 1) = p_{t+1}, and for continuous grey levels with density p(x) that A'(t) = -p(t). Use it to explain B5.

B8. Expand: \sum_i (i - \mu)^2 p_i = \sum_i i^2 p_i - 2\mu \sum_i i\,p_i + \mu^2 \sum_i p_i = \sum_i i^2 p_i - 2\mu^2 + \mu^2. For B1: \mu = \sum_i i\,p_i = 72/25 = 2.88; \sum_i i^2 p_i = 352/25 = 14.08; \sigma^2 = 14.08 - 2.88^2 = 5.79.

B9. For independent variables the variances add: \operatorname{Var}(\sum_k w_k n_k) = \sum_k w_k^2 \operatorname{Var}(n_k) = \sigma^2 \sum_k w_k^2. Minimise \sum_k w_k^2 subject to \sum_k w_k = 1: the Lagrange condition 2w_k = \lambda makes all weights equal, w_k = 1/n, with \sum_k w_k^2 = 1/n. (Or by Cauchy–Schwarz: 1 = (\sum_k w_k)^2 \le n \sum_k w_k^2.)

B10. A(t) = \sum_{i > t} p_i, so A(t) - A(t + 1) = \sum_{i > t} p_i - \sum_{i > t + 1} p_i = p_{t+1}. Continuously, A(t) = \int_t^\infty p(x)\,dx and A'(t) = -p(t) by the fundamental theorem of calculus. In B5 the average slope between 100 and 130 is the average histogram height there: 1.2 per thousand per grey level for the clean image, 4.4 for the noisy one.

Explore

The demo shows an image (left) with the mask in orange, its histogram (top right) and the mask area 1 - P(t) as a function of t (bottom right). Drag the threshold on either plot, or use the slider. The synthetic image has bright blobs covering exactly 25 % of the pixels on a dark background; its ground truth is known, so the readout gives the Dice coefficient (1 = the mask is perfect; defined in the evaluation unit). noise σ adds Gaussian noise; median 3×3 and blur σ smooth the image before the histogram is made; bins sets the number of histogram bins; P(t) adds the cumulative histogram to both plots; dark objects makes the mask I \le t.

E1. Preset clean bimodal. Read the mask area and Dice at t = 120. Move t to 100 and to 130: how much do the mask area and Dice change? Find the t with the highest Dice.

E2. Tick P(t). Where does the cumulative curve rise steeply, and where is it flat? Relate this to the peaks and the valley of the histogram.

E3. Preset noise fills the valley. Where is the valley now? Read Dice at t = 110, and find the best t. Then preset blur restores it: Dice at t = 110? Instead of the blur, try median 3×3 (blur σ = 0), then blur σ = 3. Which works best, and why is σ = 3 worse than σ = 1.5?

E4. Preset too few bins (8 bins). Can you see two peaks? Raise the bins to 32 and 256. Which number of bins shows the structure best for this 256 \times 256 image? Tick log scale: what does it reveal?

E5. Preset percentile: brightest 25 % (noise 35). Which t does it choose, and how does its Dice compare with the best you found in E3? Why does this work here, and when would it fail?

E6. Preset the micrograph (an electron micrograph: the cell is darker than the empty background, so dark objects is on). Describe the histogram. Is there a clear valley? What does the mask contain at t = 150?

E1. At t = 120: mask area 23.7 % (truth: 25 %), Dice 0.974. At t = 100: 25.8 %, Dice 0.983; at t = 130: 22.3 %, Dice 0.942. Thirty grey levels move only 3.5 % of the pixels, because t is in the valley. The best Dice is 0.991 at t = 108.

E2. P(t) rises steeply through each peak (most steeply in the background peak around 60, where 75 % of the pixels sit) and is almost flat in the valley between about 90 and 140 and above 190. Its slope is the histogram, and the mask area is its mirror image 1 - P(t).

E3. With noise 35 the two peaks merge into one broad hump with a shoulder; there is no valley. Dice at t = 110 is 0.813; the best is 0.823 at t = 119. After a Gaussian blur with σ = 1.5 the valley is back and Dice at t = 110 is 0.970. The 3 \times 3 median gives 0.960, a bit worse here (the noise is Gaussian, which averaging handles best). With σ = 3 the best Dice falls to 0.949 (0.936 at t = 110): the blur now smears the edges of the blobs over several pixels, and these partial-volume pixels fill the valley again.

E4. With 8 bins (width 32) the histogram is a staircase: a big bar for the background and a falling tail, with no visible second peak. With 32 bins both peaks and the valley appear; 256 bins also show them, but more ragged (about 256 pixels per bin on average). 32–64 bins are a good compromise here. The log scale makes small counts visible: the long tails of the peaks and the few pixels in the valley.

E5. It chooses t = 119 (the smallest t with P(t) \ge 0.75), with Dice 0.823, the same as the best threshold of E3. It works because the objects really cover 25 % of this image. In an image with a different object fraction it would keep the wrong number of pixels, however clear the valley is.

E6. The histogram is broad: it rises from about 50 to a plateau between 100 and 200 and has a peak near 240, the empty background. There is no deep valley; the cell (cytoplasm, nucleus, dark membranes) spreads over most grey levels. At t = 150 the mask holds 39.7 % of the pixels: the cell, its dark membranes and the dark material outside it, with a ragged boundary where texture crosses the threshold. A single threshold cannot pick out the nucleus: it has the same grey levels as the cytoplasm.

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/histogram/exercise.rs.

Grey values are between 0 and 1 in the code. A histogram with bins bins puts the value v into bin \lfloor v \cdot \text{bins} \rfloor (the value 1 into the last bin); with 256 bins an 8-bit grey level k lands in bin k. A threshold t is a bin number: object where the pixel’s bin is above t.

C1. histogram(img, bins): count the pixels in every bin.

h = (0, 0, …, 0)                    # one count per bin
for every pixel (x, y):
    i = bin of I(x, y)
    h[i] = h[i] + 1

C2. cumulative(h): the normalised cumulative histogram, P(t) = the fraction of pixels in bins 0, \dots, t (a running sum divided by N). C3. threshold(img, bins, t): the mask, true where the bin is above t. The checks are B1 (a), (b) and (c); they store the grey level i of B1 as i/8, so that it lands in bin i of 8 bins.

C4. percentile_threshold(h, q): the smallest t that leaves at most a fraction q of the pixels above it. Count in pixels, not in fractions:

above = N                           # all pixels are above "t = −1"
for t = 0, 1, 2, …:
    above = above − h[t]
    if above ≤ q · N: return t

The check is B4 (a): a histogram with the cumulative values of B4 gives t = 120.

C5. mean_variance(h): \mu = \sum_i i\,p_i and \sigma^2 = \sum_i (i - \mu)^2 p_i, in bin numbers. The check is B8: 2.88 and 5.79.

Then cargo run -p thresholding -- histogram and open the pictures in out/histogram/. The program makes synthetic images of bright discs on 25 % of the pixels (the truth is known), thresholds them and counts the wrong pixels. Histograms are drawn with the threshold as a grey line.

C6. The clean image (background 60, objects 160, noise 10): the program prints the mask area for t = 100, 110, 120, 130. How much does it change, and why? Look at blobs-histogram.png.

C7. The image of B2 (background 50, objects 110, noise 20, t = 80). Compare the number of wrong pixels with your answer to B2 (a), and after the 3 \times 3 mean with B2 (b). Open smooth-wrong.png (white = wrong): where are the wrong pixels that remain? Compare noisy-histogram.png with smooth-histogram.png.

The model solution is thresholding/src/histogram/solution.rs in the download.

C6. The mask area is 25.00 % at t = 100, 110 and 120 and 24.96 % at 130: thirty grey levels move almost no pixel (2 wrong pixels at 100, none at 110 and 120, 27 at 130). The two peaks, at 60 and 160 with noise 10, leave an empty valley between them: the area changes by the histogram at t, which is 0 there (B10).

C7. 4267 wrong pixels at t = 80, close to the 4378 of B2 (a) (the exact number varies with the noise). After the 3 \times 3 mean, 711 wrong pixels remain, far more than the 0.2 of B2 (b): they all lie on the outlines of the discs, where the window mixes object and background (B2 (c), partial volume). The noisy histogram is one broad peak with a shoulder, and the threshold sits on its flank; after the mean there are two narrow peaks and the threshold sits in a valley. (The tall bar at grey level 0 in the noisy histogram holds the pixels that the noise pushed below 0.)

Where this leads

So far t was chosen by eye. The next unit chooses it from the histogram: Otsu’s method makes the two classes as tight as possible, and the minimum-error threshold models the histogram as two normal distributions and puts t where they cross.