Exercise: opening, closing and the distance transform

Goal

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

  • compute an opening and a closing by hand, and check that they are idempotent,
  • predict what open-then-close and close-then-open do to a noisy mask,
  • compute a pattern spectrum for a simple case and read a granulometry curve,
  • compute a city-block distance transform by hand, and read off an erosion from it.

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

Background

Idea What it means
Opening A \circ B = (A \ominus B) \oplus B union of all copies of B that fit inside A; removes what is smaller than B
Closing A \bullet B = (A \oplus B) \ominus B the same for the background; fills holes and gaps smaller than B
Properties increasing; opening \subseteq A \subseteq closing; idempotent; (A \circ B)^c = A^c \bullet \check B
Area left, pattern spectrum a(r) = \lvert A \circ D_r\rvert for discs (or lines) of growing size; a(r) - a(r + 1)
Distance transform \mathrm{DT}(p) = distance from p to the nearest background pixel (0 on the background)
Two passes (city-block) forward: \min(d, d_{\text{left}} + 1, d_{\text{up}} + 1); backward: \min(d, d_{\text{right}} + 1, d_{\text{down}} + 1)
Erosion by a disc A \ominus D_r = \{\mathrm{DT} > r\} (city-block DT ↔︎ diamond, chessboard DT ↔︎ square)

Rows and columns are counted from 0, top left. In B1–B2 the object stays at least 2 pixels away from the image edge, so the border convention does not matter.

By hand

B1. Let B be the 3 \times 3 square and A = \begin{bmatrix} 0&0&0&0&0&0&0&0&0 \\ 0&0&0&0&0&0&0&0&0 \\ 0&0&1&1&1&1&1&0&0 \\ 0&0&1&1&1&1&1&0&0 \\ 0&0&1&1&1&0&1&0&0 \\ 0&0&1&1&1&1&1&0&0 \\ 0&0&1&0&0&0&0&0&0 \\ 0&0&0&0&0&0&0&0&0 \\ 0&0&0&0&0&0&0&0&0 \end{bmatrix} \quad (20 \text{ pixels: a block with a one-pixel hole and a one-pixel protrusion}). (a) Compute A \ominus B and then A \circ B. (b) Compute A \oplus B and then A \bullet B. (c) Open A \circ B once more. What do you get, and why could you have predicted it?

B2. With the same A and B: compute (A \circ B) \bullet B (open, then close) and (A \bullet B) \circ B (close, then open). Are they equal? Explain the difference in one sentence.

B3. Predict, without computing: a mask has a thin bridge (1 pixel wide) between two large blobs, and a 1-pixel crack running into one blob from its edge. What do an opening and a closing with the 3 \times 3 square do to the bridge and to the crack?

B4. A 1D binary signal has runs of 1s of lengths 1, 2, 2, 4 and 5, separated by gaps of at least 2 zeros. Open it with line SEs of length L = 1, 2, 3, 4, 5, 6. (a) Which runs survive the opening with a line of length L? Give the area left a(L) for each L. (b) Compute the pattern spectrum a(L) - a(L + 1) for L = 1, \dots, 5 and check that it sums to the total length of the runs. (c) Interpret: what would the spectrum look like for 50 runs of length 3 and 10 runs of length 8?

B5. The mask M = \begin{bmatrix} 0&0&0&0&0&0&0&0 \\ 0&1&1&1&1&1&1&0 \\ 0&1&1&1&1&1&1&0 \\ 0&1&1&1&1&1&1&0 \\ 0&1&1&1&1&1&1&0 \\ 0&0&0&1&1&1&1&0 \\ 0&0&0&1&1&1&1&0 \\ 0&0&0&0&0&0&0&0 \end{bmatrix} \quad (32 \text{ pixels}) (a) Compute its city-block distance transform by counting, for every object pixel, the number of 4-neighbour steps to the nearest background pixel. What is the largest value, and where? (b) Read off \{\mathrm{DT} > 2\}, the erosion of M by the diamond of radius 2 (|\Delta x| + |\Delta y| \le 2, 13 pixels). How many pixels? (c) Check two pixels directly: row 3, column 3 should be in the erosion, row 4, column 3 should not. Which diamond pixel misses the object for the second one?

