Exercise: texture and co-occurrence matrices

Goal

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

  • build the symmetric, normalised co-occurrence matrix of a small image for a given offset,
  • compute contrast, homogeneity, ASM, entropy and correlation from it,
  • predict how the features change with the angle, the distance and the number of grey levels,
  • compute a local binary pattern code and its rotation-invariant version.

Do the pen-and-paper part first, then the demo.

Background

Idea What it means
Offset distance d and angle: 0° = (d, 0) to the right, 45° = (d, -d), 90° = (0, -d) up, 135° = (-d, -d); y points down
Co-occurrence count P(i, j) number of pixels with level i whose partner at the offset has level j (both inside the image)
Symmetric P + P^\top: every pair counted both ways
p(i, j) P divided by its sum
Contrast \sum (i-j)^2 p
Homogeneity \sum p / (1 + (i-j)^2)
ASM, energy \sum p^2, \sqrt{\text{ASM}}
Entropy -\sum p \log_2 p (bits)
Correlation \sum (i-\mu)(j-\mu)\,p / \sigma^2 with \mu = \sum i\,p, \sigma^2 = \sum (i-\mu)^2 p (symmetric p)
LBP 8 neighbours clockwise from the top-left, bit 1 if neighbour ≥ centre, read as a binary number (first bit most significant)

By hand

I = \begin{bmatrix} 0 & 0 & 1 & 1 \\ 0 & 0 & 1 & 1 \\ 0 & 2 & 2 & 2 \\ 2 & 2 & 2 & 2 \end{bmatrix} \qquad (L = 3 \text{ levels})

B1. Offset 0°, d = 1 (partner to the right). (a) List the counts of the 12 horizontal pairs and build the symmetric matrix P (3 \times 3, sum 24). (b) Compute contrast, homogeneity and ASM. (c) Compute the entropy. (Use \log_2; a calculator is fine.) (d) Compute \mu, \sigma^2 and the correlation.

B2. Offset 90°, d = 1 (partner above). (a) Build the symmetric matrix. (b) Compute contrast and homogeneity. Which direction has more contrast, and what in the image explains it?

B3. The same image at 45° (d = 1, partner up and to the right) has the symmetric matrix \begin{bmatrix} 4 & 1 & 0 \\ 1 & 2 & 2 \\ 0 & 2 & 6 \end{bmatrix}. Why does it sum to 18 and not 24? Compute its contrast.

B4. Two 4 \times 4 binary images with the same histogram (8 zeros, 8 ones): a checkerboard, and “halves” (every row is 0 0 1 1). (a) Build the symmetric GLCM at 0°, d = 1, for both. (b) Compute contrast and correlation for both. Which features would separate them, which would not? (c) At 90°, what is the GLCM of the halves image?

B5. Vertical stripes with a period of 8 pixels (the value depends only on x, repeating every 8 columns). For which d at 0° is the contrast zero? At 90°? Where is it largest?

B6. The 3 \times 3 neighbourhood \begin{bmatrix} 6 & 2 & 9 \\ 5 & \mathbf 5 & 8 \\ 1 & 4 & 7 \end{bmatrix}. (a) Compute its LBP code. (b) Compute its rotation-invariant code (the smallest of the 8 circular rotations of the bit string). (c) Is it a “uniform” pattern (at most two 0/1 changes around the circle)? (d) Add 10 to every pixel, or double every pixel. What happens to the code?

Math questions

B7. (math) For a symmetric p, show that contrast = 2\sigma^2(1 - \text{correlation}). Check it on B1.

B8. (math) Show that 0 \le \text{entropy} \le \log_2 K where K is the number of non-zero cells, and that K \le \min(L^2, N) for N counted pairs. What does this mean for L = 64 on an object with 200 pairs?

B9. (math) Show that the LBP code is unchanged by any strictly increasing grey-level map g, and that a rotation of the image by 90° about the centre pixel shifts the bit string circularly by 2 positions.

