Exercise: the structure tensor
Before this unit: The Hessian: blobs, ridges and saddles (previous unit); Day 1: Images, filters and frequencies.
Goal
By the end of this exercise you should be able to:
- explain why averaging gradients fails and averaging \nabla L\,\nabla L^\top works,
- build the structure tensor of a small window and read orientation, coherence and the verdict edge / corner / flat from its eigenvalues,
- compute the Harris corner response,
- choose the two scales σ and ρ for a task,
- (math) derive the orientation formula and the Harris approximation.
Background
| Idea | What it means |
|---|---|
| Structure tensor | J = G_\rho * \begin{pmatrix} L_x^2 & L_xL_y \\ L_xL_y & L_y^2\end{pmatrix}: gradient at scale σ, window ρ (here, by hand: a plain average over the window) |
| Eigenvalues | \mu_1 \ge \mu_2 \ge 0; closed form \mu = \frac{a + c}{2} \pm \sqrt{\big(\frac{a - c}{2}\big)^2 + b^2} for \begin{pmatrix} a & b \\ b & c\end{pmatrix} |
| Orientation | eigenvector of \mu_1 = dominant gradient direction, angle \theta = \tfrac12\operatorname{atan2}(2b, a - c) (image coordinates, y down); the structure runs at \theta + 90° |
| Coherence | \big(\frac{\mu_1 - \mu_2}{\mu_1 + \mu_2}\big)^2 \in [0, 1] |
| Verdict | both small: flat; one large: edge / oriented; both large: corner |
| Harris | R = \det J - k(\operatorname{tr}J)^2, k \approx 0.05: > 0 corner, < 0 edge, ≈ 0 flat |
By hand
B1. A window contains four gradient vectors: (1, 0), (-1, 0), (1, 0), (-1, 0). (a) What is the average gradient? (b) Compute J as the average of \mathbf g\mathbf g^\top. (c) Eigenvalues, coherence and verdict. What kind of structure could produce these gradients?
B2. The same for (a) (1, 0), (0, 1), (-1, 0), (0, -1); (b) four zero vectors.
B3. A window has J = \begin{pmatrix} 5 & 2 \\ 2 & 2\end{pmatrix}. (a) Compute \mu_1, \mu_2 and the coherence. (b) Compute θ, the angle of the dominant gradient direction in image coordinates. With y down, which way does it point on the screen? At what angle (counter-clockwise on the screen) do the stripes run?
B4. Harris responses with k = 0.05 for J = \mathrm{diag}(10, 0.1), J = \mathrm{diag}(10, 8) and J = \mathrm{diag}(0.1, 0.1). Which is the corner, the edge and the flat region? What does Förstner’s \mu_2 say?
B5. Predict the ellipse glyph of J (shape and orientation) for a window (a) on the straight top edge of a bright square, (b) on its top-left corner, (c) in its flat interior, (d) on vertical stripes, (e) on isotropic noise texture.
B6. You want an orientation map of collagen fibres about 4 pixels apart, in a noisy image, where regions of different fibre direction are about 40 pixels across. Suggest σ and ρ and explain the trade-off in each.
B1. (a) (0, 0): the gradients cancel. (b) Each \mathbf g\mathbf g^\top is \begin{pmatrix} 1 & 0 \\ 0 & 0\end{pmatrix} (also for (-1, 0)), so J = \begin{pmatrix} 1 & 0 \\ 0 & 0\end{pmatrix}. (c) \mu_1 = 1, \mu_2 = 0, coherence 1: an edge or oriented structure; the gradients are horizontal, so the structure is vertical. Opposite gradients in one window: a vertical line (or vertical stripes), bright or dark. The average gradient said “nothing here”; J says “perfectly oriented”.
B2. (a) Average (0, 0); J = \frac14\big(\begin{smallmatrix}1&0\\0&0\end{smallmatrix} + \begin{smallmatrix}0&0\\0&1\end{smallmatrix} + \begin{smallmatrix}1&0\\0&0\end{smallmatrix} + \begin{smallmatrix}0&0\\0&1\end{smallmatrix}\big) = \begin{pmatrix} 0.5 & 0 \\ 0 & 0.5\end{pmatrix}: \mu_1 = \mu_2 = 0.5, coherence 0: two directions in one window, a corner (or isotropic texture). (b) J = 0: flat; coherence undefined (0/0; the demos show 0).
B3. (a) \mu = 3.5 \pm \sqrt{1.5^2 + 2^2} = 3.5 \pm 2.5: \mu_1 = 6, \mu_2 = 1; coherence (5/7)^2 = 0.51. (b) \theta = \tfrac12\operatorname{atan2}(4, 3) = 26.6° in image coordinates: with y down the dominant gradient points to the right and down (−26.6° counter-clockwise on the screen). The stripes run perpendicular to it, at 90° - 26.6° = 63.4° counter-clockwise on the screen (from lower left to upper right, steeply).
B4. \mathrm{diag}(10, 0.1): 1 - 0.05 \cdot 10.1^2 = -4.10, an edge. \mathrm{diag}(10, 8): 80 - 0.05 \cdot 18^2 = 63.8, a corner. \mathrm{diag}(0.1, 0.1): 0.01 - 0.05 \cdot 0.04 = 0.008, flat (tiny). Förstner’s \mu_2: 0.1, 8, 0.1: large only at the corner; it does not distinguish edge from flat, but it does not need to: neither is a corner.
B5. (a) A thin ellipse, long axis vertical (across the edge: the gradients point up or down), short axis ≈ 0. (b) A large, roundish ellipse (gradients up and left). (c) A dot. (d) A thin ellipse with its long axis horizontal (across the stripes). (e) A roundish ellipse whose size reflects the texture’s contrast; coherence near 0.
B6. σ should be smaller than the fibre spacing so that the stripes produce gradients at all, but large enough to suppress pixel noise: σ ≈ 1 to 1.5 (σ = 4 would blur the fibres away). ρ should cover several fibres to average out noise (ρ ≈ 6 to 8, a window of about 25 to 30 pixels), but stay well below the 40-pixel regions, or the boundaries between directions blur into a band of low coherence.
Math questions
B7. (math) Show that \mathbf u^\top J\mathbf u equals the window average of (\nabla L\cdot\mathbf u)^2, and that over unit vectors it is largest along the eigenvector of \mu_1, with value \mu_1.
B8. (math) With \nabla L = r(\cos\phi, \sin\phi), show that J_{xx} - J_{yy} = \langle r^2\cos2\phi\rangle and 2J_{xy} = \langle r^2\sin2\phi\rangle, and that the dominant gradient angle is \tfrac12\operatorname{atan2}(2J_{xy}, J_{xx} - J_{yy}). Why does the doubling make opposite gradients add?
B9. (math) Show that shifting a window by a small \mathbf h changes it by E(\mathbf h) = \sum w\,(I(\mathbf x + \mathbf h) - I(\mathbf x))^2 \approx \mathbf h^\top J\,\mathbf h, and use it to explain why a corner needs \mu_2 large.
B7. (\mathbf g\cdot\mathbf u)^2 = \mathbf u^\top\mathbf g\mathbf g^\top\mathbf u, and averaging over the window (with weights w) is linear: \langle(\nabla L\cdot\mathbf u)^2\rangle = \mathbf u^\top\langle\nabla L\nabla L^\top\rangle\mathbf u = \mathbf u^\top J\mathbf u. J is symmetric with orthonormal eigenvectors \mathbf e_1, \mathbf e_2; with \mathbf u = \cos\phi\,\mathbf e_1 + \sin\phi\,\mathbf e_2, \mathbf u^\top J\mathbf u = \mu_1\cos^2\phi + \mu_2\sin^2\phi, at most \mu_1, attained at \phi = 0.
B8. L_x^2 - L_y^2 = r^2(\cos^2\phi - \sin^2\phi) = r^2\cos2\phi and 2L_xL_y = 2r^2\cos\phi\sin\phi = r^2\sin2\phi; averaging gives the two identities. From the closed form, the eigenvector of \mu_1 of \begin{pmatrix} a & b \\ b & c\end{pmatrix} has angle \tfrac12\operatorname{atan2}(2b, a - c), i.e. half the angle of the averaged vector \langle r^2(\cos2\phi, \sin2\phi)\rangle. A gradient and its opposite differ by 180° in φ, hence by 360° in 2\phi: they map to the same doubled-angle vector and add instead of cancelling.
B9. First-order Taylor: I(\mathbf x + \mathbf h) - I(\mathbf x) \approx \nabla I(\mathbf x)^\top\mathbf h. So E(\mathbf h) \approx \sum w\,(\nabla I^\top\mathbf h)^2 = \mathbf h^\top\big(\sum w\,\nabla I\nabla I^\top\big)\mathbf h = \mathbf h^\top J\mathbf h. For a fixed shift length |\mathbf h| this ranges from \mu_2|\mathbf h|^2 (shift along \mathbf e_2) to \mu_1|\mathbf h|^2. At an edge, shifting along the edge leaves the window unchanged (\mu_2 \approx 0); a window that changes under every shift, a corner, needs \mu_2 large.
Explore: the structure tensor
Images: synthetic textures (stripes with an angle and a frequency, rotating stripes, a “fingerprint”, two textures meeting at the middle, a checkerboard with a square and a triangle, a single square, isotropic noise) or the micrograph. The left panel shows the image with one ellipse of J per 16-pixel cell, the orientation map (hue = orientation of the structure, saturation = coherence, brightness = energy) or the Harris response with the detected corners. Click a pixel: the window (cyan), its gradient arrows (yellow) and their mean (red), the gradient cloud with the ellipse of J, and the numbers. Average gradients instead shows the naive orientation map from the mean gradient.
E1. Presets edge, corner, flat (square, σ = 1, ρ = 3). Read J, \mu_1, \mu_2 and the coherence in each case, and describe the gradient cloud. Compare with B1, B2 and B5.
E2. Preset averaging gradients cancels (stripes at 30°, naive mode). What does the naive orientation map look like, and why? Compare the mean gradient (red arrow) with \sqrt{\mu_1}. Untick the naive mode.
E3. Preset ρ = 0. Read \mu_2 at the corner (32, 32). Look at the corners tab: how many corners are found? Raise ρ slowly: from which ρ are the four corners of the square detected?
E4. Preset ρ too small or too large (two textures, noise 25, ρ = 1). Describe the orientation map. Then set ρ = 3 and ρ = 8. Read the coherence at (30, 64), (62, 64) (on the boundary) and (96, 64) each time.
E5. Preset rotating stripes. Click across the image at y = 64: x = 16, 32, 64, 96, 112. Read the orientation each time. Does the hue follow?
E6. Preset corners of a checkerboard (ρ = 2). How many corners are found, and where? Raise the corner threshold and lower it; change Harris k. What happens on the triangle’s corners?
E7. Image fingerprint: describe the orientation map. Where is the coherence low, and why?
E8. Preset micrograph (σ = 1.5, ρ = 4). Which regions are oriented (saturated colours), which isotropic (grey)? Click on the nuclear envelope at (94, 126) and inside the nucleus at (150, 150): compare the coherence.
E1. Edge (32, 64): J = [740 0; 0 0], \mu_1 = 740, \mu_2 = 0, coherence 1.00, orientation 90° (the edge is vertical): the cloud is a short line along L_x. Corner (32, 32): J = [366 81; 81 366], \mu_1 = 447, \mu_2 = 285, coherence 0.05: the cloud spreads in two directions (a fan from the origin). Flat (64, 64): all zero. As in B1, B2 and B5: one large eigenvalue at the edge, two at the corner, none inside.
E2. The naive map is almost black: the average gradient is near zero everywhere on stripes. At (64, 64) the mean gradient has length 0.48, while \sqrt{\mu_1} = 32.1: the gradients are strong, they just cancel. With J the map is uniformly coloured (orientation 120°, coherence 1.00).
E3. With ρ = 0 the corner pixel has J = [1269 1269; 1269 1269]: \mu_1 = 2539, \mu_2 = 0, coherence 1: an “edge” (one diagonal gradient). The Harris response is never positive, so no corners are found. Already at ρ = 0.5 the four corners are back, at (32, 32), (95, 32), (32, 95) and (95, 95): a window of a few pixels is enough to contain gradients from both edges.
E4. ρ = 1: speckled colours and many grey pixels: each window is too small to average out the noise. Coherence at (30, 64), (62, 64), (96, 64): 0.98, 0.31, 0.97. ρ = 3: clean, uniform colours on both sides: 0.94, 0.05, 0.94. ρ = 8: still clean, but the boundary becomes a wide grey band of low coherence: 0.93, 0.01, 0.92 (the windows near the boundary mix both orientations). ρ trades noise against spatial resolution.
E5. Orientation 106°, 120°, 0°, 60°, 74° at x = 16, 32, 64, 96, 112 (coherence 0.92 to 0.99): the hue changes continuously across the image, following the turning stripes (0° = horizontal stripes in the middle).
E6. 35 corners: the 21 inner corners of the checkerboard (3 columns × 7 rows, where four squares meet), corners along the checkerboard’s right border, the four corners of the square and the three of the triangle. Raising the threshold to 0.5 changes nothing here: all corners of these clean shapes are strong. A larger k penalises the trace more; at k = 0.2 the triangle’s sharp top corner (51°) disappears first (34 corners): its two edges are close to parallel as axes, so \mu_2 is small compared with \mu_1. Right angles and the four-square corners of the checkerboard are the strongest corners.
E7. The colour turns around the centre (the orientation follows the rings), with high coherence (0.95 or more) everywhere except near the centre: 0.00 at the centre, 0.08 four pixels away, 0.49 eight pixels away. There the rings are small and strongly curved, and a window contains every orientation.
E8. Oriented: the membranes, the fibres in the cytoplasm and parts of the nuclear envelope; isotropic: the granular inside of the nucleus and the background texture. At (94, 126) on the envelope the coherence is 0.38 (the envelope is thin and curved, with texture around it); inside the nucleus at (150, 150) only 0.02.
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 edges/src/structure_tensor/exercise.rs. The Gaussian blur and the gradient of the edges unit are given, ready to use.
C1. tensor_of_gradients(grads): the structure tensor of a window by hand, the plain average of \mathbf g\mathbf g^\top over its gradient vectors. The checks are B1 and B2.
C2. eigen_tensor(j) and coherence(mu1, mu2):
μ1, μ2 = (a + c)/2 ± sqrt( ((a − c)/2)² + b² ) # μ1 ≥ μ2
θ = ½ atan2(2b, a − c) # dominant gradient direction, y down
coherence = ((μ1 − μ2) / (μ1 + μ2))², 0 if μ1 + μ2 = 0
The check is B3.
C3. harris(j, k): \det J - k\,(\operatorname{tr}J)^2. The check is B4.
C4. structure_tensor(img, sigma, rho): the tensor at every pixel.
Lx, Ly = gradient of I at scale σ
Jxx = Lx² blurred with a Gaussian of width ρ (no blur if ρ = 0)
Jxy = Lx·Ly blurred with ρ
Jyy = Ly² blurred with ρ
The check is a bright square: one large eigenvalue on its edge, two at its corner, none inside, and \mu_2 = 0 everywhere when ρ = 0.
C5. corners(response, threshold): the local maxima of the Harris response above a threshold, with a rule for ties (two equal neighbouring values: keep the first, row by row). The check finds the four corners of the square.
Then cargo run -p edges -- structure-tensor and open the pictures in out/structure-tensor/. Grey levels are 0 … 255. In the orientation maps, hue is the orientation, saturation the coherence and brightness the energy, as in the demo.
C6. Read the printed J, eigenvalues and coherence at the edge, the corner and the inside of the square (σ = 1, ρ = 3); compare with B5 and demo question E1. Then compare stripes-mean-gradient.png (the averaged gradient, coloured by its direction) with stripes-orientation.png, and the printed length of the mean gradient with \sqrt{\mu_1}.
C7. In rings-orientation.png, how often does the hue go around the colour wheel on one trip around the centre of the rings, and why? Read the printed coherence on the rings, at their centre and on the blotchy texture.
C8. Count the corners in corners.png. Which corners of the checkerboard are found, and what about the disc? The checkerboard’s inner corners have exactly equal responses at two neighbouring pixels: what would a “strictly larger than every neighbour” rule do there?
The model solution is edges/src/structure_tensor/solution.rs in the download.
C6. Edge (32, 64): J = [966 0; 0 0], \mu_1 = 966, \mu_2 = 0, coherence 1.00, gradient at 0° (across the vertical edge), Harris −46 659. Corner (32, 32): J = [478 106; 106 478], \mu_1 = 584, \mu_2 = 372, coherence 0.05, Harris 171 729. Inside: all 0. As in B5: a thin ellipse at the edge, a large round one at the corner, a dot inside. On the stripes the mean gradient has length 2.64, against \sqrt{\mu_1} = 33.3: the gradients are strong but cancel, so the mean-gradient picture is almost black. The structure tensor gives one uniform colour (coherence 0.97 at the centre, structure at 120° counter-clockwise on the screen: the stripes run perpendicular to their 30° gradient).
C7. Twice. The hue shows the orientation, an axis: 180° is once around the wheel. Going once around the centre, the orientation of the rings turns by 360°, so the hue goes around twice. Coherence 0.94 on the rings, 0.00 at their centre (every orientation in one window), 0.27 on the isotropic texture (grey and speckled colours in the map).
C8. 54 corners: the four of the square, the three of the triangle, none on the disc (its outline turns smoothly; no window has two clear directions), and on the checkerboard the 25 inner corners where four squares meet plus the 22 outer corners along its border. At an inner corner the response is the same at two neighbouring pixels, by symmetry; with “strictly larger” each rules the other out and no inner corner is found at all: with that rule this program finds only 29 corners.
Where this leads
The day’s tools (Gaussian derivatives, LoG/DoG, Hessian and structure-tensor eigenvalues at several scales) come back as the feature stack of pixel classifiers on the random-forest day (pixel classification); corners and DoG blobs as interest points in registration (keypoints); the structure tensor of a window as the Lucas–Kanade system of optical flow; edges in the Hough day.