B6. For the same mask the chessboard distance transform (steps to all 8 neighbours) is \begin{bmatrix} 0&0&0&0&0&0&0&0 \\ 0&1&1&1&1&1&1&0 \\ 0&1&2&2&2&2&1&0 \\ 0&1&2&2&2&2&1&0 \\ 0&1&1&1&2&2&1&0 \\ 0&0&0&1&2&2&1&0 \\ 0&0&0&1&1&1&1&0 \\ 0&0&0&0&0&0&0&0 \end{bmatrix}. How many pixels does the erosion of M by the 3 \times 3 square have? Why are the chessboard values never larger than the city-block ones?

B7. A granulometry with discs on an image of round cells of radius 6 and radius 13 gives pattern-spectrum peaks at r = 5 and r = 12, not 6 and 13. Give a reason. Where would the peaks move with a square SE?

B1. (a) The square fits only at row 3, column 3 and row 4, column 3 (2 pixels): A \ominus B is these two pixels. Dilating them back gives the block of rows 2–5, columns 2–4 (12 pixels): A \circ B = \begin{bmatrix} 0&0&0&0&0&0&0&0&0 \\ 0&0&0&0&0&0&0&0&0 \\ 0&0&1&1&1&0&0&0&0 \\ 0&0&1&1&1&0&0&0&0 \\ 0&0&1&1&1&0&0&0&0 \\ 0&0&1&1&1&0&0&0&0 \\ 0&0&0&0&0&0&0&0&0 \\ 0&0&0&0&0&0&0&0&0 \\ 0&0&0&0&0&0&0&0&0 \end{bmatrix}. The protrusion goes, and so do columns 5–6: next to the hole, the object is at most 2 pixels wide there, and no 3 \times 3 square fits. (b) A \oplus B covers rows 1–6, columns 1–7, plus row 7, columns 1–3 (45 pixels); the hole is filled. Eroding back gives A with the hole filled (21 pixels): the closing adds exactly the hole pixel (row 4, column 5). The protrusion stays: closing never removes anything. (c) The same 12 pixels: the opening is idempotent. Every pixel of A \circ B lies in a 3 \times 3 square inside A \circ B, so opening again keeps it.

B2. Open, then close: the opening already removed the hole region and the protrusion, and the closing of a 4 \times 3 block changes nothing: 12 pixels. Close, then open: the closing fills the hole, so the full 4 \times 5 block (rows 2–5, columns 2–6) survives the opening; only the protrusion goes: 20 pixels. Not equal: whichever filter acts first decides whether the region around the hole is “too thin” (removed) or “a block with a hole” (filled and kept).

B3. Opening: the bridge is cut (the square does not fit in it); the crack stays (the opening only removes object pixels). Closing: the crack is filled (the square cannot get into it from the background); the bridge stays and the narrow gaps beside it, if any, may be bridged further.

B4. (a) A line of length L fits in a run exactly when the run has length \ge L, and the opening keeps the whole run. Total length 1 + 2 + 2 + 4 + 5 = 14.

L 1 2 3 4 5 6
runs kept all 2, 2, 4, 5 4, 5 4, 5 5 none
a(L) 14 13 9 9 5 0
  1. a(L) - a(L + 1) for L = 1, \dots, 5: 1, 4, 0, 4, 5. Sum = 14. Each run appears at its own length with its length as the bar height.
  2. Two bars: 50 \cdot 3 = 150 at L = 3 and 10 \cdot 8 = 80 at L = 8, zero elsewhere. The spectrum counts area (pixels), not objects: divide a bar by its length to count runs.