B10. (math) Show that rotating the image by 90° permutes the four standard offsets (up to sign), so the average of a feature over 0°, 45°, 90° and 135° of a symmetric GLCM is unchanged.

B1. (a) Rows: (0,0) (0,1) (1,1); (0,0) (0,1) (1,1); (0,2) (2,2) (2,2); (2,2) (2,2) (2,2). Counts: (0,0) 2, (0,1) 2, (1,1) 2, (0,2) 1, (2,2) 5. Symmetric: P = \begin{bmatrix} 4 & 2 & 1 \\ 2 & 4 & 0 \\ 1 & 0 & 10 \end{bmatrix}, \quad \text{sum } 24. (b) Contrast = (4 \cdot 1 + 2 \cdot 4)/24 = 12/24 = \mathbf{0.5} (cells (0,1), (1,0) differ by 1; (0,2), (2,0) by 2). Homogeneity = (18 + 4 \cdot 0.5 + 2 \cdot 0.2)/24 = 20.4/24 = \mathbf{0.85}. ASM = (16 + 4 + 1 + 4 + 16 + 1 + 100)/576 = 142/576 = \mathbf{0.247}. (c) Entropy = -\big[2 \cdot \tfrac{4}{24}\log_2\tfrac{4}{24} + 2 \cdot \tfrac{2}{24}\log_2\tfrac{2}{24} + 2 \cdot \tfrac{1}{24}\log_2\tfrac{1}{24} + \tfrac{10}{24}\log_2\tfrac{10}{24}\big] = \mathbf{2.37} bits. (d) Row sums 7, 6, 11, so p_x = (7, 6, 11)/24: \mu = (6 + 22)/24 = 1.167, \sigma^2 = \sum (i - \mu)^2 p_x = 0.722. \operatorname{cov} = \sum (i-\mu)(j-\mu) p = 0.472, correlation = 0.472/0.722 = \mathbf{0.654}.

B2. (a) Vertical pairs (lower pixel, upper pixel), columns left to right: column 0: (0,0) (0,0) (2,0); column 1: (0,0) (2,0) (2,2); column 2: (1,1) (2,1) (2,2); column 3: (1,1) (2,1) (2,2). Symmetric: P = \begin{bmatrix} 6 & 0 & 2 \\ 0 & 4 & 2 \\ 2 & 2 & 6 \end{bmatrix}. (b) Contrast = (2 \cdot 2 \cdot 4 + 2 \cdot 2 \cdot 1)/24 = 20/24 = \mathbf{0.83}; homogeneity = (16 + 4 \cdot 0.5 + 4 \cdot 0.2)/24 = 18.8/24 = \mathbf{0.78}. More contrast vertically: the boundary between the top rows (0 and 1) and the bottom rows (2) runs horizontally, so vertical pairs cross it more often.

B3. A diagonal pair needs a partner one row up and one column right: only the 3 \times 3 lower-left pixels have one, 9 pairs, 18 counts in the symmetric matrix. Contrast = (2 \cdot 1 \cdot 1 + 2 \cdot 2 \cdot 1)/18 = 6/18 = 0.33.

B4. (a) Checkerboard: every horizontal pair is (0,1) or (1,0): P = \begin{bmatrix} 0 & 12 \\ 12 & 0 \end{bmatrix}. Halves: per row (0,0) (0,1) (1,1): P = \begin{bmatrix} 8 & 4 \\ 4 & 8 \end{bmatrix}. (b) Checkerboard: contrast 1, correlation −1. Halves: contrast 8/24 = 0.33, correlation +0.33. Contrast, homogeneity (0.5 vs 0.83), ASM (0.5 vs 0.28), entropy (1.0 vs 1.92) and correlation all separate them; mean, standard deviation and the histogram do not. (c) Vertically every pair is (0,0) or (1,1): P = \begin{bmatrix} 12 & 0 \\ 0 & 12 \end{bmatrix}, contrast 0, correlation 1.