B5. (a) \mathrm{DT} = \begin{bmatrix} 0&0&0&0&0&0&0&0 \\ 0&1&1&1&1&1&1&0 \\ 0&1&2&2&2&2&1&0 \\ 0&1&2&3&3&2&1&0 \\ 0&1&1&2&3&2&1&0 \\ 0&0&0&1&2&2&1&0 \\ 0&0&0&1&1&1&1&0 \\ 0&0&0&0&0&0&0&0 \end{bmatrix} The largest value is 3, at row 3, columns 3 and 4, and row 4, column 4. (b) \{\mathrm{DT} > 2\} = those 3 pixels. (c) Row 3, column 3: the diamond reaches rows 1–5 in column 3, columns 1–5 in row 3, and the four pixels diagonally next to the centre; all are 1 (row 5, column 3 is the bottom-most, and it is in M). So it is in the erosion. Row 4, column 3 has \mathrm{DT} = 2: the diamond pixel at row 5, column 2 (\Delta = (-1, +1), distance 2) is background, so the diamond does not fit.

B6. The erosion by the 3 \times 3 square (radius 1 in the chessboard metric) is \{\mathrm{DT}_{\text{chessboard}} > 1\}: the pixels with value 2, i.e. 4 + 4 + 2 + 2 = 12 pixels. A diagonal step counts 1 in the chessboard metric and 2 in the city-block metric, so every path is at most as long in the chessboard metric: \max(|\Delta x|, |\Delta y|) \le |\Delta x| + |\Delta y|.

B7. The cells are digitised around centres that do not sit exactly on pixel centres, so a digital disc of radius 6 does not quite fit into a digitised cell of radius 6; radius 5 does. (In the demo, removed pixels show the radius at which they disappear: 6 and 13.) A square of radius r (side 2r + 1) fits into a disc of radius R only if its corner, at distance r\sqrt2, is inside: r \le R/\sqrt2. The peaks move down to about 4 and 9.

Math questions

B8 (math). Prove that the opening is the union of all translates of B that fit inside A: (A \ominus B) \oplus B = \bigcup\{B_z : B_z \subseteq A\}. Use it to prove that the opening is anti-extensive and idempotent.

B9 (math). Run the forward pass of the two-pass city-block algorithm on the mask M of B5 (start: 0 on the background, \infty on the object; raster order; d \leftarrow \min(d, d_{\text{left}} + 1, d_{\text{up}} + 1)). Write the result. Which pixels does the backward pass change?

B10 (math). Prove that A \ominus D_r = \{x : \mathrm{DT}(x) > r\} for the Euclidean disc D_r = \{b : \|b\| \le r\}, and that A \oplus D_r = \{x : \mathrm{DT}_{A^c}(x) \le r\}, where \mathrm{DT}_{A^c}(x) is the distance from x to the nearest pixel of A.

B11 (math). Suppose B_s = B_s \circ B_r for s \ge r (every larger SE is a union of translates of the smaller one). Show that A \circ B_s \subseteq A \circ B_r, so the area left a(r) can only decrease. Is the condition true for the squares B_r of side 2r + 1?

B8. If x \in (A \ominus B) \oplus B, then x = z + b with z \in A \ominus B, i.e. B_z \subseteq A, and x \in B_z. Conversely, if x \in B_z \subseteq A, then z \in A \ominus B and x = z + b for some b \in B. Anti-extensive: a union of subsets of A lies in A. Idempotent: each B_z \subseteq A also satisfies B_z \subseteq A \circ B, and every B_z \subseteq A \circ B satisfies B_z \subseteq A; so both unions run over the same translates.

B9. After the forward pass: \begin{bmatrix} 0&0&0&0&0&0&0&0 \\ 0&1&1&1&1&1&1&0 \\ 0&1&2&2&2&2&2&0 \\ 0&1&2&3&3&3&3&0 \\ 0&1&2&3&4&4&4&0 \\ 0&0&0&1&2&3&4&0 \\ 0&0&0&1&2&3&4&0 \\ 0&0&0&0&0&0&0&0 \end{bmatrix} The forward pass only sees background above and to the left. The backward pass lowers the 13 pixels that are closer to background below or to the right: column 6 (rows 2–6) becomes 1; column 5 becomes 2, 2, 2, 1 in rows 3–6; row 6, column 4 becomes 1; and row 4, columns 2–4 become 1, 2, 3 (the background below row 4 on the left). The result is the DT of B5.

B10. x \in A \ominus D_r \iff x + b \in A for all \|b\| \le r \iff there is no q \notin A with \|q - x\| \le r \iff \min_{q \notin A}\|q - x\| > r \iff \mathrm{DT}(x) > r. For dilation use the duality with the symmetric D_r = \check D_r: (A \oplus D_r)^c = A^c \ominus D_r = \{x : \mathrm{DT}_{A^c}(x) > r\}, so A \oplus D_r = \{\mathrm{DT}_{A^c} \le r\}.

B11. Every copy (B_s)_z \subseteq A is, by the assumption, a union of copies (B_r)_{z + y} that lie inside (B_s)_z \subseteq A. So every pixel covered by a fitting B_s is covered by a fitting B_r: A \circ B_s \subseteq A \circ B_r, and a(s) \le a(r). For squares it holds: a square of side 2s + 1 is the union of the squares of side 2r + 1 inside it (slide the small square over all positions). Digital discs do not always satisfy it, which is why granulometries use the union of the openings by all discs of radius \ge r.

Explore: opening and closing step by step

The grid demo of the previous unit, with the operations opening, closing, open-then-close, close-then-open and “opening, twice”. The border convention is ignored: erosion does not eat in from the image edge, and dilation does not grow out of it. In the final frame dark = kept, red = removed, green = added, and the note compares with the other order or with a single opening.

P1. Example opening removes the speck. Before running: which pixels will be red? Press end and count. Then step through the second stage (the dilation) and describe what it does with the pixels the erosion removed.

P2. Example closing fills the gap. Which pixels are added? Why is the three-row gap between the big block and the two small ones not filled, while the gap between the two small blocks is?

P3. Example open∘close ≠ close∘open. How many pixels are left after open-then-close, and how many pixels differ from close-then-open (final note)? Choose close, then open and compare the two results: which noise does each order handle better?

P4. Example apply twice: nothing changes. Step to the end of the first opening (“next stage” jumps by rows) and compare with the final result.

P5. Example 9 × 9 (exercise): check B1 and B2.

P1. 37 pixels become 30: the single speck, the two-pixel speck and the thin arm (4 pixels) are red; the block is unchanged. In the dilation stage every pixel within one step of a surviving erosion pixel comes back: the block is rebuilt exactly, but nothing grows back where the erosion left no pixel.

P2. 65 pixels become 70: the three one-pixel holes in the big block and the one-pixel-wide gap (2 pixels) between the two lower blocks. A 3 \times 3 square fills gaps up to 2 pixels wide (each side grows by one pixel in the dilation, and the erosion cannot open them again); the three-row gap is wider than that.

P3. Open-then-close leaves 36 pixels; the note says close-then-open differs in 31 pixels (it leaves 67). Open-then-close removes the specks first, but the opening also removes the parts of the object that are thin because of the holes, and the closing cannot bring them back. Close-then-open fills the holes first and then keeps the filled blocks; the specks are removed by the opening, unless the closing has joined them to an object.

P4. After the first opening 34 of the 61 pixels are left; the second opening changes nothing, and the note says “Same as one opening”.

P5. Opening: 12 pixels; closing: 21; open-then-close: 12; close-then-open: 20; as in B1 and B2.

Explore: the two-pass distance transform

Left: the mask (click to edit). Right: the distances, starting from 0 on the background and ∞ on the object. Step runs the forward pass (neighbours above and to the left, shown as the window on the right grid) and then the backward pass; the log writes each minimum. At the end, green cells are \{\mathrm{DT} > r\} with r from the slider: the erosion by the diamond (city-block) or the square (chessboard) of radius r.

D1. Example 8 × 8 (exercise), city-block. Step through the first rows and compare with your forward pass (B9). Then press end and check B5. How many green pixels for r = 2, r = 1, r = 0?

D2. Switch to chessboard and check B6. Which pixels have different values in the two metrics?

D3. Example object at the edge. The object touches the image border. What are the largest distances, and where? What does the algorithm assume about the pixels outside the image?