B5. At 0°: zero for d = 8, 16, 24, \dots (a whole period: each pixel meets its own value). At 90°: zero for every d (the stripes are vertical). Largest at 0° for d = 4, 12, \dots (half a period: each pixel meets the opposite phase). Demo: contrast 24.75 at d = 4 and 12, 0 at d = 8 and 16.

B6. (a) Clockwise from the top-left: 6, 2, 9, 8, 7, 4, 1, 5. Compared with the centre 5: 1 0 1 1 1 0 0 1, so the code is 10111001_2 = \mathbf{185}. (b) The 8 rotations are 185, 115, 230, 205, 155, 55, 110, 220; the smallest is \mathbf{55} = 00110111_2. (c) Around the circle 1 0 1 1 1 0 0 1 changes 4 times: not uniform. (d) Nothing: the code depends only on which neighbours are at least as bright as the centre, which neither an offset nor a gain changes.

B7. Let I, J be the levels of a random pair. Symmetry gives the same marginal for I and J, so E[I] = E[J] = \mu and \operatorname{var} I = \operatorname{var} J = \sigma^2. Then \text{contrast} = E[(I - J)^2] = \operatorname{var}(I - J) = 2\sigma^2 - 2\operatorname{cov}(I, J) = 2\sigma^2(1 - \rho). B1: 2 \cdot 0.722 \cdot (1 - 0.654) = 0.50.

B8. Each term -p\log_2 p \ge 0 for 0 < p \le 1, so entropy \ge 0. With K non-zero probabilities, entropy is at most that of the uniform distribution on K cells, \log_2 K (Jensen’s inequality, or Gibbs’ inequality). There are L^2 cells, and N counts can fill at most N of them. With L = 64 and N = 200: entropy \le \log_2 200 = 7.6 bits, far below \log_2 4096 = 12; the value reflects the size of the object as much as its texture (demo: 6.80 bits on a disc of radius 6, against 9.01 on the whole patch).

B9. g strictly increasing means g(a) \ge g(b) \iff a \ge b, so every bit s(n_k - c) is unchanged. A rotation by 90° about the centre maps the neighbour positions top-left → top-right → bottom-right → bottom-left (and the edge neighbours likewise), i.e. each neighbour moves 2 steps around the clockwise ring: the bit string is shifted circularly by 2.

B10. A rotation R by 90° maps (d, 0) \mapsto (0, -d), (0, -d) \mapsto (-d, 0), (d, -d) \mapsto (-d, -d), (-d, -d) \mapsto (-d, d). Since a symmetric GLCM of offset \mathbf d equals that of -\mathbf d, the set \{0°, 45°, 90°, 135°\} is mapped to itself: the GLCM of the rotated image at angle \theta equals the GLCM of the original at another angle of the set (up to the slightly different image border). The average over the set is therefore unchanged.

Explore

The demo computes the GLCM of a 64 \times 64 texture patch. The patch is shown quantised to L levels, with three sample pairs at the current offset drawn as yellow arrows. The heat map is the GLCM (rows: level at \mathbf x, columns: level at the partner; the diagonal dashed), with numbers for L \le 4. The table lists the five main features, and the polar plot the contrast against the angle (every 15°, offsets rounded to the grid) at the current d. Choose a second patch B to compare. The disc mask keeps only pairs with both pixels inside a disc; min–max quantises each patch over its own range instead of 0–255.

G1. Preset same histogram, different texture. Compare the two matrices: how many cells are used, and where? Compare the five features. Then set d = 4: which patch changes, and why not the other?

G2. Preset stripes: contrast depends on angle (vertical stripes, period 8, d = 2). Read the contrast at 0°, 45°, 90° and 135°. Why is 45° the same as 0°? Now set the stripe angle to 45° and repeat. Which angle gives zero contrast now?

G3. Preset period = d: contrast vanishes. Move d from 1 to 16 and note the contrast and correlation. Explain the pattern with B5.