D1. The forward pass gives the matrix of B9; the end result is the DT of B5. Green pixels: 3 for r = 2 (the three 3s), 13 for r = 1 (all values \ge 2), and all 32 object pixels for r = 0.

D2. The chessboard values are as in B6. Four pixels differ, all where the nearest background is reached diagonally: the three 3s become 2, and row 4, column 3 goes from 2 to 1 (its nearest background, row 5, column 2, is one diagonal step away). So the erosion by the 3 \times 3 square has 12 pixels, against 13 for the diamond of radius 1.

D3. The largest city-block distance is 5, in the top-left corner pixel; the chessboard maximum is 4. The algorithm only knows the background inside the image: pixels outside are neither object nor background, so an object cut by the image edge looks thicker than it is. This matches erosion with the outside “ignored”.

Explore: granulometry

A 256 \times 256 binary image (synthetic). Left: the opening at radius r in dark; the pixels already removed are coloured by the radius at which they disappeared, so the colours form a “size map”. Right: the area left a(r) in % of the object area, and the pattern spectrum (the pixels removed between r and r + 1, in %), with the current r marked. Choose the image and the SE (disc, square, diamond, horizontal line). via distance transform shows the distance transform in grey, the erosion \{\mathrm{DT} > r\} in green and its edge in red.

G1. Example two sizes, two peaks. Where are the two peaks of the pattern spectrum, and how large are they (in % of the area)? At which radius are the small discs gone, and at which the large ones? What happens to the specks?

G2. Still on two sizes, set r = 7. Read the area left. Explain the plateau of a(r) between r = 6 and r = 12.

G3. Example touching discs: one bigger object? All discs have radius 8; some touch in pairs or chains of three. Do the pairs and chains show up as larger objects in the spectrum? Why (not)?

G4. Example lines: find the horizontal ones (horizontal line SE). At which radius do the vertical bars disappear? Over which range of radii do the horizontal bars disappear, and what determines when each one goes? Switch the SE to disc: what happens now?

G5. Example square SE on discs. Where are the peaks now? Compare with B7.

G6. Example erosion = threshold of DT. Move r and watch the green set and the left image (switch “via distance transform” off and on). Which disc radius erodes the small discs completely?

G7. Example nuclei mask (a thresholded image of synthetic nuclei). Describe the spectrum. Why is it broader than for the two-size image?

G1. Peaks at r = 5 (2212 pixels, 30.3 %) and r = 12 (4419 pixels, 60.5 %): the small discs disappear at radius 6, the large ones at 13. The specks (one or two pixels) disappear at r = 1 or 2 and give the tiny bars at the left.

G2. At r = 7, 4730 of 7310 pixels are left (64.7 %): only the large discs. Between r = 6 and 12 nothing is in the size range (the small discs are gone and the large ones still fit), so a(r) is almost flat; the small drops are the rims of the large discs, where a large digital disc is not quite round.

G3. No. The spectrum has one peak at r = 7 (4280 of 4655 pixels) for singles, pairs and chains alike: the largest disc that fits in two touching discs of radius 8 is still radius 7 (the neck is narrower, not wider). Granulometry measures the size of the largest inscribed disc, not of connected objects; touching discs do not make a “larger particle”.

G4. With the horizontal line, the vertical bars (3 pixels wide) disappear at r = 2 (the line of length 5 does not fit across them): 1386 pixels in the bar at r = 1. The horizontal bars (length 24 to 48) disappear between r = 12 and r = 24: a line of length 2r + 1 fits as long as 2r + 1 \le the bar length. With a disc both orientations disappear together at r = 2: a disc sees only the width (3 pixels).

G5. Peaks at r = 3–4 and r = 8–9 (instead of 5 and 12): a square of radius r needs a disc of radius about r\sqrt2, so 6/\sqrt2 \approx 4.2 and 13/\sqrt2 \approx 9.2.

G6. The green set \{\mathrm{DT} > r\} is exactly the set of centres where the disc fits; the dark pixels in the left image (with the DT view off) are the union of the discs placed on those centres. The small discs are eroded completely from r = 6 on (their largest DT value is about 6, and the erosion needs \mathrm{DT} > r).

G7. A broad hump from about r = 7 to 13, with the largest bar at r = 12 (3607 of 10036 pixels): the nuclei have different sizes and are elongated (for an ellipse the inscribed disc is set by the short axis), and touching nuclei do not count as larger. A few small bars at low r come from noise in the threshold.

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 morphology/src/morph_openclose/exercise.rs.

Erosion and dilation (from the last unit) are given, with the border convention “ignored”, as are the square, digital discs, diamonds and horizontal lines.

C1. open(a, se) and close(a, se): erode then dilate, and dilate then erode. The checks are B1 (12 and 21 pixels, idempotent) and B2 (12 and 20 pixels).

C2. granulometry(a, ses): the area left a(k) after the opening by each SE of a list of growing SEs, and the pattern spectrum a(k) - a(k + 1). The check is B4: lines of length 1 to 6 give a = 14, 13, 9, 9, 5, 0 and the spectrum 1, 4, 0, 4, 5.

C3. distance_transform(a, chessboard): the two raster passes.

d = 0 on the background, "far" on the object
for y = top … bottom, for x = left … right:           # forward
    d(x, y) = min( d(x, y), d(left) + 1, d(up) + 1 )
for y = bottom … top, for x = right … left:           # backward
    d(x, y) = min( d(x, y), d(right) + 1, d(down) + 1 )

Neighbours outside the image are skipped. For the chessboard distance the forward pass also looks up-left and up-right, the backward pass down-right and down-left. The checks are B5 (a) and B6.

C4. erode_by_distance(a, r, chessboard): the erosion as \{\mathrm{DT} > r\}. The checks are B5 (b) (3 pixels), B6 (12 pixels), and the comparison with the erosion by the diamond and by the square on a random mask.

Then cargo run -p morphology -- morph-openclose and open the pictures in out/morph-openclose/. The program runs a granulometry with discs of radius 0 to 15 on discs of radius 6 and 13 with a few specks (two-sizes.png, spectrum in pattern-spectrum.png), cleans a noisy mask of nuclei with a disc of radius 2, and computes distance transforms.

C5. At which radii does the pattern spectrum have its peaks, and how large are they? Compare with B7 and with the demo. One value of the spectrum is negative: how can the opening by a larger disc keep more pixels than the opening by a smaller one?

C6. Compare open-close.png with close-open.png (and the pixel counts) for the noisy mask in noisy-mask.png. Which order keeps the dim, holey nuclei, and why? (B2)

The model solution is morphology/src/morph_openclose/solution.rs in the download.

C5. Peaks at r = 5 (1430 pixels: the small discs) and r = 12 (3435 pixels: the large discs), one below the radii 6 and 13, as in B7 and in the demo. The small bars at r = 0 to 4 are the specks and the outer rims of the discs. At r = 9 the spectrum is -14: the opening by the disc of radius 10 keeps 14 pixels more than the opening by radius 9. Digital discs are not exactly unions of smaller digital discs, so the openings are not exactly nested (slide “The math: granulometry”).

C6. Open-then-close leaves 9946 pixels, close-then-open 11 123 (the mask has 10 875). Opening first removes the specks, but it also breaks the dim nuclei that are full of holes into fragments, and the closing cannot rebuild them. Closing first fills the holes, so those nuclei survive the opening whole; the specks are still removed by the opening, as long as the closing has not joined them to a nucleus.

Where this leads

Opening and closing filter by size but change the outlines of what they keep: corners get rounded, and an object is either kept as a union of SE copies or lost. The next units fix both problems in different ways: grey-level morphology applies the same operators to grey images (top-hat, gradient), and morphological reconstruction keeps every object that contains a seed, exactly as it was. The distance transform returns on the watershed day (splitting touching cells), on the skeleton day (its ridges are the skeleton), as the signed distance of level sets (day 31), and as the two-pass scheme behind dynamic programming (day 32).