G4. Preset fine vs coarse (A: white noise, B: smoothed noise). Read the contrast of both at d = 1, 2, 4, 8. Which one depends on d, and what does the d at which it levels off tell you?

G5. Preset too many levels on a small patch: A and B are two different crops of the same texture, measured in a disc of radius 6 with L = 64. Compare contrast and entropy of A and B. Then set L = 8. Then switch the disc off (radius “off”) at L = 64. What do you conclude?

G6. Preset min–max rescaling hides a brightness difference: B is the same kind of texture as A with half the contrast and darker. Compare A and B with min–max on, then off. Which setting tells you that B is different?

G7. Any stripes preset: untick symmetric. What happens to the number of pairs, and to the contrast? Why can the contrast never change when the matrix is made symmetric?

G1. A (smoothed noise): 38 of 64 cells, all near the diagonal. B (the same pixels shuffled): all 64 cells. Contrast 0.51 against 10.59, homogeneity 0.79 against 0.31, ASM 0.058 against 0.016, entropy 4.42 against 6.00 bits, correlation 0.95 against −0.01. At d = 4, A’s contrast rises to 4.51 and its correlation falls to 0.57, while B stays (10.32, 0.02): B has no spatial structure at any distance, A’s grains are a few pixels wide.

G2. Contrast 12.65 at 0°, 45° and 135°, 0 at 90°. The 45° offset at d = 2 is (2, -2): it also moves 2 pixels across the vertical stripes, and moving up does not matter. With the stripe angle at 45° (stripes running along 135°): contrast 8.03 at 0° and 90°, 22.98 at 45°, 0 at 135° (along the stripes).

G3. Contrast 3.79 (d = 1), 12.65 (2), 24.75 (4), 12.34 (6), 0 (8), 24.75 (12), 0 (16); correlation 0.69, −0.02, −0.98, 0.01, 1, −0.98, 1. A full period brings each pixel back to its own value, half a period to the opposite one: contrast and correlation are periodic in d with the period of the texture.

G4. White noise: 10.32, 10.21, 10.34, 10.38: independent of d, because pixels are unrelated at any distance. Smoothed noise: 0.18, 0.36, 0.90, 2.29: it grows with d until pixels become unrelated; the distance at which it levels off (towards the white-noise value) is the size of the grains.

G5. With the disc and L = 64: contrast 14.89 against 6.27, entropy 6.80 against 6.49 bits, and only 200 pairs for 4096 cells. With L = 8: contrast 0.42 against 0.26, entropy 3.28 against 2.35. Without the disc at L = 64: contrast 12.05 against 11.98, entropy 9.01 against 9.01. On a small object the features are noisy (two crops of the same texture disagree by a factor of two in contrast), and with many levels the entropy is limited by the number of pairs. Fewer levels help, a larger region helps more.

G6. With min–max on: A and B look alike (contrast 0.23 and 0.26, ASM 0.141 and 0.125): each patch is stretched to the full range, which undoes B’s lower contrast and offset. With the fixed range 0–255: B has contrast 0.13 and ASM 0.33 against A’s 0.23 and 0.14. Only the fixed range shows the difference; per-object rescaling makes objects incomparable.

G7. The number of pairs halves (7936 → 3968 for d = 2 at 0°); the contrast stays 12.65. (i - j)^2 = (j - i)^2, so adding the transpose adds the same contrast as the original and the normalisation divides it out again. Features that are not symmetric in i and j (for example the row mean of an asymmetric texture) could change.

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 measurements/src/texture_features/exercise.rs.

C1. quantise(img, levels, lo, hi): cut the range lo to hi into levels equal parts and give each pixel the number of its part, 0 to L - 1 (values outside the range go to the first or last level).

C2. glcm(q, levels, dx, dy, mask): the symmetric co-occurrence counts for the offset (d_x, d_y), with y pointing down (so 90° is (0, -d)):

P = L × L matrix of zeros
for every pixel x:
    y = x + offset
    if x and y are both inside the image (and inside the mask, if there is one):
        i = q(x);   j = q(y)
        P[i][j] = P[i][j] + 1
        P[j][i] = P[j][i] + 1

The checks are your matrices of B1(a) (0°), B2(a) (90°) and B3 (45°, only 18 counts).

C3. haralick(counts): divide by the sum to get p(i, j), then

contrast    = Σ (i − j)² p(i, j)
homogeneity = Σ p(i, j) / (1 + (i − j)²)
ASM         = Σ p(i, j)²
entropy     = − Σ p(i, j) log2 p(i, j)          # only cells with p > 0
μ = Σ i p(i, j);   σ² = Σ (i − μ)² p(i, j)
correlation = Σ (i − μ)(j − μ) p(i, j) / σ²

The checks are B1(b)–(d), B2(b), B3 and the checkerboard and halves of B4.

C4. lbp(img, x, y): the 8 neighbours clockwise from the top-left, bit 1 if the neighbour is at least the centre, read as a binary number; rotation_invariant(code): the smallest of the 8 circular rotations of the bits. The check is B6: 185 and 55.

Then cargo run -p measurements -- texture-features and open the pictures in out/texture-features/. The program measures the pair of the lecture (smoothed noise, and the same pixels shuffled), the correlation against the distance d, stripes with period 8, and maps of contrast and entropy computed in a 17 \times 17 window around every pixel of the micrograph (cell-contrast.png, cell-entropy.png).

C5. Read the features of the same-histogram pair. Which of them differ most? Then read the correlation against d for the smoothed noise and for white noise: at about which d has the smoothed noise forgotten its neighbour? Check the stripes against your answer to B5.

C6. Compare cell-entropy.png with cell.png. Where is the entropy high, and where is it low? The program also prints the mean and spread of both maps over the whole image and inside the nucleus. What do they say about the nucleus?

C7. The texture maps fill one 17 \times 17 window and one 8 \times 8 matrix per pixel. How many pixel pairs does the program count for the whole 256 \times 256 image? How would you avoid starting every window from zero?

The model solution is measurements/src/texture_features/solution.rs in the download.

C5. Contrast 0.49 against 10.46, homogeneity 0.79 against 0.30, correlation 0.95 against 0.00; ASM and entropy differ less (0.058 and 0.016; 4.39 and 5.99 bits). The numbers are close to the lecture’s (0.51 and 10.59), with a different random patch. The correlation of the smoothed noise falls from 0.96 at d = 1 through 0.69 at d = 4 and 0.20 at d = 8 to about 0 at d = 12: beyond about 10 pixels a pixel says nothing about its partner, roughly the size of the grains. White noise stays within 0.04 of 0 at every d. The stripes have contrast 0.0 at d = 8 and d = 16 and the largest contrast, 29.0, at d = 4 and d = 12; at 90° the contrast is 0, as in B5.

C6. The entropy is highest along the edges of the cell and the nuclear envelope, where a window holds both dark and bright pixels and many different pairs, and lowest in the pale patches between the debris outside the cell, where most pairs fall into the top grey levels. The nucleus is a smooth, even region of the map: its entropy is 3.24 \pm 0.18 against 3.50 \pm 0.80 over the whole image, and its contrast 0.90 \pm 0.08 against 0.97 \pm 0.30. Its fine granular texture is the same everywhere, so a texture feature of the nucleus hardly depends on where it is measured.

C7. Each window has 17 \cdot 16 = 272 horizontal pairs, so the program counts 65\,536 \cdot 272 \approx 1.8 \cdot 10^7 pairs (each added twice to the symmetric matrix). Moving the window one pixel to the right changes only two of its columns: subtract the pairs of the column that leaves and add those of the column that enters, about 2 \cdot 17 pairs instead of 272. The same idea as the running sums of integral images.

Where this leads

Texture features compare a pixel with a shifted copy of the same image. The colocalisation day replaces the shifted copy with a second channel: the same 2D histogram, now a colocalisation scatter plot. The next unit measures relations between whole objects: neighbours, parents and children.